The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
// @vitest-environment jsdom
/*
* Copyright Daytona Platforms Inc.
* SPDX-License-Identifier: AGPL-3.0
*/
import { act, type ReactNode } from 'react'
import { focusManager, keepPreviousData, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { queryKeys } from '@/hooks/queries/queryKeys'
import { SelectedOrganizationProvider } from '@/providers/SelectedOrganizationProvider'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { CreateBoxDialog, resolvePerBoxLimits } from './CreateBoxDialog'
import { AsciiButton } from '@/components/ascii'
import { toBoxApiCreateRequest, validateMountPath, validateMounts } from '@/lib/cloudBox'
// Mutable org returned by the mocked hook; each test sets `state.org`.
const state = vi.hoisted(() => ({
org: null as unknown,
config: { billingApiUrl: 'http://billing.test' } as { billingApiUrl?: string },
pricesQuery: { data: undefined, isLoading: false } as { data: unknown; isLoading: boolean },
// The catalog behind the image suggestions. Empty by default: the dialog has
// to work before an organization has pulled anything, which is the state
// every new organization is in.
catalogImages: [] as { name: string; curated: boolean; aliases: string[] }[],
}))
const LIVE_PRICES = {
schemaVersion: 1,
currency: 'USD',
prices: [
{ code: 'cpu', unit: 'core_hour', unitPriceCents: 5.04 },
{ code: 'gpu', unit: 'gpu_hour', unitPriceCents: 100 },
{ code: 'mem', unit: 'gib_hour', unitPriceCents: 1.44 },
{ code: 'disk', unit: 'gib_hour', unitPriceCents: 0.018 },
],
}
const mutationMocks = vi.hoisted(() => ({
createBox: vi.fn(),
refreshOrganizations: vi.fn().mockResolvedValue(undefined),
}))
const organizationsApi = vi.hoisted(() => ({ getOrganization: vi.fn(), listOrganizationMembers: vi.fn() }))
vi.mock('react-oidc-context', () => ({ useAuth: () => ({ user: { profile: { sub: 'owner' } } }) }))
vi.mock('posthog-js/react', () => ({ usePostHog: () => null }))
vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ organizationsApi }) }))
vi.mock('@/hooks/useOrganizations', () => ({
useOrganizations: () => ({
organizations: state.org ? [state.org] : [],
refreshOrganizations: mutationMocks.refreshOrganizations,
}),
}))
vi.mock('@/hooks/useSelectedOrganization', () => ({
useSelectedOrganization: () => ({ selectedOrganization: state.org }),
}))
vi.mock('@/hooks/queries/useVolumesQuery', () => ({
useVolumesQuery: () => ({ data: [{ id: 'vol-1', name: 'subtitle-models', state: 'ready' }] }),
}))
vi.mock('@/hooks/queries/useImagesQuery', () => ({
useImagesQuery: () => ({ data: state.catalogImages }),
}))
vi.mock('@/hooks/useConfig', () => ({ useConfig: () => state.config }))
vi.mock('@/hooks/queries/usePlansQuery', () => ({ usePlansQuery: () => ({}) }))
vi.mock('@/hooks/queries/billingQueries', () => ({ useOwnerPlanQuery: () => ({}) }))
vi.mock('@/hooks/queries/useUsagePricesQuery', () => ({
useUsagePricesQuery: () => state.pricesQuery,
}))
vi.mock('@/hooks/mutations/useCreateBoxMutation', () => ({
useCreateBoxMutation: () => ({ mutateAsync: mutationMocks.createBox }),
}))
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router-dom')>()
return { ...actual, useNavigate: () => vi.fn() }
})
function makeOrg(over: Record<string, unknown>) {
return { id: 'org-1', name: 'Org', ...over }
}
// Drive a React controlled input the way a user typing would.
function typeInto(el: HTMLInputElement, value: string) {
const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')
desc?.set?.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
async function flush() {
await act(async () => {
await Promise.resolve()
if (vi.isFakeTimers()) await vi.advanceTimersByTimeAsync(1)
else await new Promise((r) => setTimeout(r, 0))
})
}
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 300_000, placeholderData: keepPreviousData, retry: false } },
})
organizationsApi.getOrganization.mockReset().mockImplementation(async () => ({ data: state.org }))
organizationsApi.listOrganizationMembers.mockResolvedValue({ data: [] })
})
afterEach(() => {
queryClient.clear()
focusManager.setFocused(undefined)
vi.useRealTimers()
})
function withQueries(children: ReactNode) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
describe('resolvePerBoxLimits', () => {
it('uses the organization per-box maxima when they are positive', () => {
const limits = resolvePerBoxLimits(makeOrg({ maxCpuPerBox: 4, maxMemoryPerBox: 8, maxDiskPerBox: 10 }))
expect(limits).toEqual({ cpu: 4, memory: 8, disk: 10 })
})
it('leaves a resource uncapped when a max is unset (<= 0) — backend treats <=0 as unlimited', () => {
const limits = resolvePerBoxLimits(makeOrg({ maxCpuPerBox: 0, maxMemoryPerBox: undefined, maxDiskPerBox: -1 }))
expect(limits).toEqual({ cpu: undefined, memory: undefined, disk: undefined })
})
it('leaves resources uncapped when no organization is loaded', () => {
expect(resolvePerBoxLimits(null)).toEqual({ cpu: undefined, memory: undefined, disk: undefined })
expect(resolvePerBoxLimits(undefined)).toEqual({ cpu: undefined, memory: undefined, disk: undefined })
})
})
describe('CreateBoxDialog per-org resource cap', () => {
let root: Root | null = null
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
state.org = makeOrg({ maxCpuPerBox: 4, maxMemoryPerBox: 8, maxDiskPerBox: 10 })
state.config = { billingApiUrl: 'http://billing.test' }
state.pricesQuery = { data: LIVE_PRICES, isLoading: false }
state.catalogImages = []
mutationMocks.refreshOrganizations.mockReset().mockResolvedValue(undefined)
organizationsApi.getOrganization.mockReset().mockImplementation(async () => ({ data: state.org }))
mutationMocks.createBox.mockReset().mockResolvedValue({ id: 'created-box' })
})
afterEach(() => {
act(() => root?.unmount())
root = null
document.body.innerHTML = ''
vi.restoreAllMocks()
})
async function renderOpen() {
const host = document.createElement('div')
document.body.appendChild(host)
await rerenderOpen(host)
// Reveal the CPU/Memory/Disk steppers: Size defaults to the "Shoebox" chip,
// and "Custom" is what exposes the raw fields. Scoped to the Size group —
// Lifecycle has its own identically-labelled "Custom" chip.
const sizeGroup = document.querySelector('[aria-label="Size"]')
const custom = sizeGroup
? [...sizeGroup.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
/^Larger or custom box/.test(b.textContent ?? ''),
)
: undefined
await act(async () => custom?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
}
async function rerenderOpen(
host = document.body.firstElementChild ?? document.body.appendChild(document.createElement('div')),
) {
await act(async () => {
root ??= createRoot(host)
root.render(withQueries(<CreateBoxDialog open onOpenChange={() => {}} />))
})
await flush()
}
async function rerenderOpenWith(props: { prefillVolume?: string; prefillImage?: string }) {
const host = document.createElement('div')
document.body.appendChild(host)
await act(async () => {
root ??= createRoot(host)
root.render(withQueries(<CreateBoxDialog open onOpenChange={() => {}} {...props} />))
})
await flush()
}
function cpuInput() {
return document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')[0]
}
it('exposes sub-core sizes with complete estimates before opening Custom', async () => {
await rerenderOpen()
const card = document.querySelector<HTMLButtonElement>('button[aria-label="Matchbox"]')
expect(card).not.toBeNull()
expect(card?.textContent).toContain('0.125')
expect(card?.textContent).toContain('$0.0117')
await act(async () => card!.click())
await act(async () =>
document.querySelector<HTMLButtonElement>('button[aria-label="Larger or custom box"]')!.click(),
)
expect(cpuInput().value).toBe('0.125')
})
it('steps fractional CPU through recommended sizes without rounding typed values', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '0.125'))
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="increase"]')!.click())
expect(cpuInput().value).toBe('0.25')
await act(async () => typeInto(cpuInput(), '0.126'))
expect(cpuInput().value).toBe('0.126')
})
it('restores a valid Custom draft after comparing a preset', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '1.5'))
await act(async () => button('Matchbox').click())
await act(async () => button('Larger or custom box').click())
expect(cpuInput().value).toBe('1.5')
})
it('keeps CPU steps meaningful between recommended nodes and an organization ceiling', async () => {
state.org = makeOrg({ maxCpuPerBox: 1.75 })
await renderOpen()
await act(async () => typeInto(cpuInput(), '1.126'))
await act(async () => button('increase').click())
expect(cpuInput().value).toBe('1.75')
expect(button('increase').disabled).toBe(true)
await act(async () => button('decrease').click())
expect(cpuInput().value).toBe('1')
await act(async () => typeInto(cpuInput(), '0.126'))
await act(async () => button('decrease').click())
expect(cpuInput().value).toBe('0.125')
expect(button('decrease').disabled).toBe(true)
})
it('clears the saved Custom draft when the dialog is reopened', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '1.5'))
await act(async () => button('Matchbox').click())
await act(async () => root?.render(withQueries(<CreateBoxDialog open={false} onOpenChange={() => {}} />)))
await rerenderOpen()
await act(async () => button('Larger or custom box').click())
expect(cpuInput().value).toBe('1')
})
it('does not restore another organization’s Custom draft', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '1.5'))
await act(async () => button('Matchbox').click())
state.org = { ...makeOrg({ maxCpuPerBox: 4 }), id: 'org-other' }
await rerenderOpen()
await act(async () => button('Larger or custom box').click())
expect(cpuInput().value).toBe('0.125')
})
it('removes an incomplete volume mount so creation is not blocked', async () => {
await rerenderOpen()
await act(async () => button('+ Mount a volume').click())
expect(button('Create Box').disabled).toBe(true)
await act(async () => button('Remove mount').click())
expect(document.querySelector('input[aria-label="Mount path"]')).toBeNull()
expect(button('Create Box').disabled).toBe(false)
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ volumes: undefined }))
})
it('accepts exact whole-MiB memory and rejects fractional MiB without a CPU error', async () => {
await renderOpen()
const memory = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')[1]
await act(async () => typeInto(memory, '0.2509765625'))
expect(memory.getAttribute('aria-invalid')).toBe('false')
expect(button('Create Box').disabled).toBe(false)
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ resources: expect.objectContaining({ memory: 257 / 1024 }) }),
)
await act(async () => typeInto(memory, '0.251'))
expect(memory.getAttribute('aria-invalid')).toBe('true')
expect(memory.title).toContain('whole MiB')
expect(memory.title).not.toContain('CPU')
expect(button('Create Box').disabled).toBe(true)
})
it('shows zero per-resource costs and no paid breakdown without billing', async () => {
state.config = {}
await renderOpen()
expect(document.body.textContent).toContain('No usage charges')
const resourceFields = [...document.querySelectorAll('input[aria-label="value"]')].map(
(input) => input.parentElement?.parentElement,
)
expect(resourceFields).toHaveLength(3)
for (const field of resourceFields) expect(field?.textContent).toContain('$0.00 / hr')
expect([...document.querySelectorAll('button')].some((item) => item.textContent === 'Price breakdown')).toBe(false)
})
it('shows the effective capped configuration and price on a preset', async () => {
state.org = makeOrg({ maxCpuPerBox: 2, maxMemoryPerBox: 4, maxDiskPerBox: 10 })
await rerenderOpen()
const card = button('Cargo')
expect(card.textContent).toContain('2 vCPU')
expect(card.textContent).toContain('4 GiB RAM · 10 GiB disk')
expect(card.textContent).toContain('$0.1602')
expect(card.textContent).toContain('Adjusted')
await act(async () => card.click())
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ resources: { cpu: 2, memory: 4, disk: 10 } }),
)
})
it('keeps invalid CPU blocked when Custom is selected again', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '0.12'))
await act(async () => button('Larger or custom box').click())
expect(cpuInput().value).toBe('0.12')
expect(button('Create Box').disabled).toBe(true)
})
it('explains a Custom draft adjusted to refreshed limits', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '3'))
await act(async () => button('Matchbox').click())
state.org = makeOrg({ maxCpuPerBox: 2 })
await act(async () => {
await queryClient.invalidateQueries({ queryKey: queryKeys.organization.detail('org-1') })
})
await act(async () => button('Larger or custom box').click())
expect(cpuInput().value).toBe('2')
expect(document.body.textContent).toContain('[email protected]')
})
it('exposes named image and lifecycle controls and focuses custom resources', async () => {
await rerenderOpen()
expect(button('Browse images').textContent).toContain('Browse images')
expect(document.querySelector('button[aria-label="Stop when idle"]')).toBeTruthy()
expect(document.querySelector('button[aria-label="Wake on access"]')).toBeTruthy()
await act(async () => button('Larger or custom box').click())
expect(document.activeElement).toBe(cpuInput())
expect(document.querySelector('input[aria-label="value"]')).toBeTruthy()
})
it.each([
['Matchbox', 0.125, 0.25],
['Pocket', 0.25, 0.5],
['Lunchbox', 0.5, 1],
])('keeps %s at a 1:2 CPU-memory ratio through Custom and submission', async (label, cpu, memory) => {
await rerenderOpen()
await act(async () => button(String(label)).click())
await act(async () => button('Larger or custom box').click())
const inputs = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')
expect(Number(inputs[1].value)).toBe(memory)
await act(async () => inputs[1].dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ resources: { cpu, memory, disk: 10 } }),
)
})
function nameInput() {
return document.querySelector<HTMLInputElement>('input[placeholder="my-new-box"]')
}
it('clamps an over-max CPU input to the org maximum and shows a red contact-support hint', async () => {
await renderOpen()
const input = cpuInput()
expect(input).toBeTruthy()
await act(async () => typeInto(input, '50'))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
// auto-corrected to the org max (4), not any dashboard-local ceiling.
expect(input.value).toBe('4')
// the amber cap note names the capped resource + its max and the support mailbox
expect(document.body.textContent).toContain('[email protected]')
expect(document.body.textContent).toMatch(/CPU\s*4\s*vCPU/)
const mailto = document.querySelector('a[href^="mailto:[email protected]"]')
expect(mailto).toBeTruthy()
})
it('opens with the default values already clamped to the org max (no over-limit initial state)', async () => {
// Org caps Disk at 3 GiB — tighter than the built-in DEFAULTS.disk = 10.
state.org = makeOrg({ maxCpuPerBox: 4, maxMemoryPerBox: 8, maxDiskPerBox: 3 })
await renderOpen()
const inputs = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')
// Disk (the third stepper) must open at 3, NOT the DEFAULTS.disk of 10.
expect(inputs[2].value).toBe('3')
// CPU / Memory defaults (1 each) are already under the caps — untouched.
expect(inputs[0].value).toBe('1')
expect(inputs[1].value).toBe('1')
})
it('pins the visible input at the org max the moment the typed value would overshoot (before any blur)', async () => {
await renderOpen()
const input = cpuInput()
// No blur / focusout — this asserts the keystroke-time behaviour, which is
// the fix for "the box still shows 123123 even with the amber note up".
await act(async () => typeInto(input, '123123'))
await flush()
expect(input.value).toBe('4')
expect(document.body.textContent).toContain('[email protected]')
expect(document.body.textContent).toMatch(/CPU\s*4\s*vCPU/)
})
it('uses the API CPU ceiling when the org max is unset', async () => {
state.org = makeOrg({ maxCpuPerBox: 0, maxMemoryPerBox: undefined, maxDiskPerBox: -1 })
await renderOpen()
const input = cpuInput()
await act(async () => typeInto(input, '123123'))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
expect(input.value).toBe('16')
expect(document.body.textContent).toContain('Max 16 vCPU')
})
it('preserves open form state when an org change only tightens resource caps', async () => {
await renderOpen()
const name = nameInput()
const input = cpuInput()
expect(name).toBeTruthy()
if (!name) throw new Error('expected name input to be rendered')
await act(async () => typeInto(name, 'kept-name'))
await act(async () => typeInto(input, '4'))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
state.org = makeOrg({ maxCpuPerBox: 2, maxMemoryPerBox: 8, maxDiskPerBox: 10 })
await rerenderOpen()
expect(nameInput()?.value).toBe('kept-name')
expect(document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]').length).toBe(3)
expect(cpuInput().value).toBe('2')
expect(document.body.textContent).toMatch(/CPU\s*2\s*vCPU/)
})
it('caps each of the three resource fields independently against its own max', async () => {
await renderOpen()
const inputs = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')
expect(inputs.length).toBe(3)
for (const input of Array.from(inputs)) {
await act(async () => typeInto(input, '999999'))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
}
// Org limits from beforeEach: cpu 4, memory 8, disk 10
expect(inputs[0].value).toBe('4')
expect(inputs[1].value).toBe('8')
expect(inputs[2].value).toBe('10')
const note = document.body.textContent ?? ''
expect(note).toMatch(/CPU\s*4\s*vCPU/)
expect(note).toMatch(/Memory\s*8\s*GiB/)
expect(note).toMatch(/Disk\s*10\s*GiB/)
})
// Size presets replaced the old collapsed "Advanced Options" toggle — this
// pins that picking a named tier actually drives the three underlying values.
it("applies a Size preset's cpu/memory/disk", async () => {
await rerenderOpen()
const sizeGroup = document.querySelector('[aria-label="Size"]')
if (!sizeGroup) throw new Error('expected the Size group to be rendered')
const medium = [...sizeGroup.querySelectorAll<HTMLButtonElement>('button')].find(
(b) => b.getAttribute('aria-label') === 'Crate',
)
expect(medium).toBeTruthy()
await act(async () => medium?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
expect(document.body.textContent).toMatch(/2 vCPU.*4 GiB.*10 GiB/)
})
// Regression guard for the Size preset clamp: picking "Cargo" (4/8/50) against
// a tighter org cap must clamp immediately and say so, not leave the screen
// showing a number the org will reject on submit.
it('clamps a Size preset that exceeds the org cap and explains why immediately', async () => {
state.org = makeOrg({ maxCpuPerBox: 2, maxMemoryPerBox: 8, maxDiskPerBox: 10 })
await rerenderOpen()
const sizeGroup = document.querySelector('[aria-label="Size"]')
if (!sizeGroup) throw new Error('expected the Size group to be rendered')
const large = [...sizeGroup.querySelectorAll<HTMLButtonElement>('button')].find(
(b) => b.getAttribute('aria-label') === 'Cargo',
)
await act(async () => large?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
// Cargo asks for 4 vCPU; the org caps at 2 — clamped, not silently dropped.
expect(document.body.textContent).toMatch(/2 vCPU.*8 GiB.*10 GiB/)
expect(document.body.textContent).toContain('[email protected]')
expect(document.body.textContent).toMatch(/CPU\s*2\s*vCPU/)
})
it('clears the hint once the value is brought back under the max', async () => {
await renderOpen()
const input = cpuInput()
await act(async () => typeInto(input, '50'))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
expect(document.body.textContent).toContain('[email protected]')
const decrease = document.querySelector<HTMLButtonElement>('button[aria-label="decrease"]')
await act(async () => decrease?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
expect(input.value).toBe('2')
expect(document.body.textContent).not.toContain('[email protected]')
})
// Radix's DropdownMenuTrigger opens on `pointerdown`, not `click` (see
// @radix-ui/react-dropdown-menu's Trigger) — a plain click dispatch leaves it
// closed. jsdom has no PointerEvent constructor, but React only reads
// `button`/`ctrlKey` off the event, so a MouseEvent typed as 'pointerdown'
// satisfies it. Selecting an item, in contrast, *is* a plain click
// (@radix-ui/react-menu's Item).
async function openDropdown(ariaLabel: string) {
const trigger = document.querySelector<HTMLButtonElement>(`button[aria-label="${ariaLabel}"]`)
expect(trigger).toBeTruthy()
await act(async () =>
trigger?.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, cancelable: true, button: 0 })),
)
await flush()
}
async function selectMenuItem(text: string) {
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((el) => el.textContent === text)
expect(item).toBeTruthy()
await act(async () => item?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })))
await flush()
}
async function submit() {
const createButton = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
(button) => button.textContent === 'Create Box',
)
expect(createButton?.disabled).toBe(false)
await act(async () => createButton?.click())
await flush()
}
it.each(['0.125', '0.126', '0.5', '1.001', '1.5'])('submits fractional CPU %s without rounding', async (value) => {
await renderOpen()
const input = document.querySelector<HTMLInputElement>('input[aria-label="value"]')!
await act(async () => typeInto(input, value))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ resources: expect.objectContaining({ cpu: Number(value) }) }),
)
})
it.each(['0', '-1', '0.124', '0.1251', 'abc'])(
'blocks invalid CPU text %s instead of submitting the saved CPU',
async (value) => {
await renderOpen()
const input = document.querySelector<HTMLInputElement>('input[aria-label="value"]')!
await act(async () => typeInto(input, value))
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
expect(button('Create Box').disabled).toBe(true)
expect(mutationMocks.createBox).not.toHaveBeenCalled()
},
)
describe('subscribed Cloud resource limits', () => {
beforeEach(() => {
state.org = makeOrg({ maxCpuPerBox: 16, maxMemoryPerBox: 32, maxDiskPerBox: 100 })
mutationMocks.createBox.mockReset()
mutationMocks.createBox.mockResolvedValue({ id: 'created-box' })
})
it.each([
['Shoebox', 1, 1024, 10],
['Crate', 2, 4096, 20],
['Cargo', 4, 8192, 50],
])('submits the %s preset through the REST resource mapper', async (label, cpus, memory_mib, disk_size_gb) => {
await renderOpen()
const button = [...document.querySelectorAll<HTMLButtonElement>('[aria-label="Size"] button')].find((button) =>
button.textContent?.startsWith(String(label)),
)
expect(button).toBeTruthy()
await act(async () => button?.click())
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledTimes(1)
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0])).toMatchObject({
cpus,
memory_mib,
disk_size_gb,
})
})
it('submits the exact Custom maximum in MiB without a cap warning', async () => {
await renderOpen()
const inputs = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')
for (const [index, value] of ['16', '32', '100'].entries()) {
await act(async () => typeInto(inputs[index], value))
await act(async () => inputs[index].dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
}
await submit()
expect(document.body.textContent).not.toContain('[email protected]')
expect(mutationMocks.createBox).toHaveBeenCalledTimes(1)
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0])).toMatchObject({
cpus: 16,
memory_mib: 32768,
disk_size_gb: 100,
})
})
it.each([
[0, '17', '16', /CPU\s*16\s*vCPU/],
[1, '33', '32', /Memory\s*32\s*GiB/],
[2, '101', '100', /Disk\s*100\s*GiB/],
])(
'clamps resource %s to the returned organization limit and explains the cap',
async (index, value, max, hint) => {
await renderOpen()
const input = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')[index]
await act(async () => typeInto(input, value))
await flush()
expect(input.value).toBe(max)
expect(document.body.textContent).toMatch(hint)
expect(document.querySelector('a[href^="mailto:[email protected]"]')).toBeTruthy()
},
)
})
it('bounds the selected organization request and makes it cancelable', async () => {
await renderOpen()
expect(organizationsApi.getOrganization).toHaveBeenCalledExactlyOnceWith('org-1', {
timeout: 10_000,
signal: expect.any(AbortSignal),
})
expect(mutationMocks.refreshOrganizations).not.toHaveBeenCalled()
})
function button(label: string) {
const found = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
(b) => b.getAttribute('aria-label') === label || b.textContent === label,
)
if (!found) throw new Error(`Missing button: ${label}`)
return found
}
function deferRefresh() {
let resolve!: (response: { data: unknown }) => void
let reject!: (error: Error) => void
const promise = new Promise<{ data: unknown }>((yes, no) => {
resolve = yes
reject = no
})
organizationsApi.getOrganization.mockReturnValueOnce(promise)
return { resolve: (data = state.org) => resolve({ data }), reject }
}
it.each([
['Crate', 20],
['Cargo', 50],
])('submits %s unchanged while the first limits request hangs', async (label, diskSize) => {
deferRefresh()
await rerenderOpen()
expect(button(String(label)).matches(':disabled')).toBe(false)
expect(button('Create Box').disabled).toBe(false)
await act(async () => button(String(label)).click())
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0]).disk_size_gb).toBe(diskSize)
expect(document.body.textContent).toContain('Limits are checked when you create.')
})
it('submits Custom inputs without applying stored defaults before limits arrive', async () => {
deferRefresh()
await renderOpen()
const inputs = document.querySelectorAll<HTMLInputElement>('input[aria-label="value"]')
expect([...inputs].every((input) => !input.matches(':disabled'))).toBe(true)
for (const [index, value] of ['16', '32', '100'].entries()) {
await act(async () => typeInto(inputs[index], value))
await act(async () => inputs[index].dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
}
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0])).toMatchObject({
cpus: 16,
memory_mib: 32768,
disk_size_gb: 100,
})
})
it('allows server-validated resources if the first limit refresh fails', async () => {
const refresh = deferRefresh()
await rerenderOpen()
await act(async () => refresh.reject(new Error('network unavailable')))
await flush()
expect(document.body.textContent).toContain('Could not load limits. Limits are checked when you create.')
await act(async () => button('Cargo').click())
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0]).disk_size_gb).toBe(50)
})
it('restores the selected preset when background refresh raises the limits', async () => {
vi.useFakeTimers()
await rerenderOpen()
await act(async () => button('Crate').click())
const name = nameInput()
if (!name) throw new Error('expected name input to be rendered')
await act(async () => typeInto(name, 'kept-name'))
expect(document.body.textContent).toMatch(/2 vCPU.*4 GiB.*10 GiB/)
const refresh = deferRefresh()
await act(async () => vi.advanceTimersByTimeAsync(10_000))
expect(button('Create Box').disabled).toBe(false)
await act(async () => refresh.resolve(makeOrg({ maxCpuPerBox: 16, maxMemoryPerBox: 32, maxDiskPerBox: 100 })))
await flush()
expect(document.body.textContent).toMatch(/2 vCPU.*4 GiB.*20 GiB/)
expect(document.body.textContent).not.toContain('[email protected]')
expect(nameInput()?.value).toBe('kept-name')
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0]).disk_size_gb).toBe(20)
})
it('updates Custom maxima without changing inputs, retaining known limits after refresh failure', async () => {
await renderOpen()
await act(async () => typeInto(cpuInput(), '3'))
await act(async () => cpuInput().dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
const refresh = deferRefresh()
await act(async () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.organization.detail('org-1') })
})
expect(cpuInput().value).toBe('3')
expect(document.body.textContent).toContain('Max 4 vCPU')
await act(async () => refresh.resolve(makeOrg({ maxCpuPerBox: 16, maxMemoryPerBox: 32, maxDiskPerBox: 100 })))
await flush()
expect(cpuInput().value).toBe('3')
expect(document.body.textContent).toContain('Max 16 vCPU')
expect(document.body.textContent).toContain('Max 32 GiB')
expect(document.body.textContent).toContain('Max 100 GiB')
const failed = deferRefresh()
await act(async () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.organization.detail('org-1') })
})
await act(async () => failed.reject(new Error('network unavailable')))
await flush()
expect(document.body.textContent).toContain('Could not refresh limits. Showing last known limits.')
expect(document.body.textContent).toContain('Max 16 vCPU')
expect(button('Create Box').disabled).toBe(false)
})
it('isolates organizations while requests are pending and ignores obsolete results', async () => {
await renderOpen()
const earlier = deferRefresh()
await act(async () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.organization.detail('org-1') })
})
const refresh = deferRefresh()
state.org = makeOrg({ id: 'org-2', maxCpuPerBox: 2, maxMemoryPerBox: 4, maxDiskPerBox: 5 })
await rerenderOpen()
expect(document.body.textContent).not.toContain('Max 4 vCPU')
expect(cpuInput().matches(':disabled')).toBe(false)
await act(async () => earlier.resolve(makeOrg({ maxCpuPerBox: 16, maxMemoryPerBox: 32, maxDiskPerBox: 100 })))
await flush()
expect(document.body.textContent).not.toContain('Max 32 GiB')
await act(async () => refresh.resolve())
await flush()
await act(async () => button('Cargo').click())
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0])).toMatchObject({
cpus: 2,
memory_mib: 4096,
disk_size_gb: 5,
})
})
it('reuses its own cached limits when reopening while a fresh request is pending', async () => {
await renderOpen()
await act(async () => root?.render(withQueries(<CreateBoxDialog open={false} onOpenChange={() => {}} />)))
deferRefresh()
await renderOpen()
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(2)
expect(document.body.textContent).toContain('Max 4 vCPU')
expect(button('Create Box').disabled).toBe(false)
})
it('preloads before opening and shares the in-flight read with the dialog', async () => {
const refresh = deferRefresh()
const host = document.body.appendChild(document.createElement('div'))
root = createRoot(host)
const tree = (open: boolean) =>
withQueries(
<SelectedOrganizationProvider>
<CreateBoxDialog open={open} onOpenChange={() => {}} />
</SelectedOrganizationProvider>,
)
await act(async () => root?.render(tree(false)))
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(1)
await act(async () => root?.render(tree(true)))
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(1)
await act(async () => refresh.resolve())
await flush()
expect(button('Create Box').disabled).toBe(false)
})
it('polls only while open and foreground, and refreshes on returning to the page', async () => {
vi.useFakeTimers()
await rerenderOpen()
await act(async () => vi.advanceTimersByTimeAsync(10_000))
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(2)
await act(async () => focusManager.setFocused(false))
await act(async () => vi.advanceTimersByTimeAsync(20_000))
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(2)
await act(async () => focusManager.setFocused(true))
await flush()
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(3)
await act(async () => root?.render(withQueries(<CreateBoxDialog open={false} onOpenChange={() => {}} />)))
await act(async () => vi.advanceTimersByTimeAsync(30_000))
expect(organizationsApi.getOrganization).toHaveBeenCalledTimes(3)
})
it('does not request limits or allow creation without a selected organization', async () => {
state.org = null
await rerenderOpen()
expect(organizationsApi.getOrganization).not.toHaveBeenCalled()
expect(button('Create Box').disabled).toBe(true)
})
describe('the image field', () => {
function imageInput() {
return document.querySelector<HTMLInputElement>('input[aria-label="Image reference"]')
}
function menuItems() {
return [...document.querySelectorAll('[role="menuitem"]')].map((item) => item.textContent)
}
// The whole reason the field is free text: the catalog only ever contains
// images something already booted from, so the first box on a new image
// has nothing to pick.
it('sends no image at all when the field is left blank', async () => {
await renderOpen()
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ image: undefined }))
})
it('submits a reference the catalog has never heard of', async () => {
await renderOpen()
const input = imageInput()
if (!input) throw new Error('image reference field missing')
await act(async () => typeInto(input, 'quay.io/acme/app:v1'))
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ image: 'quay.io/acme/app:v1' }))
})
it('resizes the image menu and clears full-reference help when the field expands', async () => {
let width = 350
let available = 100
const observers: { callback: () => void; disconnect: ReturnType<typeof vi.fn>; target?: Element }[] = []
const previous = globalThis.ResizeObserver
globalThis.ResizeObserver = class {
callback: () => void
disconnect = vi.fn()
constructor(callback: ResizeObserverCallback) {
this.callback = () => callback([], this as unknown as ResizeObserver)
observers.push(this)
}
target?: Element
observe(target: Element) {
this.target = target
}
unobserve() {}
} as unknown as typeof ResizeObserver
try {
vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => width)
vi.spyOn(HTMLInputElement.prototype, 'clientWidth', 'get').mockImplementation(() => available)
vi.spyOn(HTMLInputElement.prototype, 'scrollWidth', 'get').mockReturnValue(200)
await renderOpen()
await act(async () => typeInto(imageInput()!, 'registry.example.com/team/image:v1'))
const description = imageInput()!.getAttribute('aria-describedby')
expect(description && document.getElementById(description)).toBeTruthy()
await openDropdown('Browse images')
expect(document.querySelector<HTMLElement>('[role="menu"]')?.style.width).toBe('350px')
width = 600
available = 500
const fieldObservers = observers.filter((observer) => observer.target === imageInput()!.parentElement)
await act(async () => fieldObservers.at(-1)!.callback())
expect(document.querySelector<HTMLElement>('[role="menu"]')?.style.width).toBe('600px')
expect(imageInput()!.getAttribute('aria-describedby')).toBeNull()
await act(async () => root?.unmount())
root = null
expect(fieldObservers.length).toBeGreaterThan(0)
for (const observer of fieldObservers) expect(observer.disconnect).toHaveBeenCalledOnce()
} finally {
globalThis.ResizeObserver = previous
}
})
it('fits the image menu to the whole field and keeps a long reference intact', async () => {
const ref = 'registry.example.com/team/' + 'long-repository-'.repeat(10) + 'image:release-2026-11-20'
state.catalogImages = [{ name: ref, curated: true, aliases: [] }]
vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(350)
vi.spyOn(HTMLInputElement.prototype, 'clientWidth', 'get').mockReturnValue(300)
vi.spyOn(HTMLInputElement.prototype, 'scrollWidth', 'get').mockReturnValue(1800)
await renderOpen()
await openDropdown('Browse images')
expect(document.querySelector<HTMLElement>('[role="menu"]')?.style.width).toBe('350px')
await selectMenuItem(ref)
expect(imageInput()?.value).toBe(ref)
const description = imageInput()?.getAttribute('aria-describedby')
expect(description && document.getElementById(description)?.textContent).toBe(ref)
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ image: ref }))
})
it('offers a curated image under its short name and never a tag', async () => {
state.catalogImages = [{ name: 'python', curated: true, aliases: [] }]
await renderOpen()
await openDropdown('Browse images')
expect(menuItems()).toEqual(['python'])
})
it('offers an organization image with its alias when exactly one is recorded', async () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1'] }]
await renderOpen()
await openDropdown('Browse images')
expect(menuItems()).toEqual(['quay.io/acme/app:v1'])
})
// Picking one of several aliases for the user would silently decide something
// they never said; the bare name leaves the choice with them.
it('offers the bare name when several aliases are recorded', async () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1', 'latest'] }]
await renderOpen()
await openDropdown('Browse images')
expect(menuItems()).toEqual(['quay.io/acme/app'])
})
it('fills the field from a suggestion and submits it', async () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1'] }]
await renderOpen()
await openDropdown('Browse images')
await selectMenuItem('quay.io/acme/app:v1')
expect(imageInput()?.value).toBe('quay.io/acme/app:v1')
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ image: 'quay.io/acme/app:v1' }))
})
it('says so rather than offering nothing when the catalog is empty', async () => {
await renderOpen()
await openDropdown('Browse images')
expect(menuItems()).toEqual(['No images yet'])
})
})
it('defaults auto-resume to enabled and submits the toggle state with create params', async () => {
await renderOpen()
const name = nameInput()
expect(name).toBeTruthy()
if (!name) throw new Error('expected name input to be rendered')
await act(async () => typeInto(name, 'resume-test'))
const autoResumeSwitch = document.querySelector<HTMLButtonElement>('button[aria-label="Wake on access"]')
expect(autoResumeSwitch).toBeTruthy()
expect(autoResumeSwitch?.getAttribute('data-state')).toBe('checked')
await act(async () => autoResumeSwitch?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
expect(autoResumeSwitch?.getAttribute('data-state')).toBe('unchecked')
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({
name: 'resume-test',
autoResume: false,
}),
)
})
it('defaults to stop-when-idle with no auto-delete, matching the previous defaults', async () => {
await renderOpen()
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ autoStopIntervalSeconds: 900, autoDelete: 0, autoResume: true }),
)
})
// The delete is entered as a delay *after* the stop, so the absolute value the
// API receives is always strictly later than the stop threshold — the
// relationship `validateLifecyclePolicy` enforces cannot be violated from the
// UI, which is why the Create button no longer needs to block on it.
it('submits auto-delete as an absolute value strictly later than auto-stop', async () => {
await renderOpen()
await openDropdown('Delete after stopping')
await selectMenuItem('1 hour')
await submit()
const params = mutationMocks.createBox.mock.calls.at(-1)?.[0]
expect(params.autoStopIntervalSeconds).toBe(900)
// 15m stop + the 1h delay picked above.
expect(params.autoDelete).toBe(900 + 3600)
expect(params.autoDelete).toBeGreaterThan(params.autoStopIntervalSeconds)
})
// Stop/Delete are already plain-English rows with real values ("15 min",
// "1 hour") — a third line re-deriving their sum, plus a raw `auto_delete=`
// payload line, restated what those two rows already say. Cut entirely
// rather than reworded; the submitted value is covered by the test above.
it('does not restate the stop+delay sum or the raw auto_delete payload', async () => {
await renderOpen()
await openDropdown('Delete after stopping')
await selectMenuItem('1 hour')
expect(document.body.textContent).not.toContain('Deletes')
expect(document.body.textContent).not.toContain('auto_delete=')
})
// "Never" (0) must be reachable only by deliberately picking it from a fixed
// list — the whole point of moving off free text was to make the old bug
// (clearing an input to retype silently sent 0) structurally impossible.
it('sends auto_stop=0 when "Never" is deliberately selected, and only then', async () => {
await renderOpen()
await submit()
expect(mutationMocks.createBox.mock.calls.at(-1)?.[0].autoStopIntervalSeconds).toBe(900)
await openDropdown('Stop when idle')
await selectMenuItem('Never')
await submit()
expect(mutationMocks.createBox.mock.calls.at(-1)?.[0].autoStopIntervalSeconds).toBe(0)
})
// Delete is framed as "after stopping" only while a stop is set; with Stop
// on "Never" there is no stop to be after, so the label switches to the
// idle-relative framing instead — same field, same aria-label, different copy.
it('relabels the delete field to "when idle" once Stop is set to Never', async () => {
await renderOpen()
await openDropdown('Stop when idle')
await selectMenuItem('Never')
expect(document.body.textContent).toContain('Delete when idle')
expect(document.body.textContent).not.toContain('Delete after stopping')
})
// The mount path rules are enforced server-side; replicating them in the form
// is only useful if the replica actually matches, so pin the set that must be
// rejected against apps/api/src/box/utils/volume-mount-path-validation.util.ts.
it('rejects exactly the mount paths the API rejects', () => {
expect(validateMountPath('/data')).toBeNull()
expect(validateMountPath('/mnt/models')).toBeNull()
expect(validateMountPath('')).toBeTruthy()
expect(validateMountPath('data')).toBeTruthy() // not absolute
expect(validateMountPath('/')).toBeTruthy()
expect(validateMountPath('//')).toBeTruthy()
expect(validateMountPath('/a/../b')).toBeTruthy()
expect(validateMountPath('/a/./b')).toBeTruthy()
expect(validateMountPath('/a//b')).toBeTruthy()
for (const dir of ['/proc', '/sys', '/dev', '/boot', '/etc', '/bin', '/sbin', '/lib', '/lib64']) {
expect(validateMountPath(dir)).toBeTruthy()
expect(validateMountPath(`${dir}/nested`)).toBeTruthy()
}
})
it('refuses two volumes on one mount path', () => {
expect(
validateMounts([
{ volumeId: 'a', mountPath: '/data' },
{ volumeId: 'b', mountPath: '/data' },
]),
).toMatch(/mount path/i)
expect(
validateMounts([
{ volumeId: 'a', mountPath: '/data' },
{ volumeId: 'b', mountPath: '/models' },
]),
).toBeNull()
})
// Mounts exist only at create time, so whatever the form holds has to reach
// the create call — there is no later chance to attach it.
// Leaving Name empty is a supported path: the API assigns an adjective-animal name
// (box.service.ts -> persistWithGeneratedBoxName) and, on a per-org name collision,
// retries once as "<name>-<boxId>". The dialog must say that out loud — the
// "my-new-box" placeholder otherwise reads as what an unnamed box will be called —
// and it must keep sending `undefined`, since sending a concrete name would take the
// branch that has no collision fallback.
it('says an empty name is auto-generated, and submits undefined so the API does it', async () => {
await rerenderOpen()
expect(document.body.textContent).toContain('auto-named like')
expect(document.body.textContent).toContain('cozy-otter')
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(expect.objectContaining({ name: undefined }))
})
// The Images page opens this from an image's row; the reference it hands
// over is what the box is created from.
it('submits the image it was pre-filled with', async () => {
await rerenderOpenWith({ prefillImage: 'ghcr.io/acme/agent:v1.4.2' })
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({ image: 'ghcr.io/acme/agent:v1.4.2' }),
)
})
it('submits the mounts it was pre-filled with', async () => {
await rerenderOpenWith({ prefillVolume: 'vol-1' })
const name = nameInput()
if (!name) throw new Error('expected name input to be rendered')
await act(async () => typeInto(name, 'with-volume'))
await submit()
expect(mutationMocks.createBox).toHaveBeenCalledWith(
expect.objectContaining({
name: 'with-volume',
volumes: [{ volumeId: 'vol-1', mountPath: '/data' }],
}),
)
})
// The API takes a mount by id or by name and resolves either to the volume's
// id, but a name is only unique within one organization — the picker holds
// the id, so that is what a click must submit.
it('submits the volume id, never the display name', async () => {
await rerenderOpen()
const addMount = [...document.querySelectorAll('button')].find((b) => /Mount a volume/.test(b.textContent ?? ''))
await act(async () => addMount?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
await openDropdown('Volume')
await selectMenuItem('subtitle-models')
const name = nameInput()
if (!name) throw new Error('expected name input to be rendered')
await act(async () => typeInto(name, 'picked-from-list'))
await submit()
const params = mutationMocks.createBox.mock.calls.at(-1)?.[0]
expect(params.volumes).toEqual([{ volumeId: 'vol-1', mountPath: '/data' }])
expect(JSON.stringify(params.volumes)).not.toContain('subtitle-models')
})
it('explains a volume without restating what Disk above already says', async () => {
await rerenderOpen()
expect(document.body.textContent).toContain('A volume persists independently of this box')
expect(document.body.textContent).not.toContain('scratch space')
})
// "Custom…" is a per-field escape hatch for a value the fixed list doesn't
// cover — not a second bundled-preset system. Picking it must swap in a
// plain amount+unit entry and actually change what gets submitted.
it('lets Stop when idle take an arbitrary value via "Custom…"', async () => {
await renderOpen()
await openDropdown('Stop when idle')
await selectMenuItem('Custom…')
const stopInput = document.querySelector<HTMLInputElement>('input[aria-label="Stop when idle"]')
expect(stopInput).toBeTruthy()
if (!stopInput) throw new Error('expected the custom stop input to be rendered')
await act(async () => typeInto(stopInput, '45'))
await act(async () => stopInput.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
await submit()
const params = mutationMocks.createBox.mock.calls.at(-1)?.[0]
expect(params.autoStopIntervalSeconds).toBe(45 * 60)
})
// After committing a custom value, the control must revert to its normal
// dropdown form (not stay stuck in text-entry mode) so the field still reads
// and behaves like the others once a value is set.
it('returns to dropdown form after a custom value is committed, showing that value', async () => {
await renderOpen()
await openDropdown('Stop when idle')
await selectMenuItem('Custom…')
const stopInput = document.querySelector<HTMLInputElement>('input[aria-label="Stop when idle"]')
if (!stopInput) throw new Error('expected the custom stop input to be rendered')
await act(async () => typeInto(stopInput, '45'))
await act(async () => stopInput.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
const trigger = document.querySelector<HTMLButtonElement>('button[aria-label="Stop when idle"]')
expect(trigger).toBeTruthy()
expect(trigger?.textContent).toBe('45m')
})
})
describe('CreateBoxDialog hourly price', () => {
let root: Root | null = null
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
state.org = makeOrg({ maxCpuPerBox: 4, maxMemoryPerBox: 8, maxDiskPerBox: 50 })
state.config = { billingApiUrl: 'http://billing.test' }
state.pricesQuery = { data: LIVE_PRICES, isLoading: false }
})
afterEach(() => {
act(() => root?.unmount())
root = null
document.body.innerHTML = ''
vi.restoreAllMocks()
})
async function renderOpen() {
const host = document.createElement('div')
document.body.appendChild(host)
await act(async () => {
root ??= createRoot(host)
root.render(withQueries(<CreateBoxDialog open onOpenChange={() => {}} />))
})
await flush()
}
async function pickSize(label: string) {
const sizeGroup = document.querySelector('[aria-label="Size"]')
const chip = sizeGroup
? [...sizeGroup.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
new RegExp(`^${label}`).test(b.textContent ?? ''),
)
: undefined
await act(async () => chip?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
}
it('quotes the default box from the published rates instead of $0.00', async () => {
await renderOpen()
// Shoebox = 1 vCPU / 1 GiB / 10 GiB → 5.04¢ + 1.44¢ + 0.18¢
expect(document.body.textContent).toContain('$0.0666')
expect(document.body.textContent).not.toContain('free in preview')
})
function breakdownToggle() {
return [...document.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
/Price breakdown/.test(b.textContent ?? ''),
)
}
it('opens pricing above the fixed footer without adding form scroll', async () => {
await renderOpen()
await act(async () => breakdownToggle()!.click())
await flush()
const breakdown = document.querySelector('[role="dialog"][aria-label="Price breakdown"]')!
expect(breakdown).not.toBeNull()
expect(breakdown.closest('.form-dialog-body')).toBeNull()
expect(document.querySelector('.form-dialog-body')?.contains(document.querySelector('.form-dialog-footer'))).toBe(
false,
)
})
it('keeps the breakdown collapsed until asked for it', async () => {
await renderOpen()
expect(breakdownToggle()?.getAttribute('aria-expanded')).toBe('false')
expect(document.body.textContent).not.toContain('vCPU·hr')
// The total is the decision, so it stays visible while the split is folded.
expect(document.body.textContent).toContain('$0.0666')
})
it('places an explicit price breakdown action beside the fixed total', async () => {
await renderOpen()
expect(document.body.textContent).not.toContain('Estimated rates for the full configuration.')
const footer = document.querySelector('.form-dialog-footer')
expect(footer?.textContent).toContain('Price breakdown')
const action = [...(footer?.querySelectorAll('button') ?? [])].find((b) => b.textContent === 'Price breakdown')
expect(action).toBeTruthy()
await act(async () => action?.click())
expect(document.body.textContent).toContain('Disk · 10 GiB × $0.00018/GiB·hr')
})
it('shows what the total is made of once expanded, including the disk line whole cents would hide', async () => {
await renderOpen()
const toggle = breakdownToggle()
await act(async () => toggle?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
const text = document.body.textContent ?? ''
expect(breakdownToggle()?.getAttribute('aria-expanded')).toBe('true')
expect(text).toContain('CPU · 1 vCPU × $0.0504/vCPU·hr')
expect(text).toContain('Memory · 1 GiB × $0.0144/GiB·hr')
expect(text).toContain('Disk · 10 GiB × $0.00018/GiB·hr')
})
it('re-quotes when the size changes', async () => {
await renderOpen()
await pickSize('Cargo')
// Cargo = 4 vCPU / 8 GiB / 50 GiB → 20.16¢ + 11.52¢ + 0.9¢
expect(document.body.textContent).toContain('$0.3258')
})
it('says free only when there is no billing service to charge anything', async () => {
state.config = {}
state.pricesQuery = { data: undefined, isLoading: false }
await renderOpen()
expect(document.body.textContent).toContain('No usage charges')
})
it('never reads as free when the rates fail to load', async () => {
state.pricesQuery = { data: undefined, isLoading: false }
await renderOpen()
const text = document.body.textContent ?? ''
expect(text).toContain('Unavailable')
expect(text).toContain('this box is not free')
expect(text).not.toContain('$0.00 ')
})
it('declines to quote rather than understate when a resource has no price', async () => {
state.pricesQuery = {
data: { ...LIVE_PRICES, prices: LIVE_PRICES.prices.filter((p) => p.code !== 'disk') },
isLoading: false,
}
await renderOpen()
expect(document.body.textContent).toContain('Unavailable')
})
})
// The trigger used to be built in and styled through `triggerClassName`. It is
// now a children slot, so both halves of that contract need holding: a page
// that passes a control gets a working opener, and a page that passes none —
// the Volumes list, which opens the dialog from a table row — gets no stray
// button of its own.
describe('CreateBoxDialog trigger slot', () => {
let root: Root | null = null
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
state.org = makeOrg({})
state.config = { billingApiUrl: 'http://billing.test' }
state.pricesQuery = { data: LIVE_PRICES, isLoading: false }
})
afterEach(() => {
act(() => root?.unmount())
root = null
document.body.innerHTML = ''
vi.restoreAllMocks()
})
/**
* Renders CreateBoxDialog with an optional trigger control to verify the children slot.
*/
async function renderWithTrigger(children?: ReactNode) {
const host = document.createElement('div')
document.body.appendChild(host)
await act(async () => {
root ??= createRoot(host)
root.render(withQueries(<CreateBoxDialog>{children}</CreateBoxDialog>))
})
await flush()
}
/**
* Checks whether the dialog is currently open by looking for its title text.
*/
function dialogIsOpen() {
return [...document.querySelectorAll('*')].some(
(el) => el.getAttribute('data-slot') === 'dialog-title' && el.textContent === 'New Box',
)
}
it('opens on the supplied control and returns focus there after Cancel', async () => {
await renderWithTrigger(<AsciiButton type="button">Launch a box</AsciiButton>)
const buttons = [...document.querySelectorAll<HTMLButtonElement>('button')]
const trigger = buttons.find((b) => b.textContent?.trim() === 'Launch a box')
expect(trigger).toBeDefined()
// Nothing but the caller's own control: the built-in "New Box" trigger this
// slot replaced must not still be rendered alongside it.
expect(buttons).toHaveLength(1)
expect(dialogIsOpen()).toBe(false)
await act(async () => trigger?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
expect(dialogIsOpen()).toBe(true)
const cancel = [...document.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === 'Cancel')!
await act(async () => cancel.click())
await flush()
expect(dialogIsOpen()).toBe(false)
expect(document.activeElement).toBe(trigger)
})
it('renders no button of its own when the caller passes none', async () => {
await renderWithTrigger()
expect(document.querySelectorAll('button')).toHaveLength(0)
expect(dialogIsOpen()).toBe(false)
})
})