Skip to content

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

13.6 KB
Raw Blame
// @vitest-environment jsdom
import React, { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import FirstBoxWelcome from './FirstBoxWelcome'
import { recordConsoleOnboardingStep } from '@/hooks/useConsoleAnalytics'
import { ProductAnalyticsProvider } from '../ProductAnalyticsPreferences'
import { ConsoleTrackerFixture } from '../tests/ConsoleTrackerFixture'
vi.mock('@/hooks/useConsoleAnalytics', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/hooks/useConsoleAnalytics')>()
  return { ...actual, recordConsoleOnboardingStep: vi.fn(actual.recordConsoleOnboardingStep) }
})
const api = vi.hoisted(() => ({
  profile: vi.fn(),
  post: vi.fn(),
  getConsent: vi.fn(),
  saveConsent: vi.fn(),
  rename: vi.fn(),
  save: vi.fn(),
  credits: vi.fn(),
  refresh: vi.fn(),
  wallet: vi.fn(),
  methods: vi.fn(),
  organizationId: 'org-1',
  userId: 'user-1',
  billingApiUrl: 'https://billing.example.test',
}))
vi.mock('@/hooks/useApi', () => ({
  useApi: () => ({
    axiosInstance: { post: api.post, get: api.getConsent, put: api.saveConsent },
    getOrganizationOnboarding: api.profile,
    saveOrganizationOnboarding: api.save,
    organizationsApi: { updateOrganizationName: api.rename },
    billingApi: {
      getSignupCreditDelivery: api.credits,
      getOrganizationWallet: api.wallet,
      listAllPaymentMethods: api.methods,
    },
  }),
}))
vi.mock('@/hooks/useSelectedOrganization', () => ({
  useSelectedOrganization: () => ({
    selectedOrganization: { id: api.organizationId, name: 'Existing workspace' },
    authenticatedUserOrganizationMember: { role: 'owner' },
  }),
}))
vi.mock('@/hooks/useOrganizations', () => ({ useOrganizations: () => ({ refreshOrganizations: api.refresh }) }))
vi.mock('@/hooks/useConfig', () => ({
  useConfig: () => ({
    billingApiUrl: api.billingApiUrl,
    posthog: { host: 'https://example.invalid', apiKey: 'phc_test' },
  }),
}))
vi.mock('react-oidc-context', () => ({
  useAuth: () => ({ isAuthenticated: true, user: { profile: { sub: api.userId } } }),
}))
vi.mock('./FirstBoxAtmosphere', () => ({
  default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
let host: HTMLDivElement, root: Root, client: QueryClient
beforeEach(() => {
  globalThis.IS_REACT_ACT_ENVIRONMENT = true
  vi.resetAllMocks()
  api.post.mockResolvedValue({})
  api.getConsent.mockResolvedValue({ data: { allowed: null, enabledFrom: null } })
  api.billingApiUrl = 'https://billing.example.test'
  localStorage.clear()
  api.organizationId = 'org-1'
  api.userId = 'user-1'
  api.wallet.mockResolvedValue({ creditCardConnected: false, balanceCents: 0, ongoingBalanceCents: 0, name: 'Wallet' })
  api.methods.mockResolvedValue([])
  api.profile.mockResolvedValue(null)
  api.credits.mockResolvedValue({ delivered: true })
  host = document.createElement('div')
  document.body.append(host)
  root = createRoot(host)
  client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
})
afterEach(async () => {
  await act(async () => root.unmount())
  host.remove()
  client.clear()
  localStorage.clear()
})
async function settle() {
  await act(async () => {
    await new Promise((r) => setTimeout(r, 20))
  })
}
async function mount(withConsent = false) {
  const routes = (
    <Routes>
      <Route path="/dashboard/welcome" element={<FirstBoxWelcome />} />
      <Route path="/dashboard/quickstart" element={<p>Quickstart destination</p>} />
    </Routes>
  )
  await act(async () =>
    root.render(
      <QueryClientProvider client={client}>
        <MemoryRouter initialEntries={['/dashboard/welcome']}>
          {withConsent ? (
            <ProductAnalyticsProvider>{routes}</ProductAnalyticsProvider>
          ) : (
            <ConsoleTrackerFixture organizationId={api.organizationId}>{routes}</ConsoleTrackerFixture>
          )}
        </MemoryRouter>
      </QueryClientProvider>,
    ),
  )
  await settle()
}
async function click(text: string) {
  const b = Array.from(host.querySelectorAll('button')).find((e) => e.textContent?.trim() === text)!
  await act(async () => b.click())
  await settle()
}
async function input(id: string, value: string) {
  const e = host.querySelector('#' + id)!
  await act(async () => {
    Object.getOwnPropertyDescriptor(
      e.tagName === 'INPUT' ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype,
      'value',
    )!.set!.call(e, value)
    e.dispatchEvent(new Event('input', { bubbles: true }))
  })
}
it('continues through Welcome with the analytics checkbox unchecked', async () => {
  await mount(true)
  expect(host.querySelector<HTMLInputElement>('#welcome-product-analytics')?.checked).toBe(false)
  await input('welcome-organization', 'New team')
  await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
  await click('Continue')
  expect(api.rename).toHaveBeenCalledWith('org-1', { name: 'New team' })
  expect(api.saveConsent).not.toHaveBeenCalled()
  expect(host.textContent).toContain('What are you building?')
  expect(host.querySelector('#welcome-product-analytics')).toBeNull()
})
it('locks the Welcome analytics opt-in without making Continue wait for it', async () => {
  await mount(true)
  await input('welcome-organization', 'New team')
  const analytics = host.querySelector<HTMLInputElement>('#welcome-product-analytics')!
  const terms = host.querySelector<HTMLInputElement>('#welcome-terms')!
  const submit = host.querySelector<HTMLButtonElement>('button[type="submit"]')!
  const grant = Promise.withResolvers<{ data: { allowed: boolean } }>()
  api.getConsent.mockResolvedValue({ data: { allowed: true, enabledFrom: new Date().toISOString() } })
  api.saveConsent.mockReturnValueOnce(grant.promise)
  await act(async () => analytics.click())
  expect(analytics.disabled).toBe(true)
  expect(terms.checked).toBe(false)
  expect(submit.disabled).toBe(true)
  await act(async () => terms.click())
  expect(submit.disabled).toBe(false)
  await act(async () => grant.resolve({ data: { allowed: true } }))
  await settle()
  expect(analytics.checked).toBe(true)
  expect(analytics.disabled).toBe(true)
  await act(async () => analytics.click())
  expect(analytics.checked).toBe(true)
  expect(api.saveConsent).toHaveBeenCalledExactlyOnceWith('/analytics/consent', { allowed: true, version: 1 })
  await click('Continue')
  expect(host.textContent).toContain('What are you building?')
})
it('saves the name and selected intent before offering optional credits', async () => {
  await mount()
  expect(host.textContent).toContain('Name your organization')
  expect(recordConsoleOnboardingStep).toHaveBeenCalledExactlyOnceWith('org_create_started', 'org-1')
  await input('welcome-organization', 'New team')
  expect(host.querySelector<HTMLButtonElement>('button[type="submit"]')!.disabled).toBe(true)
  await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
  await click('Continue')
  expect(api.rename).toHaveBeenCalledWith('org-1', { name: 'New team' })
  expect(host.textContent).toContain('What are you building?')
  await act(async () => host.querySelector<HTMLInputElement>('input[value="long-running-agent"]')!.click())
  await input('welcome-note', 'Run an agent overnight')
  await click('Continue')
  expect(api.save).toHaveBeenCalledWith('org-1', { useCase: 'long-running-agent', note: 'Run an agent overnight' })
  expect(recordConsoleOnboardingStep).toHaveBeenLastCalledWith('use_case_selected', 'org-1', 'long-running-agent')
  const steps = api.post.mock.calls.filter(([, body]) => body.event !== '$pageview')
  expect(steps).toEqual(
    [
      { action: 'org_create_started' },
      { action: 'org_name_submit_click', control: 'button' },
      { action: 'use_case_submit_click', control: 'button' },
      { action: 'use_case_selected', selection: 'long-running-agent' },
    ].map((properties) => [
      '/analytics/organizations/org-1/console-events',
      expect.objectContaining({ event: 'console_onboarding_step', ...properties }),
      expect.any(Object),
    ]),
  )
  expect(host.textContent).toContain('3 Get credits')
  expect(host.textContent).toContain('Verify card')
  expect(api.credits).not.toHaveBeenCalled()
  expect(localStorage.getItem('SkipOnboarding_user-1')).toBeNull()
  await click('Explore with BoxLite')
  expect(host.textContent).toContain('Quickstart destination')
})
it('restores saved intent, supports going back, and keeps failed submissions retryable', async () => {
  api.profile.mockResolvedValue({ useCase: 'coding-agent', note: 'Saved note' })
  await mount()
  expect(host.textContent).toContain('3 Get credits')
  await click('Back')
  expect(host.querySelector<HTMLTextAreaElement>('#welcome-note')!.value).toBe('Saved note')
  await click('Back')
  expect(host.querySelector<HTMLInputElement>('#welcome-organization')!.value).toBe('Existing workspace')
  const interactions = api.post.mock.calls.filter(([, body]) => body.event !== '$pageview')
  expect(interactions.map(([, body]) => [body.event, body.action, body.control])).toEqual([
    ['console_onboarding_step', 'welcome_back_to_use_case_click', 'button'],
    ['console_onboarding_step', 'welcome_back_to_org_click', 'button'],
    ['console_onboarding_step', 'org_create_started', undefined],
  ])
  await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
  await click('Continue')
  await act(async () => host.querySelector<HTMLInputElement>('input[value="exploring"]')!.click())
  api.save.mockRejectedValue(new Error('Try saving later'))
  await click('Continue')
  expect(host.textContent).toContain('Try saving later')
  expect(api.credits).not.toHaveBeenCalled()
  api.save.mockResolvedValue({})
  await click('Try again')
  expect(host.textContent).toContain('Verify card')
})
it('shows profile loading failures and reloads them without losing the page', async () => {
  api.profile.mockRejectedValue(new Error('offline'))
  await mount()
  expect(host.textContent).toContain('Could not load your setup')
  api.profile.mockResolvedValue(null)
  await click('Try again')
  expect(host.textContent).toContain('Name your organization')
})

it('restores the confirmed organization step after reloading before intent submission', async () => {
  localStorage.setItem('boxlite:welcome:user-1:org-1', JSON.stringify({ organizationName: 'Existing workspace' }))
  await mount()
  expect(host.textContent).toContain('What are you building?')
  await click('Back')
  expect(host.querySelector<HTMLInputElement>('#welcome-organization')!.value).toBe('Existing workspace')
})

it('opens Quickstart without billing or a fabricated credit grant', async () => {
  api.billingApiUrl = ''
  api.profile.mockResolvedValue({ useCase: 'exploring', note: '' })
  await mount()
  expect(host.textContent).not.toContain('signup credits')
  await click('Start quickstart')
  expect(host.textContent).toContain('Quickstart destination')
  expect(api.credits).not.toHaveBeenCalled()
})

it('restores completion after continuing without credits instead of repeating setup', async () => {
  localStorage.setItem(
    'boxlite:welcome:user-1:org-1',
    JSON.stringify({
      organizationName: 'Existing workspace',
      completedAt: 1793200000000,
      creditGrantedAt: null,
    }),
  )
  api.profile.mockResolvedValue({ useCase: 'exploring', note: '' })
  await mount()
  expect(host.textContent).toContain('Quickstart destination')
  expect(api.save).not.toHaveBeenCalled()
  expect(api.credits).not.toHaveBeenCalled()
})

it('restores the saved credits step and completion without repeating API writes', async () => {
  api.profile.mockResolvedValue({ useCase: 'coding-agent', note: 'Saved' })
  await mount()
  expect(host.textContent).toContain('Verify card')
  await click('Explore with BoxLite')
  expect(host.textContent).toContain('Quickstart destination')
  expect(JSON.parse(localStorage.getItem('boxlite:welcome:user-1:org-1')!)).toMatchObject({
    completedAt: expect.any(Number),
    useCase: 'coding-agent',
    note: 'Saved',
  })
  await act(async () => root.unmount())
  root = createRoot(host)
  await mount()
  expect(host.textContent).toContain('Quickstart destination')
  expect(api.save).not.toHaveBeenCalled()
  expect(api.credits).not.toHaveBeenCalled()
})

it('keeps another organization on its own unfinished credits step', async () => {
  localStorage.setItem('boxlite:welcome:user-1:org-1', JSON.stringify({ completedAt: Date.now() }))
  api.profile.mockResolvedValue({ useCase: 'exploring', note: '' })
  api.organizationId = 'org-2'
  await mount()
  expect(host.textContent).toContain('Verify card')
  expect(host.textContent).not.toContain('Quickstart destination')
  await click('Explore with BoxLite')
  expect(JSON.parse(localStorage.getItem('boxlite:welcome:user-1:org-2')!)).toMatchObject({
    completedAt: expect.any(Number),
  })
})

it('continues to Quickstart when reporting a successful Welcome save throws', async () => {
  api.billingApiUrl = ''
  localStorage.setItem('boxlite:welcome:user-1:org-1', JSON.stringify({ organizationName: 'Existing workspace' }))
  api.save.mockResolvedValue({})
  vi.mocked(recordConsoleOnboardingStep).mockImplementation(() => {
    throw Error('analytics unavailable')
  })
  await mount()
  await act(async () => host.querySelector<HTMLInputElement>('input[value="exploring"]')!.click())
  await click('Start quickstart')
  expect(recordConsoleOnboardingStep).toHaveBeenCalledExactlyOnceWith('use_case_selected', 'org-1', 'exploring')
  expect(client.getQueryData(['organization-onboarding', 'org-1'])).toMatchObject({ useCase: 'exploring' })
  expect(host.textContent).toContain('Quickstart destination')
})