Skip to content

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

TypeScript
9.1 KB
Raw Blame
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import type { AgentWorkspaceRoute } from '../../../uiTypes'
import { AgentTitleSelector } from '../AgentTitleSelector'

;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

const OPTIONS = [
  { id: 'alpha', label: 'Alpha' },
  { id: 'beta', label: 'Beta' },
  { id: 'gamma', label: 'Gamma' },
]

function renderSelector(overrides: Partial<React.ComponentProps<typeof AgentTitleSelector>> = {}) {
  const onSelectAgent = vi.fn()
  const onOpenRoute = vi.fn()
  const utils = render(
    <AgentTitleSelector
      ariaLabel="Switch chat agent"
      emptyLabel="No agents"
      options={OPTIONS}
      selectedId="alpha"
      selectedLabel="Alpha"
      onSelectAgent={onSelectAgent}
      onOpenRoute={onOpenRoute}
      {...overrides}
    />
  )
  return { ...utils, onSelectAgent, onOpenRoute }
}

function openMenu() {
  fireEvent.click(screen.getByRole('button', { name: 'Switch chat agent' }))
}

// All agent-name targets and the per-row 3-dots targets render with
// role="menuitem" (the dropdown is a role="menu" container). Query within the
// menu so we only match the row items, not the trigger.
function menu() {
  return screen.getByRole('menu')
}

// Returns the name menuitem (role=menuitem) whose label matches, or null.
function findNameItem(label: string) {
  return (
    within(menu())
      .getAllByRole('menuitem')
      .find(item => (item.textContent || '').trim() === label) || null
  )
}

// Returns the dots menuitem for a given agent label.
function findDotsItem(label: string) {
  return screen.getByRole('menuitem', { name: `Open ${label} sections` })
}

// jsdom performs no layout, so every getBoundingClientRect() is 0×0 and the two
// rows' anchors are indistinguishable. Stub each row's dots button with a
// distinct rect so the sub-menu's computed coordinates reveal which row it is
// anchored to.
function stubRect(el: Element, rect: { top: number; right: number }) {
  el.getBoundingClientRect = () =>
    ({
      top: rect.top,
      right: rect.right,
      bottom: rect.top + 16,
      left: rect.right - 10,
      width: 10,
      height: 16,
      x: rect.right - 10,
      y: rect.top,
      toJSON: () => ({}),
    }) as DOMRect
}

function submenuEl() {
  return document.querySelector('.agent-title-selector-submenu') as HTMLElement | null
}

afterEach(() => {
  cleanup()
  vi.restoreAllMocks()
})

describe('AgentTitleSelector', () => {
  it('renders the selected agent label in the trigger', () => {
    renderSelector({ selectedId: 'beta', selectedLabel: 'Beta' })
    const trigger = screen.getByRole('button', { name: 'Switch chat agent' })
    expect(trigger.textContent).toContain('Beta')
  })

  it('opens the menu on trigger click and lists every agent', () => {
    renderSelector()
    openMenu()
    for (const label of ['Alpha', 'Beta', 'Gamma']) {
      expect(findNameItem(label)).not.toBeNull()
    }
  })

  it('marks the selected agent row as current (aria-current)', () => {
    renderSelector({ selectedId: 'beta', selectedLabel: 'Beta' })
    openMenu()
    const beta = findNameItem('Beta')
    expect(beta).not.toBeNull()
    expect(beta?.getAttribute('aria-current')).toBe('true')
    // Non-selected rows are not marked current.
    expect(findNameItem('Alpha')?.getAttribute('aria-current')).toBeNull()
  })

  it('selects an agent when its name is clicked and closes the menu', () => {
    const { onSelectAgent } = renderSelector()
    openMenu()
    const gamma = findNameItem('Gamma')
    expect(gamma).not.toBeNull()
    fireEvent.click(gamma as HTMLElement)

    expect(onSelectAgent).toHaveBeenCalledTimes(1)
    expect(onSelectAgent).toHaveBeenCalledWith('gamma')
    // Menu closed after selection.
    expect(screen.queryByRole('menu')).toBeNull()
  })

  it('does not re-select the already-selected agent when its name is clicked', () => {
    const { onSelectAgent } = renderSelector({ selectedId: 'alpha', selectedLabel: 'Alpha' })
    openMenu()
    const alpha = findNameItem('Alpha')
    expect(alpha).not.toBeNull()
    fireEvent.click(alpha as HTMLElement)

    expect(onSelectAgent).not.toHaveBeenCalled()
  })

  it('opens a sections sub-menu from the 3-dots and navigates to a route', () => {
    const { onOpenRoute } = renderSelector()
    openMenu()

    fireEvent.click(findDotsItem('Beta'))
    // Sub-menu route item; "Connectors" maps to 'mcp-servers'.
    fireEvent.click(screen.getByRole('menuitem', { name: 'Connectors' }))

    expect(onOpenRoute).toHaveBeenCalledTimes(1)
    expect(onOpenRoute).toHaveBeenCalledWith('beta', 'mcp-servers' as AgentWorkspaceRoute)
  })

  it('temporarily hides Agent Files from the sections sub-menu', () => {
    renderSelector()
    openMenu()

    fireEvent.click(findDotsItem('Beta'))

    expect(screen.queryByRole('menuitem', { name: 'Agent Files' })).toBeNull()
  })

  it('toggles the sections sub-menu off when the dots are clicked again', () => {
    renderSelector()
    openMenu()
    const dots = findDotsItem('Beta')

    fireEvent.click(dots)
    expect(screen.queryByRole('menuitem', { name: 'Connectors' })).not.toBeNull()

    fireEvent.click(dots)
    expect(screen.queryByRole('menuitem', { name: 'Connectors' })).toBeNull()
  })

  it('shows the empty label when there are no options', () => {
    renderSelector({ options: [], selectedId: '', selectedLabel: '' })
    openMenu()
    expect(screen.getByText('No agents')).not.toBeNull()
  })

  it('portals the menu out of the selector wrapper', () => {
    const { container } = renderSelector()
    openMenu()
    const menuEl = screen.getByRole('menu')
    expect(container.querySelector('.agent-title-selector')?.contains(menuEl)).toBe(false)
    expect(menuEl.parentElement).toBe(document.body)
  })

  it('portals the nested sections sub-menu out of the (scrollable) menu so it cannot be clipped', () => {
    renderSelector()
    openMenu()
    fireEvent.click(findDotsItem('Beta'))

    const submenu = document.querySelector('.agent-title-selector-submenu')
    expect(submenu).toBeTruthy()
    // Not a descendant of the menu (which is a max-height/overflow scroll box):
    // it hangs off document.body so the overflow can't crop it.
    const menuEl = screen
      .getAllByRole('menu')
      .find(el => el.classList.contains('agent-title-selector-menu'))
    expect(menuEl?.contains(submenu)).toBe(false)
    expect(submenu?.parentElement).toBe(document.body)
  })

  it('re-anchors the sections sub-menu when jumping straight from one row to another', () => {
    renderSelector()
    openMenu()

    const betaDots = findDotsItem('Beta')
    const gammaDots = findDotsItem('Gamma')
    // Distinct top so the sub-menu's fixed `top` reveals which row it follows.
    stubRect(betaDots, { top: 100, right: 50 })
    stubRect(gammaDots, { top: 300, right: 50 })

    // Expand Beta → sub-menu positioned at Beta's anchor (top 100).
    fireEvent.click(betaDots)
    expect(submenuEl()?.style.top).toBe('100px')

    // Jump straight to Gamma WITHOUT closing the menu first. The regression:
    // with a single shared anchor ref, useFlyoutPosition never recomputes and
    // the sub-menu stays pinned to Beta's coordinates (top 100).
    fireEvent.click(gammaDots)
    expect(submenuEl()?.style.top).toBe('300px')
  })

  it('keeps the menu open when a mousedown lands inside the portaled menu or sub-menu', () => {
    renderSelector()
    openMenu()
    fireEvent.mouseDown(
      screen.getAllByRole('menu').find(el => el.classList.contains('agent-title-selector-menu'))!
    )
    expect(screen.queryByRole('menu')).not.toBeNull()

    // Open the nested sub-menu (portaled) and mousedown inside it: still open.
    fireEvent.click(findDotsItem('Beta'))
    fireEvent.mouseDown(document.querySelector('.agent-title-selector-submenu') as HTMLElement)
    expect(document.querySelector('.agent-title-selector-submenu')).not.toBeNull()
    // The route item still fires its click (guard kept it mounted through mousedown).
    fireEvent.click(screen.getByRole('menuitem', { name: 'Connectors' }))
  })

  it('moves keyboard focus into the portaled menu when it opens', () => {
    renderSelector()
    openMenu()
    // The menu is portaled to document.body; without moving focus into it, a
    // keyboard user's Tab jumps from the trigger past the menu to the next
    // header control. Focus must land on the first row item (Alpha's name).
    expect(document.activeElement).toBe(findNameItem('Alpha'))
  })

  it('moves focus into a sections sub-menu on expand and back to its row on ESC', () => {
    renderSelector()
    openMenu()
    fireEvent.click(findDotsItem('Beta'))
    const submenu = submenuEl()
    const firstRoute = submenu?.querySelector<HTMLElement>('[role="menuitem"]')
    expect(firstRoute).not.toBeNull()
    expect(document.activeElement).toBe(firstRoute)

    // ESC collapses the sub-menu and returns focus to the row's dots button.
    fireEvent.keyDown(document.body, { key: 'Escape' })
    expect(submenuEl()).toBeNull()
    expect(document.activeElement).toBe(findDotsItem('Beta'))
  })
})