Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-ui): r5-m4 remove redundant local page readiness flag
Josué2dc7e2581e89
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..dd5a1e50f 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from 'react'+import { type ReactNode, useLayoutEffect } from 'react'import { vi } from 'vitest'import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'import { act, renderHook } from '@testing-library/react'@@ -35,6 +35,11 @@ export interface RenderControllerResult {}}+export interface RenderControllerOptions {+ /** Observe committed controller state before its passive effects synchronize refs. */+ onLayoutCommit?: (controller: ReturnType<typeof useAgentChatController>) => void+}+/*** Mounts `useAgentChatController` with sensible defaults. Override any param.*@@ -47,7 +52,8 @@ export interface RenderControllerResult {* factory, so epoch comparisons in the controller are exercised for real.*/export function renderController(- overrides: Partial<ControllerParams> = {}+ overrides: Partial<ControllerParams> = {},+ options: RenderControllerOptions = {}): RenderControllerResult {const spies = {pushToast: vi.fn(),@@ -93,7 +99,7 @@ export function renderController((p: Partial<ControllerParams>) => {const hostAuthority = useHarnessHostAuthority()authority = hostAuthority- return useAgentChatController({+ const controller = useAgentChatController({onHostAccessRevoked: hostAuthority.onHostAccessRevoked,onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,isHostAccessBlocked: hostAuthority.isHostAccessBlocked,@@ -101,6 +107,10 @@ export function renderController(hostAuthorityRevision: hostAuthority.revision,...p,} as ControllerParams)+ useLayoutEffect(() => {+ options.onLayoutCommit?.(controller)+ }, [controller.activeChatId, controller.chatMessages, options.onLayoutCommit])+ return controller},{initialProps: params,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/localPageReadiness.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/localPageReadiness.characterization.test.tsxnew file mode 100644index 000000000..b4ed503bb--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/localPageReadiness.characterization.test.tsx@@ -0,0 +1,97 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, waitFor } from '@testing-library/react'+import { deferred } from './__fixtures__/catalogFixtures'+import { renderController } from './__fixtures__/controllerHarness'+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'++let clerum: MockClerum+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++beforeEach(() => {+ clerum = installMockClerum()+})++afterEach(() => {+ vi.restoreAllMocks()+ vi.useRealTimers()+ uninstallMockClerum()+})++describe('same-chat local page readiness', () => {+ it('keeps the transcript when same-chat reopen starts before passive ref synchronization', async () => {+ const chatId = 'same-chat'+ await clerum.chat.create('agent-x', chatId)+ await clerum.chat.upsertMessages('agent-x', chatId, [+ {+ id: 'local-turn-5',+ role: 'user',+ content: 'visible cached question',+ timestamp: 5,+ serverTurnNumber: 5,+ },+ ])+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 5,+ turns: [],+ })++ const originalSetLastActive = clerum.chat.setLastActive.getMockImplementation()+ if (!originalSetLastActive) throw new Error('Expected the ChatStore setLastActive producer')+ const secondCallEntered = deferred<void>()+ const releaseSecondCall = deferred<void>()+ let setLastActiveCalls = 0+ clerum.chat.setLastActive.mockImplementation(async (agentRef, selectedChatId) => {+ setLastActiveCalls += 1+ if (agentRef === 'agent-x' && selectedChatId === chatId && setLastActiveCalls === 2) {+ secondCallEntered.resolve()+ queueMicrotask(() => releaseSecondCall.resolve())+ await releaseSecondCall.promise+ }+ await originalSetLastActive(agentRef, selectedChatId)+ })++ let reopened = false+ let secondSwitch: Promise<void> | undefined+ const controller = renderController(+ {},+ {+ onLayoutCommit: view => {+ if (+ !reopened &&+ view.activeChatId === chatId &&+ view.chatMessages.some(message => message.id === 'local-turn-5')+ ) {+ reopened = true+ secondSwitch = view.switchToChat('agent-x', chatId)+ }+ },+ }+ )+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())++ await act(async () => {+ await controller.result.current.switchToChat('agent-x', chatId)+ })+ await secondCallEntered.promise+ if (!secondSwitch) throw new Error('Expected the layout observer to request a second switch')+ await secondSwitch++ expect(controller.result.current.activeChatId).toBe(chatId)+ expect(controller.result.current.chatMessages).toEqual([+ expect.objectContaining({ id: 'local-turn-5', content: 'visible cached question' }),+ ])+ expect(clerum.chat.loadMessages).toHaveBeenCalledTimes(2)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ chatId,+ undefined,+ { limit: 40, afterTurn: 4 }+ )+ controller.unmount()+ })+})diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 42c0a1012..7c8a4fb41 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -540,14 +540,6 @@ export function useAgentChatController({useEffect(() => {chatMessagesRef.current = chatMessages- const localPageRequest = activeChatLocalPageRequestRef.current- if (- localPageRequest &&- !localPageRequest.initialized &&- activeChatSwitchRequestRef.current === localPageRequest.request- ) {- localPageRequest.initialized = true- }}, [chatMessages])const [agentSending, setAgentSending] = useState(false)@@ -612,11 +604,9 @@ export function useAgentChatController({})const activeChatSwitchRequestRef = useRef<symbol | null>(null)const activeChatSwitchKeyRef = useRef<string | null>(null)- // Visible messages become reusable only after the local page has been rendered- // and copied into chatMessagesRef by its effect.+ // Correlate the visible local page to the switch request that loaded it.const activeChatLocalPageRequestRef = useRef<{request: symbol- initialized: boolean} | 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@@ -1021,11 +1011,11 @@ export function useAgentChatController({// PHASE 1 — render only the newest local page. The authoritative reconcile// below requests a delta after the newest cached server turn.+ // `setLastActive` above crosses the ChatStore boundary before this ref is+ // read, allowing the rendered page's effect to synchronize chatMessagesRef.const activeLocalPage = activeChatLocalPageRequestRef.currentconst reuseVisibleMessages =- canReuseActiveSwitch &&- activeLocalPage?.request === switchRequest &&- activeLocalPage.initialized+ canReuseActiveSwitch && activeLocalPage?.request === switchRequestlet cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []let loadedLocalPage = falsetry {@@ -1050,7 +1040,7 @@ export function useAgentChatController({(await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))if (!isStillActive()) returnif (loadedLocalPage && !reuseVisibleMessages) {- activeChatLocalPageRequestRef.current = { request: switchRequest, initialized: false }+ activeChatLocalPageRequestRef.current = { request: switchRequest }}loadedLocalMessageCountRef.current = cached.lengthsetHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)