Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

13.4 KB
Raw Blame
// @vitest-environment jsdom
/*
 * Modified by BoxLite AI, 2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { act, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import Boxes from './Boxes'
import type { BoxQueryParams } from '@/hooks/useBoxes'
import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'

const navigate = vi.hoisted(() => vi.fn())
// Each test decides what the account holds.
const state = vi.hoisted(() => ({
  items: [] as Array<Record<string, unknown>> | undefined,
  total: 0,
  role: 'owner',
  // The first render, before the list query has answered.
  pending: false,
  // The two account-state queries do not resolve together.
  boxCountPending: false,
  placeholder: false,
  socketEnabled: false,
  filteredTotal: undefined as number | undefined,
  fleetTotal: 0,
  requestError: undefined as Error | undefined,
}))

const mocks = vi.hoisted(() => ({
  useBoxes: vi.fn(),
  refetch: vi.fn(),
  setQueryData: vi.fn(),
  invalidateQueries: vi.fn(),
  handlers: new Map<string, (event: unknown) => void>(),
}))

// Stand-ins for the two dialogs, so the assertions can read what the page
// decided about them rather than reaching into a real dialog's internals.
vi.mock('@/components/OnboardingGuideDialog', () => ({
  OnboardingGuideDialog: ({ open }: { open?: boolean }) => (
    <div data-testid="onboarding-dialog" data-open={String(!!open)} />
  ),
}))
vi.mock('@/components/Box/CreateBoxDialog', () => ({
  CreateBoxDialog: () => <div data-testid="create-box-dialog" />,
}))

// Row actions live behind a Radix dropdown. Render its items inline so a test
// can reach them, the same way BoxTable's own test flattens the page-size
// Select.
vi.mock('@/components/ui/dropdown-menu', () => {
  const Passthrough = ({ children }: { children?: ReactNode }) => <>{children}</>
  return {
    DropdownMenu: Passthrough,
    DropdownMenuContent: Passthrough,
    DropdownMenuGroup: Passthrough,
    DropdownMenuLabel: Passthrough,
    DropdownMenuPortal: Passthrough,
    DropdownMenuSeparator: () => null,
    DropdownMenuShortcut: Passthrough,
    DropdownMenuSub: Passthrough,
    DropdownMenuSubContent: Passthrough,
    DropdownMenuSubTrigger: Passthrough,
    DropdownMenuTrigger: Passthrough,
    DropdownMenuCheckboxItem: Passthrough,
    DropdownMenuRadioGroup: Passthrough,
    DropdownMenuRadioItem: Passthrough,
    DropdownMenuItem: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (
      <button type="button" onClick={onClick}>
        {children}
      </button>
    ),
  }
})

vi.mock('@/hooks/useSelectedOrganization', () => ({
  useSelectedOrganization: () => ({
    selectedOrganization: { id: 'org-1' },
    authenticatedUserOrganizationMember: { role: state.role },
    authenticatedUserHasPermission: () => true,
  }),
}))
vi.mock('@/hooks/useBoxes', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@/hooks/useBoxes')>()),
  useBoxes: (key: unknown, params: BoxQueryParams) => {
    mocks.useBoxes(key, params)
    return {
      data: state.pending
        ? undefined
        : {
            items: state.items,
            total: params.filters?.idOrName && state.filteredTotal !== undefined ? state.filteredTotal : state.total,
            totalPages: 1,
          },
      isLoading: false,
      isPlaceholderData: state.placeholder,
      error: state.requestError,
      refetch: mocks.refetch,
      isFetching: false,
    }
  },
}))
vi.mock('@/hooks/useApi', () => ({
  useApi: () => ({ boxApi: { listBoxesPaginated: vi.fn().mockResolvedValue({ data: { total: 0 } }) } }),
}))
vi.mock('@/hooks/useConfig', () => ({
  useConfig: () => ({ apiUrl: 'https://api.example.test', oidc: { issuer: '' } }),
}))
vi.mock('@/hooks/useNotificationSocket', () => ({
  useNotificationSocket: () => ({
    notificationSocket: state.socketEnabled
      ? {
          on: (event: string, handler: (data: unknown) => void) => mocks.handlers.set(event, handler),
          off: (event: string) => mocks.handlers.delete(event),
        }
      : null,
  }),
}))
vi.mock('@/hooks/queries/useApiKeysQuery', () => ({
  useApiKeysQuery: () => ({
    data: state.pending ? undefined : [],
    isLoading: state.pending,
    isSuccess: !state.pending,
  }),
}))
vi.mock('@tanstack/react-query', () => ({
  useQuery: () => ({
    data: state.pending || state.boxCountPending ? undefined : state.fleetTotal,
    isSuccess: !state.pending && !state.boxCountPending,
  }),
  useQueryClient: () => ({
    setQueryData: mocks.setQueryData,
    setQueriesData: vi.fn(),
    invalidateQueries: mocks.invalidateQueries,
    cancelQueries: vi.fn(),
  }),
}))
// `sub` matters: Boxes keys its onboarding-skip flag on it and bails out of the
// auto-open effect entirely without one.
vi.mock('react-oidc-context', () => ({
  useAuth: () => ({ user: { profile: { sub: 'user-1', email: '[email protected]' } } }),
}))
vi.mock('react-router-dom', () => ({
  generatePath: (path: string) => path,
  useNavigate: () => navigate,
  useSearchParams: () => [new URLSearchParams(), vi.fn()],
}))
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), dismiss: vi.fn() } }))

function buttonWith(text: string) {
  return Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find((button) =>
    button.textContent?.includes(text),
  )
}

/** The element a test is about; failing here beats a null-dereference later. */
function required<T extends Element>(element: T | null | undefined, what: string): T {
  if (!element) {
    throw new Error(`Missing expected element: ${what}`)
  }
  return element
}

function onboardingIsOpen() {
  return document.querySelector('[data-testid="onboarding-dialog"]')?.getAttribute('data-open')
}

describe('Boxes page, empty account', () => {
  let root: Root | null = null

  beforeAll(() => {
    globalThis.IS_REACT_ACT_ENVIRONMENT = true
    window.matchMedia = () =>
      ({
        matches: false,
        addEventListener: () => undefined,
        removeEventListener: () => undefined,
      }) as unknown as MediaQueryList
  })

  beforeEach(() => {
    state.items = []
    state.total = 0
    state.role = OrganizationUserRoleEnum.OWNER
    state.requestError = undefined
    state.pending = false
    state.boxCountPending = false
    state.placeholder = false
    state.socketEnabled = false
    state.filteredTotal = undefined
    state.fleetTotal = 0
    mocks.handlers.clear()
    mocks.setQueryData.mockReset()
    // Most cases are about the empty state itself, so start from a browser that
    // has already dismissed the guide; auto-open has its own case below.
    localStorage.setItem('SkipOnboarding_user-1', 'true')
  })

  afterEach(() => {
    act(() => root?.unmount())
    root = null
    document.body.innerHTML = ''
    localStorage.clear()
    vi.clearAllMocks()
  })

  it('keeps the server-side filter editable after a failed request', () => {
    state.pending = true
    state.requestError = new Error('unavailable')
    render()
    const input = document.querySelector<HTMLInputElement>('[aria-label="Filter boxes"]')!
    expect(input.disabled).toBe(false)
    act(() => {
      Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'web')
      input.dispatchEvent(new Event('input', { bubbles: true }))
    })
    expect(mocks.useBoxes.mock.lastCall?.[1].filters.idOrName).toBe('web')
  })

  it('offers recovery instead of a successful empty inventory after initial failure', async () => {
    state.pending = true
    state.requestError = new Error('unavailable')
    render()
    const retry = [...document.querySelectorAll('button')].find((button) => button.textContent === 'Retry')
    expect(retry).toBeDefined()
    expect(document.body.textContent).not.toContain('No Boxes yet')
    await act(async () => retry?.click())
    expect(mocks.refetch).toHaveBeenCalledTimes(1)
  })

  function render() {
    const host = document.createElement('div')
    document.body.appendChild(host)
    act(() => {
      root = createRoot(host)
      root.render(<Boxes />)
    })
  }

  it.each([9, 10])('shows the overview only at ten organization Boxes (count=%i)', (count) => {
    state.fleetTotal = count
    // A filtered or empty page does not determine whether the overview is shown.
    state.total = 0
    render()
    expect(document.querySelector('[aria-label="Boxes overview"]') !== null).toBe(count >= 10)
  })

  it('shows the filtered total rather than the current page size', () => {
    state.items = [{ id: 'box-1', name: 'web-api', state: 'started', createdAt: '2026-06-01T00:00:00.000Z' }]
    state.total = 100
    state.filteredTotal = 42
    render()
    const input = document.querySelector<HTMLInputElement>('[aria-label="Filter boxes"]')!
    act(() => {
      Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'web')
      input.dispatchEvent(new Event('input', { bubbles: true }))
    })
    expect(mocks.useBoxes).toHaveBeenLastCalledWith(
      expect.anything(),
      expect.objectContaining({ page: 1, filters: { idOrName: 'web' } }),
    )
    expect(document.querySelector('.resource-filter')?.textContent).toBe('42')
  })

  it.each(['box.state.updated', 'box.desired-state.updated'])(
    'reconciles %s without decrementing unrelated or duplicate removals',
    (eventName) => {
      state.socketEnabled = true
      state.items = [{ id: 'visible', name: 'web-api', state: 'started', createdAt: '2026-06-01T00:00:00.000Z' }]
      state.total = 42
      let cached = { items: state.items, total: state.total }
      mocks.setQueryData.mockImplementation((_key, update) => {
        cached = update(cached)
      })
      render()
      const emit = (id: string) =>
        act(() =>
          mocks.handlers.get(eventName)!({
            box: { id, state: 'error', desiredState: 'destroyed' },
            oldState: 'destroying',
            newState: 'destroyed',
            newDesiredState: 'destroyed',
          }),
        )
      emit('outside-filter')
      expect(cached.total).toBe(42)
      emit('visible')
      expect(cached.items).toHaveLength(0)
      expect(cached.total).toBe(41)
      emit('visible')
      expect(cached.total).toBe(41)
      expect(mocks.invalidateQueries).toHaveBeenCalledWith({ queryKey: ['boxes', 'org-1'], refetchType: 'active' })
    },
  )

  it('hides the previous filter total while replacement results are pending', () => {
    state.total = 42
    state.placeholder = true
    render()
    expect(document.querySelector('.resource-filter')?.textContent).toBe('—')
    state.placeholder = false
    state.total = 3
    act(() => root!.render(<Boxes />))
    expect(document.querySelector('.resource-filter')?.textContent).toBe('3')
  })

  it('keeps the page and leads with the table empty state', () => {
    render()

    // The page is still a Boxes page: its own heading and its create dialog
    // survive an empty account, rather than being replaced by a panel.
    expect(document.body.textContent).toContain('No Boxes yet.')
    expect(document.querySelector('h1')?.textContent).toBe('Boxes')
    // The create affordance still belongs to the page, not to the empty state.
    expect(document.querySelector('[data-testid="create-box-dialog"]')).not.toBeNull()
    expect(onboardingIsOpen()).toBeUndefined()
    expect(navigate).not.toHaveBeenCalled()
  })

  it('navigates from the unchanged empty state to the dedicated Quickstart', () => {
    render()

    const openQuickstart = required(buttonWith('Open Quickstart'), 'Open Quickstart button')

    act(() => openQuickstart.click())

    expect(onboardingIsOpen()).toBeUndefined()
    expect(navigate.mock.calls.at(-1)?.[0]).toBe('/dashboard/quickstart')
  })

  it('navigates to a box when its row is clicked, and arms delete from the row menu', () => {
    state.items = [
      {
        id: 'box-1',
        name: 'web-api',
        state: 'started',
        cpu: 1,
        memory: 1,
        disk: 10,
        createdAt: '2026-06-01T00:00:00.000Z',
      },
    ]
    state.total = 1
    render()

    const row = required(document.querySelector<HTMLElement>('div.cursor-pointer'), 'box row')
    act(() => row.click())
    expect(navigate).toHaveBeenCalled()

    const deleteItem = required(buttonWith('Delete'), 'row menu Delete')
    act(() => deleteItem.click())

    // The page owns the confirmation, so arming it from a row must open the
    // page's dialog rather than deleting outright.
    expect(document.body.textContent).toContain('Delete “')
  })

  it('renders an empty table rather than guessing while the list is still loading', () => {
    state.pending = true
    render()

    // Nothing is known yet, so every count falls back rather than reading as a
    // real zero from the server, and the page still stands up.
    expect(document.querySelector('h1')?.textContent).toBe('Boxes')
    expect(onboardingIsOpen()).toBeUndefined()
    expect(navigate).not.toHaveBeenCalled()
  })

  it('waits for both account-state queries before deciding to auto-open the guide', () => {
    // API keys have answered; the box count has not. Account state is not known
    // yet, so the guide must not auto-open on half the picture.
    state.boxCountPending = true
    render()

    expect(onboardingIsOpen()).toBeUndefined()
    expect(navigate).not.toHaveBeenCalled()
  })

  it('keeps non-owner members on Boxes even in a new empty organization', () => {
    localStorage.clear()
    state.role = 'member'
    render()
    expect(navigate).not.toHaveBeenCalled()
    expect(document.querySelector('h1')?.textContent).toBe('Boxes')
  })
})