Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
refactor(desktop-app): reconcile drawer chat tabs from vm.activeChatId (minispec 04, #2)
Diego Zacarias2416382b276f
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex 714ffe1d0..5a23d2616 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -36,6 +36,7 @@ import {cycleChatViewTab,focusBlankChatViewTab,openPersistedChatViewTab,+ reconcileChatViewTabs,selectChatViewTab,selectChatViewTabAt,selectLastChatViewTab,@@ -1182,28 +1183,29 @@ export function App() {])+ // Reconcile `chatViewTabs` (the switcher's source of truth) from the vm's+ // displayed chat. Runs for the full-screen chat route AND whenever the drawer+ // is visible (minispec 04, approach A), so any path that moves `vm.activeChatId`+ // — the ChatThread session list, an opened notification, auto-select, resume —+ // keeps the drawer's select in sync. `reconcileChatViewTabs` is idempotent, so+ // this never ping-pongs with the drawer reveal paths and never drives a chat+ // switch itself.React.useEffect(() => {- if (vm.navItem !== DESKTOP_ROUTES.chat || !vm.selectedAgent) return- if (!vm.activeChatId) {- setChatViewTabs(state =>- focusBlankChatViewTab(state, nextChatTabId(), vm.selectedAgent as string)- )- return+ if ((vm.navItem !== DESKTOP_ROUTES.chat && !chatDrawerVisible) || !vm.selectedAgent) return+ const conversation = vm.activeChatId+ ? (vm.chatList.find(chat => chat.id === vm.activeChatId) ??+ vm.latestChatSessions.find(+ chat => chat.agentRef === vm.selectedAgent && chat.id === vm.activeChatId+ ))+ : undefined+ const active = {+ agentRef: vm.selectedAgent as string,+ chatId: vm.activeChatId ?? null,+ title: conversation?.title,}- const conversation =- vm.chatList.find(chat => chat.id === vm.activeChatId) ??- vm.latestChatSessions.find(- chat => chat.agentRef === vm.selectedAgent && chat.id === vm.activeChatId- )- setChatViewTabs(state =>- openPersistedChatViewTab(state, {- id: nextChatTabId(),- agentRef: vm.selectedAgent as string,- chatId: vm.activeChatId as string,- title: conversation?.title,- })- )+ setChatViewTabs(state => reconcileChatViewTabs(state, active, nextChatTabId()))}, [+ chatDrawerVisible,nextChatTabId,vm.activeChatId,vm.chatList,diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsxindex 00f37162f..1b1317435 100644--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx@@ -71,6 +71,15 @@ function makeController(overrides: Partial<AppController> = {}): AppController {const handleNavSelect = vi.fn((item: AppController['navItem']) => {controller.navItem = item})+ // Faithful to the real vm: selecting an agent/chat moves the primary+ // `vm.activeChatId`/`selectedAgent` (the reconciler derives the tab from them).+ const handleSelectChatAgent = vi.fn(+ (agentName: string, options: { chatId?: string; keepNavItem?: boolean } = {}) => {+ controller.selectedAgent = agentName+ controller.activeChatId = options.chatId ?? null+ if (!options.keepNavItem) controller.navItem = DESKTOP_ROUTES.chat+ }+ )controller = {booting: false,initialExperienceLoading: false,@@ -112,7 +121,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {authTransitioning: false,handleEnsureTeamContext: vi.fn(async () => false),getCurrentTeamId: vi.fn(() => 'team-a'),- handleSelectChatAgent: vi.fn(),+ handleSelectChatAgent,handleNavSelect,handleLogout: vi.fn(),pushToast: vi.fn(),@@ -236,4 +245,40 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {expect(sandboxUiPageHarness.props?.chatDrawerOpen).toBe(false)expect(appHeaderHarness.props?.notificationTrayMode).toBe('drawer')})++ // #2 — reconciler covers the drawer (minispec 04 approach A). The ChatThread+ // session list moves `vm.activeChatId` via switchToChat WITHOUT touching+ // chatViewTabs. Simulate that (mutate activeChatId as the vm would) and assert+ // the drawer switcher re-derives to the displayed chat.+ it('syncs the drawer switcher when the displayed chat changes outside the tab path', () => {+ currentController = makeController({+ selectedAgent: 'alpha',+ activeChatId: 'chat-1',+ navItem: DESKTOP_ROUTES.chat,+ chatList: CHAT_LIST,+ } as Partial<AppController>)+ const { rerender } = render(<App />)++ // Launch from chat-1 → drawer opens on chat-1.+ act(() => {+ sidebarHarness.props?.onOpenSandboxUiApp?.({+ appRef: 'ns/app',+ label: 'App',+ defaultPath: '/',+ })+ })+ expect(sandboxUiPageHarness.props?.chatDrawerOpen).toBe(true)+ expect(screen.getByRole('button', { name: 'Open chats' }).textContent).toContain('First chat')++ // The ChatThread session list picks chat-2: switchToChat moves activeChatId+ // only — no tab-state call. The reconciler must re-derive the switcher.+ act(() => {+ currentController.activeChatId = 'chat-2'+ rerender(<App />)+ })++ expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)+ expect(screen.getByRole('button', { name: 'Open chats' }).textContent).toContain('Second chat')+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts b/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.tsindex c976a56e0..213bdccdc 100644--- a/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts+++ b/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts@@ -5,8 +5,10 @@ import {closeChatViewTab,createChatViewTabsState,cycleChatViewTab,+ activeChatViewTab,focusBlankChatViewTab,openPersistedChatViewTab,+ reconcileChatViewTabs,selectChatViewTabAt,selectLastChatViewTab,} from '../chatViewTabs'@@ -113,3 +115,70 @@ describe('chat view tabs', () => {)})})++describe('reconcileChatViewTabs (minispec 04 §4 invariant — property-based)', () => {+ // An event is "the vm now displays this chat" (chatId null = a blank new chat).+ const agentArb = fc.constantFrom('alpha', 'beta', 'gamma')+ const chatArb = fc.option(fc.constantFrom('c1', 'c2', 'c3', 'c4'), { nil: null })+ const titleArb = fc.option(fc.constantFrom('T1', 'T2'), { nil: undefined })+ const eventArb = fc.record({ agentRef: agentArb, chatId: chatArb, title: titleArb })++ it('the active tab always reflects the displayed chat; no duplicate persisted tabs', () => {+ fc.assert(+ fc.property(fc.array(eventArb, { maxLength: 40 }), events => {+ let state = createChatViewTabsState('seed', 'alpha')+ let counter = 0+ for (const event of events) {+ state = reconcileChatViewTabs(state, event, `gen-${counter++}`)+ const active = activeChatViewTab(state)+ // (1) total order / correct selection: the active tab is the displayed chat.+ expect(active.agentRef).toBe(event.agentRef)+ expect(active.chatId).toBe(event.chatId)+ // (2) no duplicate identifiers among persisted (non-blank) tabs.+ const seen = new Set<string>()+ for (const tab of state.tabs) {+ if (tab.chatId === null) continue+ const key = `${tab.agentRef}::${tab.chatId}`+ expect(seen.has(key)).toBe(false)+ seen.add(key)+ }+ }+ })+ )+ })++ it('is idempotent: applying the same event twice equals applying it once (same ref)', () => {+ fc.assert(+ fc.property(fc.array(eventArb, { maxLength: 20 }), eventArb, (prefix, event) => {+ let state = createChatViewTabsState('seed', 'alpha')+ let counter = 0+ for (const e of prefix) state = reconcileChatViewTabs(state, e, `p-${counter++}`)+ const once = reconcileChatViewTabs(state, event, `once`)+ const twice = reconcileChatViewTabs(once, event, `twice`)+ // Second application must be a no-op — same reference (setState bails out).+ expect(twice).toBe(once)+ })+ )+ })++ it('never drops a non-displayed persisted tab that was already open', () => {+ fc.assert(+ fc.property(fc.array(eventArb, { maxLength: 30 }), events => {+ let state = createChatViewTabsState('seed', 'alpha')+ let counter = 0+ const everOpened = new Set<string>()+ for (const event of events) {+ state = reconcileChatViewTabs(state, event, `g-${counter++}`)+ if (event.chatId !== null) everOpened.add(`${event.agentRef}::${event.chatId}`)+ // Every persisted chat ever displayed still has exactly one live tab.+ for (const key of everOpened) {+ const [agentRef, chatId] = key.split('::')+ expect(+ state.tabs.filter(t => t.agentRef === agentRef && t.chatId === chatId)+ ).toHaveLength(1)+ }+ }+ })+ )+ })+})diff --git a/desktop-app/ui/src/lib/chatViewTabs.ts b/desktop-app/ui/src/lib/chatViewTabs.tsindex 1fc13f0ad..f1acbaa82 100644--- a/desktop-app/ui/src/lib/chatViewTabs.ts+++ b/desktop-app/ui/src/lib/chatViewTabs.ts@@ -75,6 +75,66 @@ export function openPersistedChatViewTab(return { tabs: [...state.tabs, next], activeTabId: next.id }}+/**+ * Single reconciler for the invariant `chatViewTabs.activeTabId ≡ the displayed+ * chat` (minispec 04, approach A). `vm.activeChatId` is PRIMARY; the tab state is+ * DERIVED from it. Used by both the full-screen chat route and the app drawer.+ *+ * Hard rules (anti-loop):+ * - Idempotent: when the active tab already reflects `active` (same agent+chat,+ * and the title already matches when one is supplied), it returns the SAME+ * `state` reference so `setChatViewTabs` bails out — no re-render, no ping-pong+ * with the drawer reveal paths (which dedupe by `(agentRef, chatId)` too).+ * - Never spawns a duplicate persisted tab (dedupes by `(agentRef, chatId)`).+ * - Blank branch (`active.chatId === null`): never cascades new blank tabs; it+ * keeps the already-active blank tab, only aligning its agent.+ * - Never drives `switchToChat` — it only derives tab state.+ */+export function reconcileChatViewTabs(+ state: ChatViewTabsState,+ active: { agentRef: string; chatId: string | null; title?: string } | null,+ newTabId: string+): ChatViewTabsState {+ if (!active || !active.agentRef) return state+ if (active.chatId === null) {+ const current = activeChatViewTab(state)+ if (current.chatId === null) {+ // Already showing a blank tab — align its agent, never spawn a new one.+ return current.agentRef === active.agentRef+ ? state+ : {+ tabs: state.tabs.map(tab =>+ tab.id === current.id ? { ...tab, agentRef: active.agentRef } : tab+ ),+ activeTabId: current.id,+ }+ }+ return focusBlankChatViewTab(state, newTabId, active.agentRef)+ }+ const existing = state.tabs.find(+ tab => tab.agentRef === active.agentRef && tab.chatId === active.chatId+ )+ const title = active.title?.trim()+ if (existing) {+ const isActive = state.activeTabId === existing.id+ const titleMatches = !title || existing.title === title+ if (isActive && titleMatches) return state+ return {+ tabs:+ title && existing.title !== title+ ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))+ : state.tabs,+ activeTabId: existing.id,+ }+ }+ return openPersistedChatViewTab(state, {+ id: newTabId,+ agentRef: active.agentRef,+ chatId: active.chatId,+ title: active.title,+ })+}+export function selectChatViewTab(state: ChatViewTabsState, id: string): ChatViewTabsState {return state.tabs.some(tab => tab.id === id) ? { ...state, activeTabId: id } : state}