Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): R1-H3 supersede stale chat reconciliation
Josué74bd85bd739d
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.tsindex feade5b0b..620df49de 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts@@ -201,6 +201,37 @@ describe('reconcileChat — single-flight', () => {expect(reconcile.isInFlight(chatKey)).toBe(false)})+ it('supersedes an old same-chat run and permits a fresh authoritative fetch', async () => {+ let resolveOld: (value: SessionMessagesResult) => void = () => {}+ const load = vi+ .fn<() => Promise<SessionMessagesResult>>()+ .mockImplementationOnce(+ () => new Promise<SessionMessagesResult>(resolve => (resolveOld = resolve))+ )+ .mockResolvedValueOnce(idleResp({ totalTurns: 2 }))+ const deps = buildDeps({+ loadSessionMessages: load as unknown as ReconcileChatDeps['loadSessionMessages'],+ })+ const reconcile = createReconcileChat(deps)++ const oldRun = reconcile(chatKey, { reason: 'first-open' })+ reconcile.supersede(chatKey)+ const freshRun = reconcile(chatKey, { reason: 'second-open' })++ await freshRun+ resolveOld(idleResp({ totalTurns: 1 }))+ await expect(oldRun).resolves.toBe('stale_drop')+ expect(load).toHaveBeenCalledTimes(2)+ expect(deps.settleIdle).toHaveBeenCalledTimes(1)+ expect(deps.settleIdle).toHaveBeenCalledWith(+ chatKey,+ expect.objectContaining({ totalTurns: 2 }),+ expect.any(Number),+ undefined,+ expect.any(Function)+ )+ })+it('drops a late 404 after reset instead of evicting the next session cache', async () => {let rejectLoad: (reason: unknown) => void = () => {}const load = vi.fn(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.tsxindex b9e0ba623..61746683d 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@@ -119,6 +119,47 @@ describe('switchToChat (unified, D.4)', () => {)})+ it('drops an old A response after A-B-A and uses the fresh same-chat reconcile', async () => {+ const sessionResult = (chatId: string, answer?: string) => ({+ agent: 'agent-x',+ chatId,+ state: 'idle' as const,+ turns: chatId === 'chat-a' ? [turn(1, 'question', answer)] : [],+ })+ let resolveOldA!: (value: ReturnType<typeof sessionResult>) => void+ const oldA = new Promise<ReturnType<typeof sessionResult>>(resolve => {+ resolveOldA = resolve+ })+ clerum.chat.loadMessages.mockResolvedValue([])+ clerum.rpc.loadSessionMessages+ .mockImplementationOnce(() => oldA)+ .mockResolvedValueOnce(sessionResult('chat-b'))+ .mockResolvedValueOnce(sessionResult('chat-a', 'fresh answer'))+ const { result } = renderController()+ await settleMount()++ let firstSwitch!: Promise<void>+ await act(async () => {+ firstSwitch = result.current.switchToChat('agent-x', 'chat-a')+ await waitFor(() => expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(1))+ })+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ await result.current.switchToChat('agent-x', 'chat-a')+ })+ resolveOldA(sessionResult('chat-a', 'stale answer'))+ await act(async () => {+ await firstSwitch+ })++ expect(result.current.activeChatId).toBe('chat-a')+ 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.rpc.loadSessionMessages).toHaveBeenCalledTimes(3)+ })+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/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.tsindex 96a6e2048..506361c48 100644--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts@@ -117,6 +117,8 @@ export interface ReconcileChat {(chatKey: string, args: ReconcileChatArgs): Promise<ReconcileOutcome>/** Whether a reconcile is currently in flight for the chat (single-flight). */isInFlight: (chatKey: string) => boolean+ /** Invalidate and detach the current run for one chat while leaving others alone. */+ supersede: (chatKey: string) => void/*** Abort every in-flight reconcile (logout / team-switch / renderer teardown):* bumps a generation so any run past its next relevance check bails BEFORE its@@ -145,6 +147,7 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {// at `settleIdle` time, so a hint that arrives before the fetch resolves is// still honoured (M6).const inFlightHint = new Map<string, string | undefined>()+ const chatGenerations = new Map<string, number>()const attempts = deps.networkRetryAttempts ?? DEFAULT_RETRY_ATTEMPTSconst backoff = deps.networkRetryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS// Bumped by `reset()`; a run started under an older generation is no longer@@ -175,11 +178,13 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {async function run(chatKey: string, args: ReconcileChatArgs): Promise<ReconcileOutcome> {const startGeneration = generation+ const startChatGeneration = chatGenerations.get(chatKey) ?? 0const { agentRef, chatId } = parseTaskKey(chatKey)// Relevant only while (a) no `reset()` happened since this run began AND (b)// the injected chat-level guard still holds.const stillRelevant = () =>generation === startGeneration &&+ (chatGenerations.get(chatKey) ?? 0) === startChatGeneration &&(deps.isStillRelevant?.(chatKey) ?? true) &&(args.isRelevant?.() ?? true)// R2 anchor: the epoch at the START of the fetch, so a snapshot that a newer@@ -236,7 +241,11 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {} finally {// RESET already tore the entry down on 404; re-dispatching FINISHED would// resurrect an empty entry, so skip the finalizer in that case.- if (outcome !== '404' && generation === startGeneration) {+ if (+ outcome !== '404' &&+ generation === startGeneration &&+ (chatGenerations.get(chatKey) ?? 0) === startChatGeneration+ ) {deps.fsm.dispatch(chatKey, { type: 'RECONCILE_FINISHED' })}deps.telemetry('stream_recovery', { reason: args.reason, outcome })@@ -268,10 +277,16 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {return promise}) as ReconcileChatreconcile.isInFlight = (chatKey: string) => inFlight.has(chatKey)+ reconcile.supersede = (chatKey: string) => {+ chatGenerations.set(chatKey, (chatGenerations.get(chatKey) ?? 0) + 1)+ inFlight.delete(chatKey)+ inFlightHint.delete(chatKey)+ }reconcile.reset = () => {generation += 1inFlight.clear()inFlightHint.clear()+ chatGenerations.clear()}return reconcile}diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex e871dc8d7..dc3c97bb8 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -471,6 +471,7 @@ export function useAgentChatController({navItem,selectedAgent,})+ const activeChatSwitchRequestRef = useRef<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@@ -745,6 +746,7 @@ export function useAgentChatController({...activeChatVisibilityRef.current,activeChatId: null,}+ activeChatSwitchRequestRef.current = nullautoSelectedChatIdRef.current = nullsetActiveChatId(null)clearList()@@ -787,6 +789,10 @@ export function useAgentChatController({// chat, and a task in flight is rejoined via the tracker D.3 already mounts.const switchToChat = useCallback(async (agentRef: string, chatId: string) => {+ const switchRequest = Symbol(`${agentRef}:${chatId}`)+ activeChatSwitchRequestRef.current = switchRequest+ const key = makeTaskKey(agentRef, chatId)+ reconcileChatRef.current!.supersede(key)activeChatVisibilityRef.current = {...activeChatVisibilityRef.current,activeChatId: chatId,@@ -807,7 +813,6 @@ export function useAgentChatController({setFailedAgentSend(null)await chatStore.setLastActive(agentRef, chatId)- const key = makeTaskKey(agentRef, chatId)unfillableServerGapUpperBoundsRef.current.delete(key)// Renderer-local relevance guard for a fast A→B→A switch: THIS switch's@@ -815,7 +820,14 @@ export function useAgentChatController({// `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 = () => activeChatVisibilityRef.current.activeChatId === chatId+ const isStillActive = () => {+ const visible = activeChatVisibilityRef.current+ return (+ activeChatSwitchRequestRef.current === switchRequest &&+ visible.selectedAgent === agentRef &&+ visible.activeChatId === chatId+ )+ }// PHASE 1 — render only the newest local page. The authoritative reconcile// below requests a delta after the newest cached server turn.