Skip to content

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

TypeScript

fix(desktop): preserve reconcile relevance through hydrate

Josuée539ae56f0ae
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 707f3ffbf..381199c4b 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
@@ -44,6 +44,14 @@ const turn = (n: number, user: string, response?: string) => ({
completed_at: response ? `2026-05-28T10:0${n}:05Z` : undefined,
})
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(resolvePromise => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
describe('switchToChat (unified, D.4)', () => {
it('Phase 1 renders the cache, Phase 2 reconciles, and preserves the cache when there is no diff', async () => {
const cached = [
@@ -160,6 +168,82 @@ describe('switchToChat (unified, D.4)', () => {
expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(3)
})
+ it('drops a superseded A reconcile parked inside hydration after A-B-A', async () => {
+ type Messages = Awaited<ReturnType<typeof clerum.chat.loadMessages>>
+ type SessionResult = Awaited<ReturnType<typeof clerum.rpc.loadSessionMessages>>
+ const staleFetch = deferred<SessionResult>()
+ const staleHydration = deferred<Messages>()
+ clerum.chat.loadMessages
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([])
+ .mockImplementationOnce(() => staleHydration.promise)
+ .mockResolvedValue([])
+ let agentAFetches = 0
+ clerum.rpc.loadSessionMessages.mockImplementation(
+ async (_hostRef: string, _agentRef: string, chatId: string) => {
+ if (chatId === 'chat-b') {
+ return {
+ agent: 'agent-x',
+ chatId: 'chat-b',
+ state: 'idle' as const,
+ turns: [],
+ }
+ }
+ agentAFetches += 1
+ return agentAFetches === 1
+ ? staleFetch.promise
+ : {
+ agent: 'agent-x',
+ chatId: 'chat-a',
+ state: 'idle' as const,
+ turns: [turn(1, 'question', 'fresh answer')],
+ }
+ }
+ )
+ const { result } = renderController()
+ await settleMount()
+ let staleSwitch!: Promise<void>
+ await act(async () => {
+ staleSwitch = result.current.switchToChat('agent-x', 'chat-a')
+ await waitFor(() => expect(agentAFetches).toBe(1))
+ })
+ await act(async () => {
+ staleFetch.resolve({
+ agent: 'agent-x',
+ chatId: 'chat-a',
+ state: 'idle',
+ turns: [turn(1, 'question', 'stale answer')],
+ })
+ await Promise.resolve()
+ })
+ await waitFor(() => expect(clerum.chat.loadMessages).toHaveBeenCalledTimes(3))
+
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'chat-b')
+ await result.current.switchToChat('agent-x', 'chat-a')
+ })
+ await waitFor(() =>
+ expect(result.current.chatMessages.map(message => message.content)).toContain('fresh answer')
+ )
+ const persistedBeforeStaleHydration = clerum.chat.replaceMessages.mock.calls.length
+
+ await act(async () => {
+ staleHydration.resolve([])
+ await staleSwitch
+ })
+
+ expect(result.current.chatMessages.map(message => message.content)).toContain('fresh answer')
+ expect(result.current.chatMessages.map(message => message.content)).not.toContain(
+ 'stale answer'
+ )
+ expect(clerum.chat.replaceMessages).toHaveBeenCalledTimes(persistedBeforeStaleHydration)
+ expect(
+ clerum.chat.replaceMessages.mock.calls.some(call =>
+ call[2].some(message => message.content === 'stale answer')
+ )
+ ).toBe(false)
+ })
+
it('does not overwrite a long chat whose cache already matches the server (no 50-cap false-stale)', async () => {
// 30 turns → 60 messages, well past any windowing limit.
const turns = Array.from({ length: 30 }, (_, i) => turn(i + 1, `q${i + 1}`, `a${i + 1}`))
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index ec52dc164..2e340e192 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -1414,8 +1414,14 @@ export function useAgentChatController({
async (
chatKey: TaskKey,
resp: SessionMessagesResult,
- taskIdHint: string | undefined
- ): Promise<{ rendered: AgentChatMessage[]; replaced: boolean; cached: AgentChatMessage[] }> => {
+ taskIdHint: string | undefined,
+ stillRelevant: () => boolean
+ ): Promise<{
+ rendered: AgentChatMessage[]
+ replaced: boolean
+ cached: AgentChatMessage[]
+ stale: boolean
+ }> => {
const { agentRef, chatId } = parseTaskKey(chatKey)
const isActive = () => {
const v = activeChatVisibilityRef.current
@@ -1438,12 +1444,19 @@ export function useAgentChatController({
(resp as ReconciliationMessagesResult)[DELTA_RECONCILIATION_WINDOW] === true
const hasOlderFromServer = !deltaWindow && Boolean(resp.hasMoreBefore)
const localMessages = mergeUniqueMessages(visible, cached)
+ const staleResult = (rendered: AgentChatMessage[] = localMessages) => ({
+ rendered,
+ replaced: false,
+ cached: localMessages,
+ stale: true,
+ })
+ if (!stillRelevant()) return staleResult()
if (!isActive() || tracker.get(chatKey)) {
- return { rendered: localMessages, replaced: false, cached: localMessages }
+ return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]
if (!hydrated.length) {
- return { rendered: localMessages, replaced: false, cached: localMessages }
+ return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
const localHasServerTurns = localMessages.some(
message => serverTurnNumber(message) !== undefined
@@ -1452,15 +1465,16 @@ export function useAgentChatController({
const responseContainsAllTurns =
resp.totalTurns === undefined || resp.totalTurns === resp.turns.length
if (responseContainsAllTurns && hydrated.length <= localMessages.length) {
- return { rendered: localMessages, replaced: false, cached: localMessages }
+ return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
}
const hydratedWithAttachments = withResponseFileAttachments(
hydrated,
taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : []
)
+ if (!stillRelevant()) return staleResult()
if (!isActive() || tracker.get(chatKey)) {
- return { rendered: localMessages, replaced: false, cached: localMessages }
+ return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
// Pre-paging caches have no server-turn identity, so ordinary local
// user/assistant rows cannot be compared safely with an authoritative
@@ -1469,26 +1483,30 @@ export function useAgentChatController({
// its optimistic bubbles remain visible until task-scoped reconciliation.
const replaceSettledLegacyCache =
localMessages.length > 0 && !localHasServerTurns && !resp.activeTaskId
- const rendered = localMessages.length && !replaceSettledLegacyCache
- ? mergeServerMessages(
- localMessages,
- hydratedWithAttachments,
- resp.activeTaskId ? new Set([resp.activeTaskId]) : undefined
- )
- : hydratedWithAttachments
+ const rendered =
+ localMessages.length && !replaceSettledLegacyCache
+ ? mergeServerMessages(
+ localMessages,
+ hydratedWithAttachments,
+ resp.activeTaskId ? new Set([resp.activeTaskId]) : undefined
+ )
+ : hydratedWithAttachments
const hasOlderAfterMerge =
hasOlderFromServer || nextServerBackfillBeforeTurn(rendered) !== undefined
+ if (!stillRelevant()) return staleResult(rendered)
if (latestPageFallback) {
setHasOlderMessages(hasOlderAfterMerge)
} else {
setHasOlderMessages(previous => previous || hasOlderAfterMerge)
}
if (sameMessageSequence(rendered, localMessages)) {
- return { rendered: localMessages, replaced: false, cached: localMessages }
+ return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
+ if (!stillRelevant()) return staleResult(rendered)
chatMessagesRef.current = rendered
setChatMessages(rendered)
const meta = await chatStore.createChat(agentRef, chatId)
+ if (!stillRelevant()) return staleResult(rendered)
if (resp.activeTaskId) {
await chatStore.replaceMessages(agentRef, chatId, rendered, {
activeTaskIds: [resp.activeTaskId],
@@ -1496,7 +1514,10 @@ export function useAgentChatController({
} else {
await chatStore.replaceMessages(agentRef, chatId, rendered)
}
- if (!isActive()) return { rendered, replaced: true, cached: localMessages }
+ if (!stillRelevant()) return staleResult(rendered)
+ if (!isActive()) {
+ return { rendered, replaced: true, cached: localMessages, stale: false }
+ }
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).
@@ -1509,6 +1530,7 @@ export function useAgentChatController({
: firstUserInput
if (hydratedTitle) {
await chatStore.renameChat(agentRef, chatId, hydratedTitle)
+ if (!stillRelevant()) return staleResult(rendered)
title = hydratedTitle
applyLatestTitle(agentRef, chatId, hydratedTitle)
}
@@ -1516,7 +1538,7 @@ 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, replaced: true, cached: localMessages }
+ return { rendered, replaced: true, cached: localMessages, stale: false }
},
[
tracker,
@@ -1547,11 +1569,13 @@ export function useAgentChatController({
// the chat to `awaiting_approval`, which — during hydrate's awaits — would
// let the sticky re-seed effect race in a `'<unknown>'`-anchored rejoin
// before this entry exists (P1-A regression).
- const { rendered } = await hydrateActiveChatFromServer(
+ const { rendered, stale } = await hydrateActiveChatFromServer(
chatKey as TaskKey,
resp,
- resp.activeTaskId
+ resp.activeTaskId,
+ stillRelevant
)
+ if (stale) return 'stale_drop'
// R-F13 / spec §4.5-3: the hydrate above yields (IPC round-trip). If a
// `reset()` (logout / team-switch) or a switch-away landed during that
// await, bail BEFORE re-opening a live stream — otherwise `tracker.attach`
@@ -1612,11 +1636,13 @@ export function useAgentChatController({
// Active chat → reflect any newly-persisted server turns into the visible
// view (replace-never-append parity with switchToChat Phase 2, A.4.4).
- const { replaced, cached } = await hydrateActiveChatFromServer(
+ const { replaced, cached, stale } = await hydrateActiveChatFromServer(
chatKey as TaskKey,
resp,
- taskIdHint
+ taskIdHint,
+ stillRelevant
)
+ if (stale) return 'stale_drop'
if (replaced) return 'reconcile_replaced'
// GAP-H1 durable fallback (rama 4): a task whose result the server never