Skip to content

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

TypeScript

perf(desktop): load recent chat history before older turns

Josué94475af51f44
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 0178b9e78..cffc632c0 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -537,6 +537,9 @@ export function App() {
activeMessages: vm.activeMessages,
groupedMessages: vm.groupedMessages,
chatMessagesLoading: vm.chatMessagesLoading,
+ hasOlderMessages: vm.hasOlderMessages,
+ olderMessagesLoading: vm.olderMessagesLoading,
+ handleLoadOlderMessages: vm.handleLoadOlderMessages,
activityByMessageId: vm.activityByMessageId,
progressByMessageId: vm.progressByMessageId,
}),
@@ -545,6 +548,9 @@ export function App() {
vm.activeMessages,
vm.groupedMessages,
vm.chatMessagesLoading,
+ vm.hasOlderMessages,
+ vm.olderMessagesLoading,
+ vm.handleLoadOlderMessages,
vm.activityByMessageId,
vm.progressByMessageId,
]
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index 8c9485362..010fba650 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -180,6 +180,9 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {
activeMessages,
groupedMessages,
chatMessagesLoading,
+ hasOlderMessages,
+ olderMessagesLoading,
+ handleLoadOlderMessages,
activeChatId,
activityByMessageId,
progressByMessageId,
@@ -448,6 +451,19 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {
data-testid="message-list"
className={`chat-thread ${isDedicatedAgentView ? 'chat-thread-dedicated' : ''}`}
>
+ {activeChatId && hasOlderMessages && (
+ <div className="chat-history-page-control">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={olderMessagesLoading}
+ onClick={() => void handleLoadOlderMessages()}
+ >
+ {olderMessagesLoading ? 'Loading older messages...' : 'Load older messages'}
+ </Button>
+ </div>
+ )}
{activeChatId &&
groupedWithKeys.map((group, groupIndex) => {
const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : null
diff --git a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
index 9ead00fad..13be252eb 100644
--- a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
+++ b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts
@@ -12,6 +12,9 @@ export interface ChatThreadStateContextValue {
activeMessages: AgentChatMessage[]
groupedMessages: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }>
chatMessagesLoading: boolean
+ hasOlderMessages: boolean
+ olderMessagesLoading: boolean
+ handleLoadOlderMessages: () => Promise<void>
activityByMessageId: Record<string, AgentMessageActivity>
progressByMessageId: Record<string, TaskProgress>
}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
index 12464c0b9..5a6fd148c 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
@@ -51,7 +51,9 @@ describe('BACK_ONLINE dispatcher (§4.1)', () => {
expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
'agent-x',
'agent-x',
- 'chat-offline'
+ 'chat-offline',
+ undefined,
+ { limit: 80 }
)
)
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
index 82ba91753..433d26290 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
@@ -71,7 +71,13 @@ describe('pendingChatSelection effect', () => {
})
await waitFor(() => expect(result.current.activeChatId).toBe('c-latest'))
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-latest')
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'c-latest',
+ undefined,
+ { limit: 80 }
+ )
})
it('latest → overrides an older visible chat when explicitly requested', async () => {
@@ -99,7 +105,13 @@ describe('pendingChatSelection effect', () => {
})
await waitFor(() => expect(result.current.activeChatId).toBe('c-newest'))
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-newest')
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'c-newest',
+ undefined,
+ { limit: 80 }
+ )
})
it('latest → does not override a chat auto-created while the list load is in flight', async () => {
@@ -190,7 +202,9 @@ describe('pendingChatSelection effect', () => {
expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
'agent-x',
'agent-x',
- 'c-specific'
+ 'c-specific',
+ undefined,
+ { limit: 80 }
)
)
await waitFor(() => expect(result.current.activeChatId).toBe('c-specific'))
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
index 07e598060..5cafe9e99 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx
@@ -63,8 +63,14 @@ describe('switchToChat (unified, D.4)', () => {
await result.current.switchToChat('agent-x', 'c1')
})
- expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'c1', undefined, undefined)
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c1')
+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'c1', 80, undefined)
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'c1',
+ undefined,
+ { limit: 80, afterTurn: 1 }
+ )
expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
expect(result.current.chatMessages).toHaveLength(2)
})
@@ -100,7 +106,7 @@ describe('switchToChat (unified, D.4)', () => {
expect(result.current.chatMessages).toHaveLength(60)
})
- it('Phase 2 overwrites a stale cache when the server has more turns and persists via replace', async () => {
+ it('Phase 2 appends only the missing server delta to a durable-ID cache', async () => {
clerum.chat.loadMessages.mockResolvedValue([
{ id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },
])
@@ -118,13 +124,136 @@ describe('switchToChat (unified, D.4)', () => {
})
expect(result.current.chatMessages).toHaveLength(4)
- expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
'agent-x',
'c2',
expect.arrayContaining([expect.objectContaining({ id: 'turn-2-assistant' })])
)
})
+ it('follows server delta pages until the active chat reaches the latest revision', async () => {
+ clerum.chat.loadMessages.mockResolvedValue([
+ { id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },
+ { id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },
+ ])
+ clerum.rpc.loadSessionMessages
+ .mockResolvedValueOnce({
+ agent: 'agent-x',
+ chatId: 'delta-pages',
+ state: 'idle',
+ totalTurns: 3,
+ latestTurnNumber: 2,
+ hasMoreAfter: true,
+ turns: [turn(2, 'q2', 'a2')],
+ })
+ .mockResolvedValueOnce({
+ agent: 'agent-x',
+ chatId: 'delta-pages',
+ state: 'idle',
+ totalTurns: 3,
+ latestTurnNumber: 3,
+ hasMoreAfter: false,
+ turns: [turn(3, 'q3', 'a3')],
+ })
+ const { result } = renderController()
+ await settleMount()
+
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'delta-pages')
+ })
+
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenNthCalledWith(
+ 1,
+ 'agent-x',
+ 'agent-x',
+ 'delta-pages',
+ undefined,
+ { limit: 80, afterTurn: 1 }
+ )
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenNthCalledWith(
+ 2,
+ 'agent-x',
+ 'agent-x',
+ 'delta-pages',
+ undefined,
+ { limit: 80, afterTurn: 2 }
+ )
+ expect(result.current.chatMessages).toHaveLength(6)
+ expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'delta-pages',
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'turn-2-assistant' }),
+ expect.objectContaining({ id: 'turn-3-assistant' }),
+ ])
+ )
+ })
+
+ it('loads older history on demand and prepends it without blocking first render', async () => {
+ const newestLocalPage = Array.from({ length: 80 }, (_, index) => ({
+ id: `turn-${index + 21}-user`,
+ role: 'user' as const,
+ content: `q${index + 21}`,
+ timestamp: index + 21,
+ }))
+ clerum.chat.loadMessages.mockImplementation(
+ async (_agentRef: string, _chatId: string, _limit?: number, offset?: number) =>
+ offset ? [] : newestLocalPage
+ )
+ clerum.rpc.loadSessionMessages
+ .mockResolvedValueOnce({
+ agent: 'agent-x',
+ chatId: 'older-pages',
+ state: 'idle',
+ totalTurns: 100,
+ hasMoreBefore: true,
+ hasMoreAfter: false,
+ turns: [],
+ })
+ .mockResolvedValueOnce({
+ agent: 'agent-x',
+ chatId: 'older-pages',
+ state: 'idle',
+ totalTurns: 100,
+ oldestTurnNumber: 1,
+ latestTurnNumber: 20,
+ hasMoreBefore: false,
+ hasMoreAfter: true,
+ turns: Array.from({ length: 20 }, (_, index) =>
+ turn(index + 1, `q${index + 1}`, `a${index + 1}`)
+ ),
+ })
+ const { result } = renderController()
+ await settleMount()
+
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'older-pages')
+ })
+
+ expect(result.current.chatMessages).toHaveLength(80)
+ expect(result.current.hasOlderMessages).toBe(true)
+
+ await act(async () => {
+ await result.current.handleLoadOlderMessages()
+ })
+
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'older-pages',
+ undefined,
+ { limit: 80, beforeTurn: 21 }
+ )
+ expect(result.current.chatMessages).toHaveLength(120)
+ expect(result.current.chatMessages[0]?.id).toBe('turn-1-user')
+ expect(result.current.hasOlderMessages).toBe(false)
+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'older-pages',
+ expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])
+ )
+ })
+
it('adds a server-only chat to the sidebar when switched to directly (S4)', async () => {
// chatList starts empty (default getIndex → no chats); simulate opening a
// notification for a chat the local list doesn't know about.
@@ -436,9 +565,9 @@ describe('switchToChat (unified, D.4)', () => {
await result.current.switchToChat('agent-x', 'z1')
})
- // With the zombie acked, the replace lands and both messages render.
+ // With the zombie acked, the missing durable assistant message is appended.
expect(result.current.chatMessages).toHaveLength(2)
- expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
'agent-x',
'z1',
expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])
@@ -527,9 +656,9 @@ describe('switchToChat (unified, D.4)', () => {
await result.current.switchToChat('agent-x', 'pa')
})
- // The retry landed the durable reply: replace fired, zombie acked, NOT offline.
+ // The retry landed the durable reply: delta appended, zombie acked, NOT offline.
expect(result.current.chatMessages).toHaveLength(2)
- expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
'agent-x',
'pa',
expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])
@@ -649,9 +778,9 @@ describe('switchToChat (unified, D.4)', () => {
await sw
})
- // The residual (task-pb) was acked and the durable reply replaced the cache.
+ // The residual was acked and the durable reply was appended to the cache.
expect(result.current.chatMessages).toHaveLength(2)
- expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
'agent-x',
'pb',
expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
index ebc376dbe..9a5ce7139 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
@@ -70,7 +70,13 @@ describe('useAgentChatController — characterization (D.0)', () => {
expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-1')
// Phase 2 now always reconciles with the server.
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'chat-1')
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'chat-1',
+ undefined,
+ { limit: 80 }
+ )
// Cache was up to date → no overwrite, no rejoin.
expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
expect(result.current.chatMessages).toHaveLength(3)
@@ -100,7 +106,13 @@ describe('useAgentChatController — characterization (D.0)', () => {
await result.current.switchToChat('agent-x', 'chat-2')
})
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'chat-2')
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'chat-2',
+ undefined,
+ { limit: 80 }
+ )
expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'chat-2')
// Server is source of truth → replace, not append.
expect(clerum.chat.replaceMessages).toHaveBeenCalled()
@@ -725,8 +737,8 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
})
- // The durable reply lands; no error/resend, no zombie blocking the replace.
- await waitFor(() => expect(clerum.chat.replaceMessages).toHaveBeenCalled())
+ // The durable reply lands as a delta; no error/resend and no zombie block.
+ await waitFor(() => expect(clerum.chat.appendMessages).toHaveBeenCalled())
expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
expect(result.current.failedAgentSend).toBeNull()
await sendPromise
diff --git a/desktop-app/ui/src/hooks/domain/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
index 404a1f0fc..57fa7ab90 100644
--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts
+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
@@ -1,5 +1,5 @@
import { parseTaskKey } from '@contexts/AgentTaskTrackerContext'
-import type { SessionMessagesResult } from '../../../../src/types'
+import type { SessionMessagesQuery, SessionMessagesResult } from '../../../../src/types'
import type { SessionFsmStore } from './sessionFsm'
/**
@@ -38,7 +38,11 @@ export type ReconcileOutcome =
export interface ReconcileChatDeps {
fsm: SessionFsmStore
/** Fetch the durable server session state (turns + recovery fields). */
- loadSessionMessages: (agentRef: string, chatId: string) => Promise<SessionMessagesResult>
+ loadSessionMessages: (
+ agentRef: string,
+ chatId: string,
+ query?: SessionMessagesQuery
+ ) => Promise<SessionMessagesResult>
/**
* Server reports a live (`processing`/`awaiting_approval`) task: seed the
* snapshot and attach a stream via the coordinator. Returns the outcome
@@ -87,6 +91,8 @@ export interface ReconcileChatArgs {
reason: string
/** The task this reconcile is settling — drives the idle durable fallback. */
taskIdHint?: string
+ /** Bounded page or delta request used by the authoritative transcript fetch. */
+ messagesQuery?: SessionMessagesQuery
/**
* Per-call relevance guard (in addition to the dep-level `isStillRelevant` and
* the `reset()` generation). A `switchToChat`-initiated reconcile passes the
@@ -147,12 +153,13 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
async function fetchWithRetry(
agentRef: string,
chatId: string,
- stillRelevant: () => boolean
+ stillRelevant: () => boolean,
+ query?: SessionMessagesQuery
): Promise<SessionMessagesResult | undefined> {
for (let attempt = 0; attempt < attempts; attempt++) {
if (!stillRelevant()) return undefined
try {
- return await deps.loadSessionMessages(agentRef, chatId)
+ return await deps.loadSessionMessages(agentRef, chatId, query)
} catch (err) {
// Non-network (404, etc.) rethrows to the branch handler; a network blip
// is retried with backoff up to the cap (mirrors switchToChat P2-A).
@@ -179,7 +186,7 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
deps.fsm.dispatch(chatKey, { type: 'RECONCILE_STARTED' })
let outcome: ReconcileOutcome = 'noop'
try {
- const resp = await fetchWithRetry(agentRef, chatId, stillRelevant)
+ const resp = await fetchWithRetry(agentRef, chatId, stillRelevant, args.messagesQuery)
if (!resp) {
outcome = 'noop'
return outcome
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index a3cd94806..024418158 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -17,6 +17,7 @@ import type {
HostActivityStreamEvent,
HostMessageAttachment,
MessageToolStep,
+ SessionMessagesQuery,
} from '../../../../src/types'
import type { SessionMessagesResult } from '../../../../src/types'
import { DESKTOP_ROUTES } from '../../constants/navigation'
@@ -98,6 +99,27 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100
* persisted `toolSteps` (#582 fallback in ChatThread).
*/
const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50
+const MESSAGE_PAGE_SIZE = 80
+
+function serverTurnNumber(message: AgentChatMessage): number | undefined {
+ if (message.serverTurnNumber !== undefined) return message.serverTurnNumber
+ const match = /^turn-(\d+)-(?:user|assistant)$/.exec(message.id)
+ return match ? Number(match[1]) : undefined
+}
+
+function mergeUniqueMessages(
+ existing: AgentChatMessage[],
+ incoming: AgentChatMessage[],
+ position: 'before' | 'after' = 'after'
+): AgentChatMessage[] {
+ const source = position === 'before' ? [...incoming, ...existing] : [...existing, ...incoming]
+ const seen = new Set<string>()
+ return source.filter(message => {
+ if (seen.has(message.id)) return false
+ seen.add(message.id)
+ return true
+ })
+}
/** Keep only the last `n` insertion-ordered keys of a per-message map. Returns the
* same reference when already within the cap (so React state stays identity-stable). */
@@ -258,6 +280,9 @@ export function useAgentChatController({
} = chatListCtl
const [chatMessages, setChatMessages] = useState<AgentChatMessage[]>([])
const [chatMessagesLoading, setChatMessagesLoading] = useState(false)
+ const [hasOlderMessages, setHasOlderMessages] = useState(false)
+ const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)
+ const loadedLocalMessageCountRef = useRef(0)
const [activityByAgentMessage, setActivityByAgentMessage] = useState<
Record<string, Record<string, AgentMessageActivity>>
@@ -304,7 +329,11 @@ export function useAgentChatController({
// (assigned in an effect, not the render body — R-F12) so the instance stays
// stable while the closures it calls track the latest state.
const reconcileBranchesRef = useRef<{
- loadSessionMessages: (agentRef: string, chatId: string) => Promise<SessionMessagesResult>
+ loadSessionMessages: (
+ agentRef: string,
+ chatId: string,
+ query?: SessionMessagesQuery
+ ) => Promise<SessionMessagesResult>
attachLiveTask: ReconcileChatDeps['attachLiveTask']
settleIdle: ReconcileChatDeps['settleIdle']
evictChat: ReconcileChatDeps['evictChat']
@@ -313,8 +342,8 @@ export function useAgentChatController({
if (!reconcileChatRef.current) {
reconcileChatRef.current = createReconcileChat({
fsm,
- loadSessionMessages: (agentRef, chatId) =>
- reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId),
+ loadSessionMessages: (agentRef, chatId, query) =>
+ reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId, query),
attachLiveTask: (chatKey, resp, epoch, stillRelevant) =>
reconcileBranchesRef.current!.attachLiveTask(chatKey, resp, epoch, stillRelevant),
settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>
@@ -578,13 +607,24 @@ export function useAgentChatController({
// Clear the reply-notification dedupe set so taskIds don't accumulate across
// login/logout / team-switch cycles (security review, hygiene).
resetReplyNotificationDedupe()
+ chatStore.clearCachedRemoteData()
setChatMessages([])
setChatMessagesLoading(false)
+ setHasOlderMessages(false)
+ setOlderMessagesLoading(false)
+ loadedLocalMessageCountRef.current = 0
// The error/resend banner is per-chat view state — drop it when the active
// chat is torn down (logout / unauth boot) so it can't survive into the next.
setAgentError(null)
setFailedAgentSend(null)
- }, [resetComposerAttachments, clearList, tracker, fsm, resetReplyNotificationDedupe])
+ }, [
+ resetComposerAttachments,
+ clearList,
+ tracker,
+ fsm,
+ resetReplyNotificationDedupe,
+ chatStore.clearCachedRemoteData,
+ ])
// Unified switch (post-D.4): cache-first render → server reconcile → tracker
// rejoin. No `isRemote` branch — the server is the source of truth for every
@@ -600,6 +640,8 @@ export function useAgentChatController({
setActiveChatId(chatId)
setChatMessages([])
setChatMessagesLoading(true)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
// 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
@@ -617,11 +659,14 @@ export function useAgentChatController({
// approval on a NON-visible chat — is never subject to an active-chat guard.
const isStillActive = () => activeChatVisibilityRef.current.activeChatId === chatId
- // PHASE 1 — local cache (instant render, no RPC). Load the full cache (no
- // cap): the reconcile compares its length against the full server history,
- // so a windowed slice would falsely look "stale" on long chats.
- const cached = await chatStore.loadMessages(agentRef, chatId).catch(() => [])
+ // PHASE 1 — render only the newest local page. The authoritative reconcile
+ // below requests a delta after the newest cached server turn.
+ const cached = await chatStore
+ .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
+ .catch(() => [])
if (!isStillActive()) return
+ loadedLocalMessageCountRef.current = cached.length
+ setHasOlderMessages(cached.length === MESSAGE_PAGE_SIZE)
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
@@ -653,19 +698,26 @@ export function useAgentChatController({
// itself no longer needs a taskId to match (R2's epoch replaces the old
// `recoveringTaskIdByKeyRef` bookkeeping).
//
- // Note (accepted): the gate re-reads `loadMessages` inside its hydrate, so a
- // switch reads the cache twice (Phase 1 + hydrate). The extra IPC is cheap
- // and the hydrate's length-compare self-heals if an SSE terminal appended
- // between the two reads (the next reconcile lands the fuller view). Note
+ // 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 = cached.reduce<number | undefined>((latest, message) => {
+ const current = serverTurnNumber(message as AgentChatMessage)
+ return current === undefined ? latest : Math.max(latest ?? 0, current)
+ }, undefined)
await reconcileChat(key, {
reason: 'switch_to_chat',
taskIdHint: zombieBefore?.taskId,
isRelevant: isStillActive,
+ messagesQuery: {
+ limit: MESSAGE_PAGE_SIZE,
+ ...(latestCachedTurn !== undefined ? { afterTurn: latestCachedTurn } : {}),
+ },
})
},
[
@@ -711,6 +763,67 @@ export function useAgentChatController({
[selectedAgent, switchToChat]
)
+ const handleLoadOlderMessages = useCallback(async () => {
+ if (!selectedAgent || !activeChatId || olderMessagesLoading) return
+ setOlderMessagesLoading(true)
+ try {
+ const visibleIds = new Set(chatMessages.map(message => message.id))
+ const localPage = (await chatStore
+ .loadMessages(
+ selectedAgent,
+ activeChatId,
+ MESSAGE_PAGE_SIZE,
+ loadedLocalMessageCountRef.current
+ )
+ .catch(() => [])) as AgentChatMessage[]
+ const unseenLocal = localPage.filter(message => !visibleIds.has(message.id))
+ if (unseenLocal.length) {
+ loadedLocalMessageCountRef.current += localPage.length
+ setChatMessages(previous => mergeUniqueMessages(previous, unseenLocal, 'before'))
+ setHasOlderMessages(localPage.length === MESSAGE_PAGE_SIZE)
+ return
+ }
+
+ const oldestTurn = chatMessages.reduce<number | undefined>((oldest, message) => {
+ const current = serverTurnNumber(message)
+ return current === undefined ? oldest : Math.min(oldest ?? current, current)
+ }, undefined)
+ if (oldestTurn === undefined || oldestTurn <= 1) {
+ setHasOlderMessages(false)
+ return
+ }
+
+ const response = await chatStore.loadSessionMessages(
+ selectedAgent,
+ selectedAgent,
+ activeChatId,
+ { limit: MESSAGE_PAGE_SIZE, beforeTurn: oldestTurn }
+ )
+ const older = turnsToChatMessages(response.turns) as AgentChatMessage[]
+ const merged = mergeUniqueMessages(chatMessages, older, 'before')
+ setChatMessages(merged)
+ await chatStore.replaceMessages(selectedAgent, activeChatId, merged)
+ loadedLocalMessageCountRef.current = merged.length
+ setHasOlderMessages(Boolean(response.hasMoreBefore))
+ } catch (error) {
+ console.warn('[chat-history] failed to load older messages', {
+ agentRef: selectedAgent,
+ chatId: activeChatId,
+ error,
+ })
+ } finally {
+ setOlderMessagesLoading(false)
+ }
+ }, [
+ activeChatId,
+ chatMessages,
+ chatStore.loadMessages,
+ chatStore.loadSessionMessages,
+ chatStore.replaceMessages,
+ olderMessagesLoading,
+ selectedAgent,
+ ])
+
// Agent selection → load chats
useEffect(() => {
if (!selectedAgent) {
@@ -725,6 +838,8 @@ export function useAgentChatController({
setChatListLoading(false)
setChatMessages([])
setChatMessagesLoading(false)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
return
}
@@ -740,6 +855,8 @@ export function useAgentChatController({
setActiveChatId(requestedSelection.chatId)
setChatMessages([])
setChatMessagesLoading(true)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
if (requestedSelection.title) {
upsertProvisionalEntry(
requestedSelection.chatId,
@@ -757,6 +874,8 @@ export function useAgentChatController({
setActiveChatId(null)
setChatMessages([])
setChatMessagesLoading(false)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
}
setChatListLoading(true)
;(async () => {
@@ -1033,9 +1152,10 @@ export function useAgentChatController({
// `reconcileBranchesRef` (assigned in the effect below), keeping the gate
// instance — and its coalescing state — stable across renders.
- // Shared hydration (§4.3 / A.4.4): materialize the server's turns into the
- // active view + persist (replace-never-append, D.4 §6.2), auto-title a fresh
- // hydration from the first user turn (empty cache), and upsert the sidebar (S4).
+ // Shared hydration (§4.3 / A.4.4): materialize the server's page into the
+ // active view, append a delta when the cache has durable server turn IDs, or
+ // replace once when migrating a legacy/random-ID cache. It also auto-titles a
+ // fresh hydration from turn one and upserts the sidebar (S4).
// Both reconcile branches use it: `settleIdle` (idle replace) and
// `attachLiveTask` (render in-flight turns so a rejoin can anchor to the
// rendered user bubble — P1-A). Returns the rendered set + whether it replaced,
@@ -1055,23 +1175,45 @@ export function useAgentChatController({
return v.selectedAgent === agentRef && v.activeChatId === chatId
}
const cached = (await chatStore
- .loadMessages(agentRef, chatId)
+ .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
.catch(() => [])) as AgentChatMessage[]
if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }
const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]
- if (hydrated.length <= cached.length) return { rendered: cached, replaced: false, cached }
+ if (!hydrated.length) return { rendered: cached, replaced: false, cached }
+ const cachedHasServerTurns = cached.some(message => serverTurnNumber(message) !== undefined)
+ if (!cachedHasServerTurns) {
+ setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))
+ }
+ if (!cachedHasServerTurns && cached.length > 0) {
+ const responseContainsAllTurns =
+ resp.totalTurns === undefined || resp.totalTurns === resp.turns.length
+ if (responseContainsAllTurns && hydrated.length <= cached.length) {
+ return { rendered: cached, replaced: false, cached }
+ }
+ }
+ const newMessages = hydrated.filter(message => !cached.some(item => item.id === message.id))
+ if (!newMessages.length) return { rendered: cached, replaced: false, cached }
const hydratedWithAttachments = withResponseFileAttachments(
- hydrated,
+ newMessages,
taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : []
)
if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }
- setChatMessages(hydratedWithAttachments)
+ const rendered = cachedHasServerTurns
+ ? mergeUniqueMessages(cached, hydratedWithAttachments)
+ : hydratedWithAttachments
+ setChatMessages(rendered)
const meta = await chatStore.createChat(agentRef, chatId)
- await chatStore.replaceMessages(agentRef, chatId, hydratedWithAttachments)
+ if (cachedHasServerTurns) {
+ await chatStore.appendMessages(agentRef, chatId, hydratedWithAttachments)
+ loadedLocalMessageCountRef.current += hydratedWithAttachments.length
+ } else {
+ await chatStore.replaceMessages(agentRef, chatId, rendered)
+ loadedLocalMessageCountRef.current = rendered.length
+ }
// Auto-title a fresh hydration (empty cache) from the first user turn, so a
// server-only chat doesn't keep its "Chat <id>" placeholder (A.4.4 / S4).
let title = meta.title
- if (cached.length === 0) {
+ if (cached.length === 0 && (resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1) {
const firstUserInput = resp.turns.find(t => t.user_input?.trim())?.user_input?.trim() || ''
const hydratedTitle =
firstUserInput.length > 60
@@ -1086,10 +1228,11 @@ export function useAgentChatController({
// S4: upsert into the sidebar. A chat opened via a notification for the
// already-selected agent may not be in chatList yet; a bare `.map` drops it.
upsertHydratedEntry(meta, title)
- return { rendered: hydratedWithAttachments, replaced: true, cached }
+ return { rendered, replaced: true, cached }
},
[
tracker,
+ chatStore.appendMessages,
chatStore.loadMessages,
chatStore.createChat,
chatStore.replaceMessages,
@@ -1272,8 +1415,37 @@ export function useAgentChatController({
useEffect(() => {
reconcileBranchesRef.current = {
- loadSessionMessages: (agentRef, chatId) =>
- chatStore.loadSessionMessages(agentRef, agentRef, chatId),
+ loadSessionMessages: async (agentRef, chatId, query) => {
+ const requestedQuery = query ?? { limit: MESSAGE_PAGE_SIZE }
+ let response = await chatStore.loadSessionMessages(
+ agentRef,
+ agentRef,
+ chatId,
+ requestedQuery
+ )
+ if (requestedQuery.afterTurn === undefined || !response.hasMoreAfter) {
+ return response
+ }
+
+ const turns = [...response.turns]
+ const seenCursors = new Set<number>()
+ let cursor = response.latestTurnNumber ?? turns.at(-1)?.number
+ while (response.hasMoreAfter && cursor !== undefined && !seenCursors.has(cursor)) {
+ seenCursors.add(cursor)
+ response = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
+ limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,
+ afterTurn: cursor,
+ })
+ turns.push(...response.turns)
+ cursor = response.latestTurnNumber ?? response.turns.at(-1)?.number
+ }
+ return {
+ ...response,
+ turns,
+ oldestTurnNumber: turns[0]?.number,
+ latestTurnNumber: turns.at(-1)?.number,
+ }
+ },
attachLiveTask: reconcileAttachLiveTask,
settleIdle: reconcileSettleIdle,
evictChat: reconcileEvictChat,
@@ -2274,6 +2446,8 @@ export function useAgentChatController({
setActiveChatId(chatId)
setChatMessages([])
setChatMessagesLoading(true)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
if (options.title) {
upsertProvisionalEntry(chatId, options.title, options.isRemote === true)
}
@@ -2289,6 +2463,8 @@ export function useAgentChatController({
setActiveChatId(null)
setChatMessages([])
setChatMessagesLoading(false)
+ setHasOlderMessages(false)
+ loadedLocalMessageCountRef.current = 0
// Deselecting the active chat (e.g. team switch) must also drop its per-chat
// error/resend banner so it doesn't bleed into the next active chat.
setAgentError(null)
@@ -2326,6 +2502,8 @@ export function useAgentChatController({
latestChatSessionsLoading,
chatMessages,
chatMessagesLoading,
+ hasOlderMessages,
+ olderMessagesLoading,
sessionStateByChatKey,
sessionStateByChatId,
// Fase 2b (§4.7.4): the app-shell builds the central `decideApproval` bound to
@@ -2353,6 +2531,7 @@ export function useAgentChatController({
handleDeleteChat,
handleDeleteChatForAgent,
handleSelectChat,
+ handleLoadOlderMessages,
handleSendAgentMessage,
handleRetryFailedAgentSend,
clearComposerSendError,
diff --git a/desktop-app/ui/src/hooks/sessionAdapter.ts b/desktop-app/ui/src/hooks/sessionAdapter.ts
index 321dfee09..679c7368d 100644
--- a/desktop-app/ui/src/hooks/sessionAdapter.ts
+++ b/desktop-app/ui/src/hooks/sessionAdapter.ts
@@ -27,6 +27,7 @@ export function turnsToChatMessages(turns: ServerTurn[]): ChatMessage[] {
role: 'user',
content: userDisplay.content,
timestamp: Date.parse(t.started_at),
+ serverTurnNumber: t.number,
...(userDisplay.attachments.length ? { attachments: userDisplay.attachments } : {}),
})
if (t.response !== undefined) {
@@ -37,6 +38,7 @@ export function turnsToChatMessages(turns: ServerTurn[]): ChatMessage[] {
role: 'assistant',
content: t.response,
timestamp: Date.parse(t.completed_at ?? t.started_at),
+ serverTurnNumber: t.number,
...(t.tokens ? { tokens: t.tokens } : {}),
// #582: carry the turn's tools so the progress stepper's "N tools" view
// survives a reload / cold-load (live SSE steps are renderer-only).
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index e18a88de2..ddff0e45a 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -1098,6 +1098,8 @@ export function useAppController() {
latestChatSessionsLoading: chat.latestChatSessionsLoading,
chatMessages: chat.chatMessages,
chatMessagesLoading: chat.chatMessagesLoading,
+ hasOlderMessages: chat.hasOlderMessages,
+ olderMessagesLoading: chat.olderMessagesLoading,
composerImageAttachments: chat.composerImageAttachments,
composerReferenceAttachments: chat.composerReferenceAttachments,
agentSending: chat.agentSending,
@@ -1114,6 +1116,7 @@ export function useAppController() {
handleDeleteChat: chat.handleDeleteChat,
handleDeleteChatForAgent: chat.handleDeleteChatForAgent,
handleSelectChat: chat.handleSelectChat,
+ handleLoadOlderMessages: chat.handleLoadOlderMessages,
handleSendAgentMessage: chat.handleSendAgentMessage,
handleRetryFailedAgentSend: chat.handleRetryFailedAgentSend,
clearComposerSendError: chat.clearComposerSendError,
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index f8b665650..7ce5e7237 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -6043,6 +6043,12 @@ h3 {
gap: var(--space-2-5);
}
+.chat-history-page-control {
+ display: flex;
+ justify-content: center;
+ padding-block: var(--space-1);
+}
+
.chat-empty-state {
align-content: center;
justify-items: center;
diff --git a/desktop-app/ui/src/uiTypes.ts b/desktop-app/ui/src/uiTypes.ts
index 0139d11b1..d04aa2a76 100644
--- a/desktop-app/ui/src/uiTypes.ts
+++ b/desktop-app/ui/src/uiTypes.ts
@@ -62,6 +62,8 @@ export type AgentChatMessage = {
role: AgentChatRole
content: string
timestamp: number
+ /** Authoritative server turn ordinal used for delta reconciliation and paging. */
+ serverTurnNumber?: number
/** mcp-host task that produced/owns this message — used to rejoin after reload (D.3, v2). */
task_id?: string
attachments?: ChatMessageAttachment[]