Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): keep opened chat transcripts in memory on reopen
Alfredo Lopez432a458c48e1
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex 830d83e39..d88770196 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -47,7 +47,11 @@ export interface RenderControllerResult {* factory, so epoch comparisons in the controller are exercised for real.*/export function renderController(- overrides: Partial<ControllerParams> = {}+ overrides: Partial<ControllerParams> = {},+ options: {+ /** Called with the controller's return value on every render, for frame-level assertions. */+ onRender?: (value: ReturnType<typeof useAgentChatController>) => void+ } = {}): RenderControllerResult {const spies = {pushToast: vi.fn(),@@ -93,7 +97,7 @@ export function renderController((p: Partial<ControllerParams>) => {const hostAuthority = useHarnessHostAuthority()authority = hostAuthority- return useAgentChatController({+ const value = useAgentChatController({onHostAccessRevoked: hostAuthority.onHostAccessRevoked,onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,isHostAccessBlocked: hostAuthority.isHostAccessBlocked,@@ -101,6 +105,8 @@ export function renderController(hostAuthorityRevision: hostAuthority.revision,...p,} as ControllerParams)+ options.onRender?.(value)+ return value},{initialProps: params,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsxnew file mode 100644index 000000000..d8f573545--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx@@ -0,0 +1,468 @@+// @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.+ */+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, localIndex } 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)(+ '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],+ ['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 === '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)(+ "g. %s: a 'specific' open from another Host shows the remembered chat while the index loads",+ async host => {+ const otherHost = 'other-host'+ const disk = { 'chat-a': transcript('chat-a') }+ serveDisk(disk)+ const controller = mount(host, { agentNames: [host, otherHost] })+ await settleMount()+ await open(controller, host, 'chat-a')+ act(() => controller.rerender({ selectedAgent: otherHost, agentNames: [host, otherHost] }))+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith(otherHost))++ const hostIndex = deferred<ReturnType<typeof localIndex>>()+ const defaultIndex = clerum.chat.getIndex.getMockImplementation()+ clerum.chat.getIndex.mockImplementation((agentRef: string) =>+ agentRef === host ? hostIndex.promise : defaultIndex?.(agentRef)+ )+ const returnStart = frames.length+ act(() => controller.result.current.setPendingChatSelection(host, 'chat-a'))+ act(() => controller.rerender({ selectedAgent: host, agentNames: [host, otherHost] }))+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenLastCalledWith(host))+ // The index read (behind the deleted-chat cleanup on a rebind) is pending.+ expectOnlyTranscript(frames.slice(returnStart), 'chat-a', disk['chat-a'])++ const hostReadsBefore = clerum.rpc.loadSessionMessages.mock.calls.length+ await act(async () => {+ hostIndex.resolve(localIndex([{ id: 'chat-a', title: 'Chat A' }]))+ })+ await waitFor(() =>+ expect(clerum.rpc.loadSessionMessages.mock.calls.length).toBeGreaterThan(hostReadsBefore)+ )+ expect(lastHostReadChatId()).toBe('chat-a')+ expectOnlyTranscript(frames.slice(returnStart), 'chat-a', disk['chat-a'])+ }+ )++ it('stateless wake: a failed reconcile keeps the remembered transcript and holds nothing', async () => {+ const host = 'chatllm-stateless'+ 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+ })+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/transcriptMemo.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/transcriptMemo.test.tsnew file mode 100644index 000000000..9fe447911--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/transcriptMemo.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest'+import type { AgentChatMessage } from '../../../uiTypes'+import { createTranscriptMemo, transcriptMemoKey } from '../transcriptMemo'++const LIMITS = { maxChats: 2, maxMessages: 3, maxAttachmentBase64Chars: 10 }++function message(id: string, dataBase64?: string): AgentChatMessage {+ return {+ id,+ role: 'user',+ content: id,+ timestamp: 1,+ ...(dataBase64 !== undefined+ ? { attachments: [{ name: `${id}.png`, mimeType: 'image/png', dataBase64 }] }+ : {}),+ } as AgentChatMessage+}++function entry(...messages: AgentChatMessage[]) {+ return { messages, hasOlderMessages: false, loadedLocalMessageCount: messages.length }+}++const scopeA = 'true:env:user:team-1'+const scopeB = 'true:env:user:team-2'++describe('transcriptMemo', () => {+ it('returns the stored entry by reference', () => {+ const memo = createTranscriptMemo(LIMITS)+ const stored = entry(message('m1'))+ memo.set(transcriptMemoKey(scopeA, 'host-a', 'chat-1'), stored)+ expect(memo.get(transcriptMemoKey(scopeA, 'host-a', 'chat-1'))).toBe(stored)+ })++ it('evicts the least recently used chat, counting a get as a use', () => {+ const memo = createTranscriptMemo(LIMITS)+ const k1 = transcriptMemoKey(scopeA, 'host-a', 'chat-1')+ const k2 = transcriptMemoKey(scopeA, 'host-a', 'chat-2')+ const k3 = transcriptMemoKey(scopeA, 'host-a', 'chat-3')+ memo.set(k1, entry(message('m1')))+ memo.set(k2, entry(message('m2')))+ expect(memo.get(k1)).toBeDefined()+ memo.set(k3, entry(message('m3')))+ expect(memo.get(k2)).toBeUndefined()+ expect(memo.get(k1)).toBeDefined()+ expect(memo.get(k3)).toBeDefined()+ })++ it('keeps auth scopes apart', () => {+ const memo = createTranscriptMemo(LIMITS)+ memo.set(transcriptMemoKey(scopeA, 'host-a', 'chat-1'), entry(message('m1')))+ expect(memo.get(transcriptMemoKey(scopeB, 'host-a', 'chat-1'))).toBeUndefined()+ expect(memo.get(transcriptMemoKey(scopeA, 'host-a', 'chat-1'))).toBeDefined()+ })++ it('deleteAgent removes only that Host', () => {+ const memo = createTranscriptMemo(LIMITS)+ memo.set(transcriptMemoKey(scopeA, 'host-a', 'chat-1'), entry(message('m1')))+ memo.set(transcriptMemoKey(scopeA, 'host-b', 'chat-1'), entry(message('m2')))+ memo.deleteAgent('host-a')+ expect(memo.get(transcriptMemoKey(scopeA, 'host-a', 'chat-1'))).toBeUndefined()+ expect(memo.get(transcriptMemoKey(scopeA, 'host-b', 'chat-1'))).toBeDefined()+ })++ it('clear removes every entry', () => {+ const memo = createTranscriptMemo(LIMITS)+ const key = transcriptMemoKey(scopeA, 'host-a', 'chat-1')+ memo.set(key, entry(message('m1')))+ expect(memo.get(key)).toBeDefined()+ memo.clear()+ expect(memo.get(key)).toBeUndefined()+ })++ it.each([+ ['an empty transcript', entry()],+ ['a transcript longer than maxMessages', entry(...['a', 'b', 'c', 'd'].map(id => message(id)))],+ ['attachments above the base64 budget', entry(message('m1', '12345678901'))],+ ])('does not store %s, and drops the previous entry for that chat', (_label, rejected) => {+ const memo = createTranscriptMemo(LIMITS)+ const key = transcriptMemoKey(scopeA, 'host-a', 'chat-1')+ // Positive control: an entry at the limits is stored.+ memo.set(key, entry(message('m1', '1234567890'), message('m2'), message('m3')))+ expect(memo.get(key)).toBeDefined()+ memo.set(key, rejected)+ expect(memo.get(key)).toBeUndefined()+ })+})diff --git a/desktop-app/ui/src/hooks/domain/transcriptMemo.ts b/desktop-app/ui/src/hooks/domain/transcriptMemo.tsnew file mode 100644index 000000000..03eaed9f5--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/transcriptMemo.ts@@ -0,0 +1,79 @@+import type { AgentChatMessage } from '../../uiTypes'++/**+ * #1091 A9 — the last transcripts the user saw, so reopening a chat renders it+ * at once instead of clearing to a spinner while the disk cache and the Host are+ * read again. The disk check and the Host reconcile still run afterwards; this+ * only removes the blank window.+ */+export interface TranscriptMemoEntry {+ messages: AgentChatMessage[]+ hasOlderMessages: boolean+ loadedLocalMessageCount: number+}++export interface TranscriptMemo {+ get: (key: string) => TranscriptMemoEntry | undefined+ set: (key: string, entry: TranscriptMemoEntry) => void+ deleteAgent: (agentRef: string) => void+ clear: () => void+}++export interface TranscriptMemoLimits {+ maxChats: number+ maxMessages: number+ maxAttachmentBase64Chars: number+}++/** Key layout: auth scope, agentRef and chatId, NUL-separated. */+export function transcriptMemoKey(authScope: string, agentRef: string, chatId: string): string {+ return `${authScope}\u0000${agentRef}\u0000${chatId}`+}++function attachmentBase64Chars(messages: AgentChatMessage[]): number {+ let total = 0+ for (const message of messages) {+ for (const attachment of message.attachments ?? []) {+ total += attachment.dataBase64?.length ?? 0+ }+ }+ return total+}++export function createTranscriptMemo(limits: TranscriptMemoLimits): TranscriptMemo {+ // Map iteration order is insertion order, so the first key is the least+ // recently used one once `get` and `set` re-insert what they touch.+ const entries = new Map<string, TranscriptMemoEntry>()++ return {+ get(key) {+ const entry = entries.get(key)+ if (!entry) return undefined+ entries.delete(key)+ entries.set(key, entry)+ return entry+ },+ set(key, entry) {+ entries.delete(key)+ if (+ entry.messages.length === 0 ||+ entry.messages.length > limits.maxMessages ||+ attachmentBase64Chars(entry.messages) > limits.maxAttachmentBase64Chars+ ) {+ return+ }+ entries.set(key, entry)+ while (entries.size > limits.maxChats) {+ entries.delete(entries.keys().next().value!)+ }+ },+ deleteAgent(agentRef) {+ for (const key of entries.keys()) {+ if (key.split('\u0000')[1] === agentRef) entries.delete(key)+ }+ },+ clear() {+ entries.clear()+ },+ }+}diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 300f6b9e7..49052e7d0 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -100,6 +100,7 @@ import {projectSessionState,} from './sessionFsm'import { mapTrackerStatusToProgress, readApprovalInputPreview } from './trackerToProgress'+import { type TranscriptMemoEntry, createTranscriptMemo, transcriptMemoKey } from './transcriptMemo'import type { PushNotificationInput } from './types'import {type ChatListControllerHost,@@ -141,6 +142,13 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50const LOCAL_MESSAGE_PAGE_SIZE = 80const SERVER_TURN_PAGE_SIZE = 40+// #1091 A9: transcripts kept for instant reopen. The A/B harness reopens at most+// this many chats per Host, newest first, so the LRU never thrashes there.+const TRANSCRIPT_MEMO_LIMITS = {+ maxChats: 8,+ maxMessages: 3 * LOCAL_MESSAGE_PAGE_SIZE,+ maxAttachmentBase64Chars: 8 * 1024 * 1024,+}const MAX_RECONCILE_DELTA_PAGES = 5const FILE_REFERENCES_NOT_RECEIVED_MESSAGE ='The Host did not receive the selected Global Files; the message was sent without them.'@@ -592,6 +600,8 @@ export function useAgentChatController({if (lastRetentionScope.current === scope) returnlastRetentionScope.current = scopeclearAllComposerDrafts()+ // The memo key already carries the scope; this frees the previous scope's entries.+ transcriptMemoRef.current?.clear()sendScopeGeneration.current += 1agentSendSetupOwnerRef.current = nullagentSendInFlightRef.current = false@@ -620,6 +630,67 @@ 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.+ useEffect(() => {+ if (chatMessagesLoading || !activeChatId || !selectedAgent) 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,+ 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]+ )const activeChatSwitchRequestRef = useRef<symbol | null>(null)const activeChatSwitchKeyRef = useRef<string | null>(null)// Latest `pushToast` for the hoisted tracker callbacks (onTrackerTerminal reads@@ -946,6 +1017,7 @@ export function useAgentChatController({// login/logout / team-switch cycles (security review, hygiene).resetReplyNotificationDedupe()chatStore.clearCachedRemoteData()+ transcriptMemo.clear()setChatMessages([])setChatMessagesLoading(false)setHasOlderMessages(false)@@ -963,6 +1035,7 @@ export function useAgentChatController({resetReplyNotificationDedupe,chatStore.clearCachedRemoteData,cancelOlderMessagesLoad,+ transcriptMemo,])// Unified switch (post-D.4): cache-first render → server reconcile → tracker@@ -986,6 +1059,7 @@ export function useAgentChatController({activeChatSwitchRequestRef.current = switchRequestactiveChatSwitchKeyRef.current = switchKey}+ const remembered = canReuseActiveSwitch ? undefined : rememberedTranscript(agentRef, chatId)// A same-chat click must coalesce onto an already-running loud recovery.// Superseding it would discard the stream-loss caller that owns the Resend// or durable-result UX. Genuine chat changes still cancel stale work.@@ -997,13 +1071,7 @@ export function useAgentChatController({selectedAgent: agentRef,}setActiveChatId(chatId)- if (!canReuseActiveSwitch) {- setChatMessages([])- setChatMessagesLoading(true)- setHasOlderMessages(false)- cancelOlderMessagesLoad()- loadedLocalMessageCountRef.current = 0- }+ if (!canReuseActiveSwitch) presentSelectedTranscript(remembered)// 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@@ -1046,16 +1114,36 @@ export function useAgentChatController({} 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- loadedLocalMessageCountRef.current = cached.length- setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)- if (!canReuseActiveSwitch) setChatMessages(cached as AgentChatMessage[])+ // #1091 A9: the remembered transcript is already on screen. Keep it when+ // the disk page is its newest part (or the disk read returned nothing);+ // otherwise the disk page wins, e.g. a reply persisted while the chat was+ // hidden. The Host reconcile below runs in both cases.+ const keepRemembered =+ remembered !== undefined &&+ (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[])+ }+ }// Phase 1 rendered the cache → clear the blocking spinner. The reconcile// runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the// reconcile gate) instead.@@ -1120,7 +1208,8 @@ export function useAgentChatController({reconcileChat,scrollChatToBottom,clearUnreadInList,- cancelOlderMessagesLoad,+ rememberedTranscript,+ presentSelectedTranscript,chatStore.setLastActive,chatStore.loadMessages,chatStore.clearUnreadTerminal,@@ -1343,11 +1432,7 @@ export function useAgentChatController({selectedAgent,}setActiveChatId(requestedSelection.chatId)- setChatMessages([])- setChatMessagesLoading(true)- setHasOlderMessages(false)- cancelOlderMessagesLoad()- loadedLocalMessageCountRef.current = 0+ presentSelectedTranscript(rememberedTranscript(selectedAgent, requestedSelection.chatId))if (requestedSelection.title) {upsertProvisionalEntry(requestedSelection.chatId,@@ -1436,7 +1521,15 @@ export function useAgentChatController({return () => {cancelled = true}- }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent, isHostAccessBlocked])+ }, [+ cancelOlderMessagesLoad,+ currentTeamId,+ navItem,+ selectedAgent,+ isHostAccessBlocked,+ presentSelectedTranscript,+ rememberedTranscript,+ ])// ─── Activity / progress state updaters (hoisted from sendAgentMessage so the// tracker subscription effect and tracker callbacks can share them) ───@@ -1962,6 +2055,8 @@ export function useAgentChatController({reconcileChatRef.current?.supersede(chatKey)fsm.dispatch(chatKey, { type: 'RESET' })}+ // A held Host's transcripts must not reappear from memory once it is released.+ transcriptMemo.deleteAgent(agentRef)const stopActivity = activityUnsubByAgentRef.current[agentRef]if (stopActivity) {delete activityUnsubByAgentRef.current[agentRef]@@ -2003,6 +2098,7 @@ export function useAgentChatController({[tracker,fsm,+ transcriptMemo,hideAgent,chatStore.clearCachedRemoteData,clearList,@@ -3803,17 +3899,14 @@ export function useAgentChatController({selectedAgent: agentName,}setActiveChatId(chatId)- setChatMessages([])- setChatMessagesLoading(true)- setHasOlderMessages(false)- cancelOlderMessagesLoad()- loadedLocalMessageCountRef.current = 0+ presentSelectedTranscript(rememberedTranscript(agentName, chatId))if (options.title) {upsertProvisionalEntry(chatId, options.title, options.isRemote === true)}},[- cancelOlderMessagesLoad,+ presentSelectedTranscript,+ rememberedTranscript,currentTeamId,writePendingSelection,upsertProvisionalEntry,