Skip to content

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

feat(console): make sub-core Box sizing discoverable (#2990)

Manda3433ee824a01
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index 824eb9292..40f427841 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -3,6 +3,35 @@
The web console at `app.boxlite.ai`. A Vite + React app, built and tested
through Nx as the `dashboard` project.
+## Create Box sizing
+
+New Box presents six named presets from 0.125 to 4 vCPU, retaining the existing
+1 vCPU / 1 GiB / 10 GiB default. Sub-core presets pair CPU and memory at 1:2 (0.125/0.25, 0.25/0.5, 0.5/1), with 10 GiB disk;
+the names identify configurations, not guaranteed workload suitability.
+Each card shows its effective organization-capped configuration and complete hourly
+estimate from the existing usage-price query. Adjusted cards are labelled before
+selection; unavailable rates are never presented as a free quote.
+
+**Larger or custom box** opens the inline resource editor, scrolls it into view,
+and focuses CPU. It retains three-decimal CPU input. Its +/- controls move between 0.125, 0.25,
+0.5, 1, 2, 4, 8 and 16 vCPU, respecting a lower organization ceiling. CPU, memory
+and disk show separate estimated contributions, with the total beside Create Box.
+The fixed total includes a **Price breakdown** button that opens the CPU, memory
+and disk calculation above the footer, without scrolling through the form. The
+panel follows the current configuration and supports Escape to return to its trigger.
+A valid Custom draft survives preset comparisons within the open dialog and is
+clamped to current limits when restored. Closing or changing organization clears
+that saved draft. Creation still uses the existing REST mutation and server validation.
+
+**Browse images** is the visible catalog action beside the editable image reference.
+The Image suggestions menu tracks the entire input's width, including after dialog
+resizing. Long references wrap within the menu; an overflowing selected reference is
+also shown in full below the editable input. Neither presentation changes the image
+reference sent to the API.
+
+Volumes and Lifecycle are directly visible sections, without an Advanced disclosure.
+Their existing defaults, validation and submission behavior are unchanged.
+
## New-account email policy
First-account verification is enabled by the API's `TURNSTILE_SITEKEY`. Without
diff --git a/apps/dashboard/docs/create-box-sizing/README.md b/apps/dashboard/docs/create-box-sizing/README.md
new file mode 100644
index 000000000..b6e93f165
--- /dev/null
+++ b/apps/dashboard/docs/create-box-sizing/README.md
@@ -0,0 +1,9 @@
+# Create Box sizing
+
+See [behavior and constraints](../../README.md#create-box-sizing).
+
+Screenshots use the existing Console with mocked API responses. They demonstrate
+layout and estimated-rate presentation, not successful production provisioning.
+
+![Visible sub-core presets and fixed total](sizes.png)
+![CPU, memory and disk price calculation](pricing.png)
diff --git a/apps/dashboard/docs/create-box-sizing/pricing.png b/apps/dashboard/docs/create-box-sizing/pricing.png
new file mode 100644
index 000000000..172f7150a
Binary files /dev/null and b/apps/dashboard/docs/create-box-sizing/pricing.png differ
diff --git a/apps/dashboard/docs/create-box-sizing/sizes.png b/apps/dashboard/docs/create-box-sizing/sizes.png
new file mode 100644
index 000000000..20f0e4a39
Binary files /dev/null and b/apps/dashboard/docs/create-box-sizing/sizes.png differ
diff --git a/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx b/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx
index f01391723..8e7edb356 100644
--- a/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx
+++ b/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx
@@ -149,29 +149,18 @@ describe('CreateBoxDialog per-org resource cap', () => {
vi.restoreAllMocks()
})
- // Volumes and Lifecycle live behind one "Advanced" disclosure; these tests
- // are about the controls, so they open it first.
- async function openAdvanced() {
- const toggle = [...document.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
- /^[▸▾]\s*Advanced/.test((b.textContent ?? '').trim()),
- )
- if (toggle && toggle.getAttribute('aria-expanded') !== 'true') {
- await act(async () => toggle.dispatchEvent(new MouseEvent('click', { bubbles: true })))
- await flush()
- }
- }
-
async function renderOpen() {
const host = document.createElement('div')
document.body.appendChild(host)
await rerenderOpen(host)
- await openAdvanced()
- // Reveal the CPU/Memory/Disk steppers: Size defaults to the "Small" chip,
+ // 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) => /^Custom/.test(b.textContent ?? ''))
+ ? [...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()
@@ -201,6 +190,174 @@ describe('CreateBoxDialog per-org resource cap', () => {
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"]')
}
@@ -248,7 +405,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
expect(document.body.textContent).toMatch(/CPU\s*4\s*vCPU/)
})
- it('does not pin the input to a dashboard-local ceiling when the org max is unset', async () => {
+ 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()
@@ -257,8 +414,8 @@ describe('CreateBoxDialog per-org resource cap', () => {
await act(async () => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })))
await flush()
- expect(input.value).toBe('123123')
- expect(document.body.textContent).not.toContain('[email protected]')
+ 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 () => {
@@ -310,7 +467,9 @@ describe('CreateBoxDialog per-org resource cap', () => {
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.textContent === 'Medium')
+ 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 })))
@@ -319,7 +478,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
expect(document.body.textContent).toMatch(/2 vCPU.*4 GiB.*10 GiB/)
})
- // Regression guard for the Size preset clamp: picking "Large" (4/8/50) against
+ // 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 () => {
@@ -327,12 +486,14 @@ describe('CreateBoxDialog per-org resource cap', () => {
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.textContent === 'Large')
+ 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()
- // Large asks for 4 vCPU; the org caps at 2 — clamped, not silently dropped.
+ // 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/)
@@ -350,7 +511,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
await act(async () => decrease?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await flush()
- expect(input.value).toBe('3.9')
+ expect(input.value).toBe('2')
expect(document.body.textContent).not.toContain('[email protected]')
})
@@ -416,9 +577,9 @@ describe('CreateBoxDialog per-org resource cap', () => {
})
it.each([
- ['Small', 1, 1024, 10],
- ['Medium', 2, 4096, 20],
- ['Large', 4, 8192, 50],
+ ['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) =>
@@ -483,7 +644,9 @@ describe('CreateBoxDialog per-org resource cap', () => {
})
function button(label: string) {
- const found = [...document.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === label)
+ 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
}
@@ -500,8 +663,8 @@ describe('CreateBoxDialog per-org resource cap', () => {
}
it.each([
- ['Medium', 20],
- ['Large', 50],
+ ['Crate', 20],
+ ['Cargo', 50],
])('submits %s unchanged while the first limits request hangs', async (label, diskSize) => {
deferRefresh()
await rerenderOpen()
@@ -536,7 +699,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
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('Large').click())
+ await act(async () => button('Cargo').click())
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0]).disk_size_gb).toBe(50)
})
@@ -544,7 +707,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
it('restores the selected preset when background refresh raises the limits', async () => {
vi.useFakeTimers()
await rerenderOpen()
- await act(async () => button('Medium').click())
+ 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'))
@@ -601,10 +764,10 @@ describe('CreateBoxDialog per-org resource cap', () => {
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 16 vCPU')
+ expect(document.body.textContent).not.toContain('Max 32 GiB')
await act(async () => refresh.resolve())
await flush()
- await act(async () => button('Large').click())
+ await act(async () => button('Cargo').click())
await submit()
expect(toBoxApiCreateRequest(mutationMocks.createBox.mock.calls[0][0])).toMatchObject({
cpus: 2,
@@ -696,11 +859,71 @@ describe('CreateBoxDialog per-org resource cap', () => {
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('Choose a known image')
+ await openDropdown('Browse images')
expect(menuItems()).toEqual(['python'])
})
@@ -709,7 +932,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1'] }]
await renderOpen()
- await openDropdown('Choose a known image')
+ await openDropdown('Browse images')
expect(menuItems()).toEqual(['quay.io/acme/app:v1'])
})
@@ -720,7 +943,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1', 'latest'] }]
await renderOpen()
- await openDropdown('Choose a known image')
+ await openDropdown('Browse images')
expect(menuItems()).toEqual(['quay.io/acme/app'])
})
@@ -729,7 +952,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
state.catalogImages = [{ name: 'quay.io/acme/app', curated: false, aliases: ['v1'] }]
await renderOpen()
- await openDropdown('Choose a known image')
+ await openDropdown('Browse images')
await selectMenuItem('quay.io/acme/app:v1')
expect(imageInput()?.value).toBe('quay.io/acme/app:v1')
@@ -741,7 +964,7 @@ describe('CreateBoxDialog per-org resource cap', () => {
it('says so rather than offering nothing when the catalog is empty', async () => {
await renderOpen()
- await openDropdown('Choose a known image')
+ await openDropdown('Browse images')
expect(menuItems()).toEqual(['No images yet'])
})
@@ -930,7 +1153,6 @@ describe('CreateBoxDialog per-org resource cap', () => {
// the id, so that is what a click must submit.
it('submits the volume id, never the display name', async () => {
await rerenderOpen()
- await openAdvanced()
const addMount = [...document.querySelectorAll('button')].find((b) => /Mount a volume/.test(b.textContent ?? ''))
await act(async () => addMount?.dispatchEvent(new MouseEvent('click', { bubbles: true })))
@@ -951,7 +1173,6 @@ describe('CreateBoxDialog per-org resource cap', () => {
it('explains a volume without restating what Disk above already says', async () => {
await rerenderOpen()
- await openAdvanced()
expect(document.body.textContent).toContain('A volume persists independently of this box')
expect(document.body.textContent).not.toContain('scratch space')
})
@@ -1040,24 +1261,24 @@ describe('CreateBoxDialog hourly price', () => {
it('quotes the default box from the published rates instead of $0.00', async () => {
await renderOpen()
- // Small = 1 vCPU / 1 GiB / 10 GiB → 5.04¢ + 1.44¢ + 0.18¢
+ // 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) =>
- /Est\. price per hour/.test(b.textContent ?? ''),
+ /Price breakdown/.test(b.textContent ?? ''),
)
}
- it('keeps expanded pricing inside the scrollable form body', async () => {
+ 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('#box-price-breakdown')!
+ const breakdown = document.querySelector('[role="dialog"][aria-label="Price breakdown"]')!
expect(breakdown).not.toBeNull()
- expect(breakdown.closest('.form-dialog-body')).not.toBeNull()
+ expect(breakdown.closest('.form-dialog-body')).toBeNull()
expect(document.querySelector('.form-dialog-body')?.contains(document.querySelector('.form-dialog-footer'))).toBe(
false,
)
@@ -1072,6 +1293,17 @@ describe('CreateBoxDialog hourly price', () => {
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()
@@ -1088,9 +1320,9 @@ describe('CreateBoxDialog hourly price', () => {
it('re-quotes when the size changes', async () => {
await renderOpen()
- await pickSize('Large')
+ await pickSize('Cargo')
- // Large = 4 vCPU / 8 GiB / 50 GiB → 20.16¢ + 11.52¢ + 0.9¢
+ // Cargo = 4 vCPU / 8 GiB / 50 GiB → 20.16¢ + 11.52¢ + 0.9¢
expect(document.body.textContent).toContain('$0.3258')
})
@@ -1099,7 +1331,7 @@ describe('CreateBoxDialog hourly price', () => {
state.pricesQuery = { data: undefined, isLoading: false }
await renderOpen()
- expect(document.body.textContent).toContain('free in preview')
+ expect(document.body.textContent).toContain('No usage charges')
})
it('never reads as free when the rates fail to load', async () => {
diff --git a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx b/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
index 93404c0de..443c20cd3 100644
--- a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
+++ b/apps/dashboard/src/components/Box/CreateBoxDialog.tsx
@@ -10,10 +10,11 @@ import {
FormDialogBody,
} from '@/components/ui/form-dialog'
import { AsciiButton } from '@/components/ascii'
-import { AsciiChip, BRAND, PanelNote } from '@/components/ascii'
+import { BRAND, PanelNote } from '@/components/ascii'
import { Dialog, DialogDescription, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Switch } from '@/components/ui/switch'
+import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'
import { RoutePath } from '@/enums/RoutePath'
import { useCreateBoxMutation } from '@/hooks/mutations/useCreateBoxMutation'
import { useConfig } from '@/hooks/useConfig'
@@ -30,10 +31,12 @@ import { VolumeState } from '@boxlite-ai/api-client'
import { cn } from '@/lib/utils'
import type { Box } from '@boxlite-ai/api-client'
import { ChevronDown } from '@/components/ui/icon'
-import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'
import { generatePath, useNavigate } from 'react-router-dom'
import { toast } from 'sonner'
+const CPU_STOPS = [0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
+
const NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
const DEFAULTS = {
@@ -75,6 +78,7 @@ function Stepper({
max,
onExceed,
fractional = false,
+ wholeMiB = false,
onValidityChange,
}: {
value: number
@@ -82,6 +86,7 @@ function Stepper({
min?: number
max?: number
onExceed?: () => void
+ wholeMiB?: boolean
fractional?: boolean
onValidityChange?: (valid: boolean) => void
}) {
@@ -103,7 +108,11 @@ function Stepper({
const handleTyped = (raw: string) => {
if (fractional) {
const n = Number(raw)
- const valid = /^\d+(?:\.\d{0,3})?$/.test(raw) && Number.isFinite(n) && n >= min
+ const valid =
+ (wholeMiB ? /^\d+(?:\.\d*)?$/ : /^\d+(?:\.\d{0,3})?$/).test(raw) &&
+ Number.isFinite(n) &&
+ n >= min &&
+ (!wholeMiB || Number.isInteger(n * 1024))
setInvalid(!valid)
onValidityChange?.(valid)
if (!valid) {
@@ -149,7 +158,9 @@ function Stepper({
<button
type="button"
aria-label="decrease"
- onClick={() => onChange(clamp(fractional ? (Math.round(value * 1000) - 100) / 1000 : value - 1))}
+ onClick={() =>
+ onChange(clamp(fractional ? ([...CPU_STOPS].reverse().find((stop) => stop < value) ?? min) : value - 1))
+ }
disabled={value <= min}
className={cn(btn, 'border-r border-border')}
>
@@ -159,7 +170,13 @@ function Stepper({
value={text}
inputMode={fractional ? 'decimal' : 'numeric'}
aria-invalid={invalid}
- title={invalid ? 'Enter at least 0.125 CPU with up to three decimal places' : undefined}
+ title={
+ invalid
+ ? wholeMiB
+ ? 'Enter memory in whole MiB increments, at least 0.125 GiB'
+ : 'Enter at least 0.125 CPU with up to three decimal places'
+ : undefined
+ }
aria-label="value"
onChange={(e) => handleTyped(e.target.value)}
onBlur={(e) => commit(e.target.value)}
@@ -171,7 +188,7 @@ function Stepper({
<button
type="button"
aria-label="increase"
- onClick={() => onChange(clamp(fractional ? (Math.round(value * 1000) + 100) / 1000 : value + 1))}
+ onClick={() => onChange(clamp(fractional ? (CPU_STOPS.find((stop) => stop > value) ?? value + 1) : value + 1))}
disabled={max != null && value >= max}
className={cn(btn, 'border-l border-border')}
>
@@ -185,6 +202,7 @@ function Stepper({
// full-width below the grid (see CappedResourcesNote) rather than cramped under
// each narrow column.
function ResourceField({
+ estimate,
label,
unit,
value,
@@ -194,6 +212,7 @@ function ResourceField({
fractional,
onValidityChange,
}: {
+ estimate?: string
label: string
unit: string
value: number
@@ -215,8 +234,10 @@ function ResourceField({
max={max}
onExceed={onExceed}
fractional={fractional}
+ wholeMiB={label === 'Memory'}
onValidityChange={onValidityChange}
/>
+ {estimate && <span className="font-mono text-meta text-muted-foreground">{estimate} / hr</span>}
{max != null && (
<span className="font-mono text-meta text-muted-foreground">
Max {max} {unit}
@@ -247,83 +268,26 @@ function CappedResourcesNote({ items }: { items: { label: string; unit: string;
}
// ── Price ───────────────────────────────────────────────────────────────────
-// Quoted from Commerce's published rates so the number tracks the size chosen
-// above. Three absences are kept distinct, because collapsing them is how a
-// dialog ends up claiming a box is free when it is not:
-//
-// no billing service — nothing is charged, and saying "free" is the truth
-// rates still loading — we do not know the price yet
-// rates unavailable — we do not know the price, and usage is metered anyway
-//
-// Only the first may render as $0.00. Commerce settles the real charge, so this
-// is labelled an estimate rather than a price.
-/** Quotes the selected resource size from published rates while distinguishing loading, unavailable, and unmetered states. */
-function BoxPriceRow({ cpu, memory, disk }: BoxSpec) {
- const config = useConfig()
- const pricesQuery = useUsagePricesQuery()
- const quote = boxHourlyPrice(pricesQuery.data, { cpu, memory, disk })
- const [breakdownOpen, setBreakdownOpen] = useState(false)
-
- const ROW = 'flex shrink-0 flex-col gap-1 border-t border-border px-4 py-4 sm:px-6'
- const LABEL = 'form-field-label'
- const FIGURE = 'font-mono text-section font-bold tracking-[-0.5px] sm:text-page'
-
- if (!config.billingApiUrl) {
- return (
- <div className={cn(ROW, 'sm:flex-row sm:items-baseline sm:justify-between')}>
- <span className={LABEL}>Price per hour</span>
- <span className={FIGURE}>
- $0.00 <span className="text-meta font-normal text-muted-foreground">/ hr · free in preview</span>
- </span>
- </div>
- )
- }
-
- if (!quote) {
- const loading = pricesQuery.isLoading
- return (
- <div className={ROW}>
- <div className="flex flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between">
- <span className={LABEL}>Est. price per hour</span>
- <span className={cn(FIGURE, 'text-muted-foreground')}>{loading ? '—' : 'Unavailable'}</span>
- </div>
- <PanelNote>
- {loading
- ? 'Fetching current rates.'
- : 'Current rates could not be loaded. Usage is still metered — this box is not free.'}
- </PanelNote>
- </div>
- )
- }
-
- // The total is the decision; how it splits across CPU/memory/disk is the
- // audit. Collapsed by default so the row stays one line, on the same `▸`
- // affordance the sibling Size / Lifecycle / Volumes labels already use.
+function BoxPriceBreakdown({ quote }: { quote: NonNullable<ReturnType<typeof boxHourlyPrice>> }) {
return (
- <div className={ROW}>
- <div className="flex flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between">
- <button
- type="button"
- aria-expanded={breakdownOpen}
- aria-controls="box-price-breakdown"
- onClick={() => setBreakdownOpen((wasOpen) => !wasOpen)}
- className={cn(
- LABEL,
- 'mb-0 inline-flex min-h-6 items-center gap-1 self-start transition-colors hover:text-foreground',
- )}
- >
- <span style={{ color: BRAND }}>{breakdownOpen ? '▾' : '▸'}</span> Est. price per hour
- </button>
- <span className={FIGURE}>
- {formatPriceCents(quote.totalCents)}
- <span className="text-meta font-normal text-muted-foreground"> / hr</span>
- </span>
- </div>
- {breakdownOpen && (
- <div id="box-price-breakdown" className="mt-1 flex flex-col gap-0.5">
+ <Popover>
+ <PopoverTrigger asChild>
+ <AsciiButton size="sm">Price breakdown</AsciiButton>
+ </PopoverTrigger>
+ <PopoverContent
+ side="top"
+ align="start"
+ aria-label="Price breakdown"
+ className="w-[440px] max-w-[calc(100vw-32px)] max-h-[var(--radix-popover-content-available-height)] overflow-y-auto"
+ >
+ <div className="mb-3 text-body font-medium">Estimated cost per hour</div>
+ <div className="space-y-3">
{quote.lines.map((line) => (
- <div key={line.code} className="flex items-baseline justify-between gap-3 font-mono text-meta">
- <span className="text-muted-foreground">
+ <div
+ key={line.code}
+ className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 font-mono text-meta"
+ >
+ <span className="min-w-0 flex-1 text-muted-foreground [overflow-wrap:anywhere]">
{line.label} · {line.quantity} {line.quantityUnit} × {formatPriceCents(line.unitPriceCents, 6)}/
{line.quantityUnit}·hr
</span>
@@ -331,8 +295,12 @@ function BoxPriceRow({ cpu, memory, disk }: BoxSpec) {
</div>
))}
</div>
- )}
- </div>
+ <div className="mt-3 flex items-baseline justify-between gap-3 border-t border-border pt-3 text-body">
+ <span>Total</span>
+ <span className="font-mono">{formatPriceCents(quote.totalCents)} / hr</span>
+ </div>
+ </PopoverContent>
+ </Popover>
)
}
@@ -343,9 +311,12 @@ function BoxPriceRow({ cpu, memory, disk }: BoxSpec) {
// mirror the Lifecycle pattern (chips + a `Custom` escape hatch) so the two
// sections teach one interaction, not two.
const SIZE_PRESETS = [
- { id: 'small', label: 'Small', cpu: 1, memory: 1, disk: 10 },
- { id: 'medium', label: 'Medium', cpu: 2, memory: 4, disk: 20 },
- { id: 'large', label: 'Large', cpu: 4, memory: 8, disk: 50 },
+ { id: 'matchbox', label: 'Matchbox', cpu: 0.125, memory: 0.25, disk: 10 },
+ { id: 'pocket', label: 'Pocket', cpu: 0.25, memory: 0.5, disk: 10 },
+ { id: 'lunchbox', label: 'Lunchbox', cpu: 0.5, memory: 1, disk: 10 },
+ { id: 'small', label: 'Shoebox', cpu: 1, memory: 1, disk: 10 },
+ { id: 'medium', label: 'Crate', cpu: 2, memory: 4, disk: 20 },
+ { id: 'large', label: 'Cargo', cpu: 4, memory: 8, disk: 50 },
{ id: 'custom', label: 'Custom', cpu: null, memory: null, disk: null },
] as const
@@ -658,7 +629,15 @@ export const CreateBoxDialog = ({
const { data: catalogImages = [] } = useImagesQuery()
// Only confirmed effective limits constrain input; the server validates unknown limits on creation.
- const limits = resolvePerBoxLimits(confirmedLimits)
+ const resolvedLimits = resolvePerBoxLimits(confirmedLimits)
+ const limits = { ...resolvedLimits, cpu: Math.min(resolvedLimits.cpu ?? 16, 16) }
+ const config = useConfig()
+ const pricesQuery = useUsagePricesQuery()
+ const effectiveSpec = (spec: BoxSpec): BoxSpec => ({
+ cpu: Math.min(spec.cpu, limits.cpu),
+ memory: Math.min(spec.memory, limits.memory ?? spec.memory),
+ disk: Math.min(spec.disk, limits.disk ?? spec.disk),
+ })
// A DEFAULT value can exceed a stricter per-org cap (e.g. DEFAULTS.disk=10
// vs an org's maxDiskPerBox=3), which would otherwise send an over-limit
@@ -669,20 +648,57 @@ export const CreateBoxDialog = ({
const [name, setName] = useState('')
const [imageRef, setImageRef] = useState('')
+ const [imageControl, setImageControl] = useState<HTMLDivElement | null>(null)
+ const [imageMenuWidth, setImageMenuWidth] = useState(0)
+ const [imageRefOverflows, setImageRefOverflows] = useState(false)
+ const imageDescriptionId = useId()
+ useEffect(() => {
+ if (!imageControl) return
+ const measure = () => {
+ // offsetWidth is unaffected by the dialog's opening scale animation.
+ setImageMenuWidth(imageControl.offsetWidth)
+ const input = imageControl.querySelector('input')
+ setImageRefOverflows(Boolean(imageRef && input && input.scrollWidth > input.clientWidth))
+ }
+ measure()
+ if (typeof ResizeObserver === 'undefined') return
+ const observer = new ResizeObserver(measure)
+ observer.observe(imageControl)
+ return () => observer.disconnect()
+ }, [imageControl, imageRef])
+
const [cpu, setCpu] = useState(initialCpu)
const [cpuValid, setCpuValid] = useState(true)
+ const [memoryValid, setMemoryValid] = useState(true)
+ const resourceDescriptionId = useId()
+ const customDraft = useRef<BoxSpec | null>(null)
+ useEffect(() => {
+ customDraft.current = null
+ }, [selectedOrganization?.id])
const [memory, setMemory] = useState(initialMemory)
const [disk, setDisk] = useState(initialDisk)
+ const selectedQuote = boxHourlyPrice(pricesQuery.data, { cpu, memory, disk })
+ const resourceEstimate = (code: string) => {
+ if (!config.billingApiUrl) return '$0.00'
+ const line = selectedQuote?.lines.find((item) => item.code === code)
+ return line ? formatPriceCents(line.subtotalCents, 6) : '—'
+ }
// 0 means "never" for both — a legitimate value, not the accidental-empty-input
// bug the old free-text field had, because a dropdown has no empty state.
const [stopSeconds, setStopSeconds] = useState(DEFAULTS.autoStopIntervalSeconds)
const [deleteDelaySeconds, setDeleteDelaySeconds] = useState(0)
const [autoResume, setAutoResumeEnabled] = useState(true)
- // A mount handed in by the caller (Volumes → "+ Box") is the reason the
- // dialog opened, so the section it lives in starts open.
- const [showAdvanced, setShowAdvanced] = useState(() => Boolean(prefillVolume))
const [mounts, setMounts] = useState<BoxVolumeMount[]>([])
const [sizePreset, setSizePreset] = useState<SizePresetId>('small')
+ const customResourcesRef = useRef<HTMLDivElement>(null)
+ const focusCustomResources = () => {
+ customResourcesRef.current?.querySelector('input')?.focus({ preventScroll: true })
+ customResourcesRef.current?.scrollIntoView?.({ block: 'nearest' })
+ }
+ useEffect(() => {
+ if (open && sizePreset === 'custom') focusCustomResources()
+ }, [open, sizePreset])
+
const [submitting, setSubmitting] = useState(false)
const [capped, setCapped] = useState({ cpu: false, memory: false, disk: false })
@@ -698,6 +714,7 @@ export const CreateBoxDialog = ({
wasOpenRef.current = open
if (!open || wasOpen) return
+ customDraft.current = null
setName('')
setImageRef(prefillImage ?? '')
setCpu(initialCpu)
@@ -711,6 +728,7 @@ export const CreateBoxDialog = ({
setMounts(prefillVolume ? [{ volumeId: prefillVolume, mountPath: '/data' }] : [])
setSizePreset('small')
setCpuValid(true)
+ setMemoryValid(true)
setSubmitting(false)
setCapped({ cpu: false, memory: false, disk: false })
}, [open, initialCpu, initialMemory, initialDisk, prefillVolume, prefillImage])
@@ -770,8 +788,25 @@ export const CreateBoxDialog = ({
// catch up silently. A pick the user just made deserves an explanation for
// why the number on screen doesn't match the tier they clicked.
const applySizePreset = (id: SizePresetId) => {
+ if (id === sizePreset) {
+ if (id === 'custom') focusCustomResources()
+ return
+ }
+ if (sizePreset === 'custom' && cpuValid && memoryValid) customDraft.current = { cpu, memory, disk }
+ if (id === 'custom' && customDraft.current) {
+ const restored = effectiveSpec(customDraft.current)
+ setCpu(restored.cpu)
+ setMemory(restored.memory)
+ setDisk(restored.disk)
+ setCapped({
+ cpu: restored.cpu !== customDraft.current.cpu,
+ memory: restored.memory !== customDraft.current.memory,
+ disk: restored.disk !== customDraft.current.disk,
+ })
+ }
setSizePreset(id)
setCpuValid(true)
+ setMemoryValid(true)
const spec = SIZE_PRESETS.find((p) => p.id === id)
if (!spec || spec.cpu == null || spec.memory == null || spec.disk == null) return // `custom` only reveals the controls
const nextCpu = limits.cpu != null && spec.cpu > limits.cpu ? limits.cpu : spec.cpu
@@ -784,7 +819,7 @@ export const CreateBoxDialog = ({
}
const handleCreate = async () => {
- if (!cpuValid) return
+ if (!cpuValid || !memoryValid) return
if (!selectedOrganization?.id) {
toast.error('Select an organization to create a box.')
return
@@ -834,7 +869,7 @@ export const CreateBoxDialog = ({
<Dialog open={open} onOpenChange={setOpen}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
- <DialogContent className={cn('sm:max-w-[560px]', className)}>
+ <DialogContent className={cn('sm:max-w-[760px]', className)}>
<DialogHeader>
<DialogTitle>New Box</DialogTitle>
<DialogDescription className="sr-only">Create a Box for your agent.</DialogDescription>
@@ -862,32 +897,37 @@ export const CreateBoxDialog = ({
</div>
</div>
- <div className="flex flex-col gap-[9px]">
+ <div className="flex min-w-0 flex-col gap-[9px]">
<div className="form-field-label">Image</div>
{/* Free text with the catalog as suggestions, not a closed list:
any reference the operator's allowlist admits is valid here,
and an image only enters the catalog after something has
already booted from it — so a picker of known images could
never offer the first one. */}
- <div className="flex items-stretch border border-border bg-card focus-within:border-brand">
+ <div
+ ref={setImageControl}
+ className="flex min-w-0 items-stretch border border-border bg-card focus-within:border-brand"
+ >
<input
value={imageRef}
onChange={(e) => setImageRef(e.target.value)}
placeholder="Default image"
aria-label="Image reference"
+ aria-describedby={imageRefOverflows ? imageDescriptionId : undefined}
className="w-full min-w-0 border-0 bg-transparent px-[13px] py-[11px] font-mono text-body text-foreground outline-none placeholder:text-muted-foreground"
/>
<DropdownMenu>
<DropdownMenuTrigger
- aria-label="Choose a known image"
- title="Choose a known image"
- className="flex shrink-0 items-center px-[11px] text-muted-foreground outline-none transition-colors hover:text-foreground data-[state=open]:text-foreground"
+ aria-label="Browse images"
+ className="flex shrink-0 items-center gap-2 border-l border-border px-[11px] text-meta text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
+ Browse images
<ChevronDown className="size-3.5" />
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
- className="max-h-[260px] min-w-[var(--radix-dropdown-menu-trigger-width)] overflow-y-auto font-mono text-meta"
+ style={{ width: imageMenuWidth || undefined }}
+ className="max-h-[min(260px,var(--radix-dropdown-menu-content-available-height))] min-w-0 max-w-[calc(100vw-32px)] overflow-x-hidden overflow-y-auto font-mono text-meta"
>
{imageSuggestions.length === 0 ? (
<DropdownMenuItem disabled>No images yet</DropdownMenuItem>
@@ -895,7 +935,10 @@ export const CreateBoxDialog = ({
imageSuggestions.map((suggestion) => (
<DropdownMenuItem
key={suggestion.ref}
- className={cn('cursor-pointer', suggestion.ref === imageRef && 'text-brand')}
+ className={cn(
+ 'min-w-0 cursor-pointer whitespace-normal [overflow-wrap:anywhere]',
+ suggestion.ref === imageRef && 'text-brand',
+ )}
onClick={() => setImageRef(suggestion.ref)}
>
{suggestion.ref}
@@ -905,6 +948,14 @@ export const CreateBoxDialog = ({
</DropdownMenuContent>
</DropdownMenu>
</div>
+ {imageRefOverflows && (
+ <p
+ id={imageDescriptionId}
+ className="min-w-0 font-mono text-meta text-muted-foreground [overflow-wrap:anywhere]"
+ >
+ {imageRef}
+ </p>
+ )}
<div className="font-sans text-meta leading-relaxed text-muted-foreground">
Optional — any reference your operator allows. The first box on a new image waits for it to be pulled.
</div>
@@ -916,36 +967,86 @@ export const CreateBoxDialog = ({
it costs is not an advanced concern; it gets the same visibility
as Lifecycle and Volumes below. */}
<fieldset aria-label="Box resources" className="flex min-w-0 flex-col gap-[13px] border-t border-border pt-5">
- {/* Matches the sibling `▸ Lifecycle` / `▸ Volumes` treatment rather
- than `ascii.SectionTitle`: inside this dialog the established
- label scale is 10px/1.2px (Name, Image), and SectionTitle's
- 11px/1.5px heading would read as a different tier from its own
- siblings. */}
- <div className="form-field-label">
- <span style={{ color: BRAND }}>▸</span> Size
- </div>
-
- {(limitsError || !confirmedLimits) && (
- <p role="status" className="font-sans text-meta text-muted-foreground">
- {limitsError
- ? confirmedLimits
- ? 'Could not refresh limits. Showing last known limits.'
- : 'Could not load limits. Limits are checked when you create.'
- : 'Limits are checked when you create.'}
- </p>
- )}
- <div role="group" aria-label="Size" className="grid grid-cols-2 gap-[6px] sm:grid-cols-4">
- {SIZE_PRESETS.map((p) => (
- <AsciiChip
- key={p.id}
- selected={sizePreset === p.id}
- aria-pressed={sizePreset === p.id}
- onClick={() => applySizePreset(p.id)}
- className="px-2 py-[7px] font-sans text-meta"
+ <div role="group" aria-label="Size" className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="form-field-label mb-0">Size</div>
+ <AsciiButton
+ aria-label="Larger or custom box"
+ aria-pressed={sizePreset === 'custom'}
+ variant="secondary"
+ className={sizePreset === 'custom' ? 'border-foreground bg-secondary' : undefined}
+ aria-expanded={sizePreset === 'custom'}
+ aria-controls={`${resourceDescriptionId}-custom`}
+ size="sm"
+ onClick={() => applySizePreset('custom')}
>
- {p.label}
- </AsciiChip>
- ))}
+ Larger or custom box
+ </AsciiButton>
+ </div>
+ {(limitsError || !confirmedLimits) && (
+ <p role="status" className="font-sans text-meta text-muted-foreground">
+ {limitsError
+ ? confirmedLimits
+ ? 'Could not refresh limits. Showing last known limits.'
+ : 'Could not load limits. Limits are checked when you create.'
+ : 'Limits are checked when you create.'}
+ </p>
+ )}
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ {SIZE_PRESETS.filter((p) => p.id !== 'custom').map((p, index) => {
+ const spec = effectiveSpec({ cpu: p.cpu, memory: p.memory, disk: p.disk })
+ const adjusted = spec.cpu !== p.cpu || spec.memory !== p.memory || spec.disk !== p.disk
+ const quote = boxHourlyPrice(pricesQuery.data, spec)
+ const selected = sizePreset === p.id
+ return (
+ <button
+ key={p.id}
+ type="button"
+ aria-label={p.label}
+ aria-describedby={`${resourceDescriptionId}-${p.id}`}
+ aria-pressed={selected}
+ onClick={() => applySizePreset(p.id)}
+ className={cn(
+ 'group min-w-0 border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ selected
+ ? 'border-foreground bg-secondary'
+ : 'border-border hover:border-muted-foreground hover:bg-accent',
+ )}
+ >
+ <span className="mb-1 flex items-center justify-between gap-2">
+ <span className="text-body font-medium">{p.label}</span>
+ <svg
+ aria-hidden="true"
+ viewBox="0 0 32 32"
+ className={cn('size-7 shrink-0', selected ? 'text-foreground' : 'text-muted-foreground')}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ >
+ <g transform={`translate(16 16) scale(${0.55 + index * 0.085}) translate(-16 -16)`}>
+ <path d="M16 2 29 9.5v13L16 30 3 22.5v-13Z M3 9.5 16 17l13-7.5 M16 17v13 M9.5 5.75l13 7.5" />
+ </g>
+ </svg>
+ </span>
+ <span id={`${resourceDescriptionId}-${p.id}`} className="block">
+ <span className="block font-mono text-em">
+ {spec.cpu} <span className="text-meta text-muted-foreground">vCPU</span>
+ </span>
+ <span className="mt-1 block text-meta text-muted-foreground">
+ {spec.memory} GiB RAM · {spec.disk} GiB disk
+ </span>
+ <span className="mt-2 flex flex-wrap items-baseline justify-between gap-1 border-t border-border pt-2">
+ <span className="font-mono text-body">
+ {!config.billingApiUrl ? '$0.00' : quote ? formatPriceCents(quote.totalCents) : '—'}
+ <span className="font-sans text-meta text-muted-foreground"> / hr</span>
+ </span>
+ {adjusted && <span className="text-meta text-warning-foreground">Adjusted</span>}
+ </span>
+ </span>
+ </button>
+ )
+ })}
+ </div>
</div>
{/* Hidden once Custom is open: the steppers below already show
@@ -954,7 +1055,7 @@ export const CreateBoxDialog = ({
there's no other visible readout of the current size. */}
{sizePreset !== 'custom' && (
<div className="font-mono text-meta text-muted-foreground">
- {cpu} vCPU · {memory} GiB RAM · {disk} GiB disk
+ Selected: {cpu} vCPU · {memory} GiB RAM · {disk} GiB disk
</div>
)}
@@ -971,11 +1072,16 @@ export const CreateBoxDialog = ({
/>
{sizePreset === 'custom' && (
- <div className="grid grid-cols-1 gap-[14px] border-t border-dashed border-border pt-[13px] sm:grid-cols-3">
+ <div
+ ref={customResourcesRef}
+ id={`${resourceDescriptionId}-custom`}
+ className="grid scroll-mt-4 grid-cols-1 gap-[14px] border-t border-dashed border-border pt-[13px] sm:grid-cols-3"
+ >
<ResourceField
fractional
onValidityChange={setCpuValid}
label="CPU"
+ estimate={cpuValid ? resourceEstimate('cpu') : '—'}
unit="vCPU"
value={cpu}
onChange={changeResource('cpu', setCpu)}
@@ -983,7 +1089,10 @@ export const CreateBoxDialog = ({
onExceed={() => setCapped((c) => ({ ...c, cpu: true }))}
/>
<ResourceField
+ fractional
+ onValidityChange={setMemoryValid}
label="Memory"
+ estimate={memoryValid ? resourceEstimate('mem') : '—'}
unit="GiB"
value={memory}
onChange={changeResource('memory', setMemory)}
@@ -992,6 +1101,7 @@ export const CreateBoxDialog = ({
/>
<ResourceField
label="Disk"
+ estimate={resourceEstimate('disk')}
unit="GiB"
value={disk}
onChange={changeResource('disk', setDisk)}
@@ -1002,29 +1112,7 @@ export const CreateBoxDialog = ({
)}
</fieldset>
- {/* Volumes and lifecycle are real controls, but they are the third
- and fourth decision on a screen whose promise is "a box for your
- agent" — most boxes take the defaults, and the agent that made the
- box already chose. One disclosure, both sections, collapsed. */}
- <div className="border-t border-border pt-4">
- <button
- type="button"
- onClick={() => setShowAdvanced((v) => !v)}
- aria-expanded={showAdvanced}
- className="flex min-h-6 w-full items-center justify-between font-sans text-meta font-medium text-foreground transition-colors hover:text-brand"
- >
- <span>
- <span style={{ color: BRAND }}>{showAdvanced ? '▾' : '▸'}</span> Advanced
- <span className="ml-2 font-normal text-muted-foreground">
- volumes · lifecycle
- {mounts.length > 0 ? ` · ${mounts.length} mount${mounts.length > 1 ? 's' : ''}` : ''}
- </span>
- </span>
- </button>
- </div>
- {showAdvanced && (
- <>
- {/* volumes — the only moment a box and a volume can be connected:
+ {/* volumes — the only moment a box and a volume can be connected:
there is no attach/detach endpoint, so a running box can never
gain or lose one. That fact used to be spelled out in a note
below the list, but Size is equally locked at create time (no
@@ -1032,113 +1120,115 @@ export const CreateBoxDialog = ({
Volumes out implied a false asymmetry. Dropped; "+ Mount a
volume" moved into the header row instead, saving the row it
cost. */}
- <div className="flex flex-col gap-[11px] border-t border-border pt-5">
- <div className="flex items-center justify-between gap-3">
- <div className="form-field-label">
- <span style={{ color: BRAND }}>▸</span> Volumes
- </div>
- <button
- type="button"
- onClick={() => setMounts((prev) => [...prev, { volumeId: '', mountPath: '/data' }])}
- className="inline-flex h-7 items-center border border-border px-[10px] font-sans text-meta transition-colors hover:border-brand"
- >
- + Mount a volume
- </button>
- </div>
+ <div className="flex flex-col gap-[11px] border-t border-border pt-5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="form-field-label">
+ <span style={{ color: BRAND }}>▸</span> Volumes
+ </div>
+ <button
+ type="button"
+ onClick={() => setMounts((prev) => [...prev, { volumeId: '', mountPath: '/data' }])}
+ className="inline-flex h-7 items-center border border-border px-[10px] font-sans text-meta transition-colors hover:border-brand"
+ >
+ + Mount a volume
+ </button>
+ </div>
- {/* Disk above is scratch space that dies with the box; a volume is
+ {/* Disk above is scratch space that dies with the box; a volume is
the opposite of that, which is the one fact worth stating here. */}
- <PanelNote>
- A volume persists independently of this box and can be mounted into another box later.
- </PanelNote>
-
- {mounts.length > 0 && (
- <div className="flex flex-col gap-[9px]">
- {mounts.map((mount, index) => (
- <MountRow
- key={index}
- mount={mount}
- volumes={availableVolumes}
- onChange={(next) => setMounts((prev) => prev.map((m, i) => (i === index ? next : m)))}
- onRemove={() => setMounts((prev) => prev.filter((_, i) => i !== index))}
- />
- ))}
- </div>
- )}
+ <PanelNote>
+ A volume persists independently of this box and can be mounted into another box later.
+ </PanelNote>
+
+ {mounts.length > 0 && (
+ <div className="flex flex-col gap-[9px]">
+ {mounts.map((mount, index) => (
+ <MountRow
+ key={index}
+ mount={mount}
+ volumes={availableVolumes}
+ onChange={(next) => setMounts((prev) => prev.map((m, i) => (i === index ? next : m)))}
+ onRemove={() => setMounts((prev) => prev.filter((_, i) => i !== index))}
+ />
+ ))}
</div>
+ )}
+ </div>
- {/* lifecycle — decides when the box disappears (and whether its disk
+ {/* lifecycle — decides when the box disappears (and whether its disk
goes with it); placed last so it sits directly above the price it
changes. Three flat rows, always visible: no presets to learn,
no "Custom" panel hiding the real controls. */}
- <div className="flex flex-col gap-[13px] border-t border-border pt-5">
- <div className="form-field-label">
- <span style={{ color: BRAND }}>▸</span> Lifecycle
- </div>
+ <div className="flex flex-col gap-[13px] border-t border-border pt-5">
+ <div className="form-field-label">
+ <span style={{ color: BRAND }}>▸</span> Lifecycle
+ </div>
- <div className="flex flex-col gap-[9px]">
- <SelectField
- label="Stop when idle"
- ariaLabel="Stop when idle"
- value={stopSeconds}
- options={STOP_OPTIONS}
- onChange={setStopSeconds}
- />
- {/* The single most surprising part of the feature: only the
+ <div className="flex flex-col gap-[9px]">
+ <SelectField
+ label="Stop when idle"
+ ariaLabel="Stop when idle"
+ value={stopSeconds}
+ options={STOP_OPTIONS}
+ onChange={setStopSeconds}
+ />
+ {/* The single most surprising part of the feature: only the
three request paths that refresh `lastActivityAt` count as
activity (the REST proxy, the WS attach and the preview
proxy's last-activity ping). Nothing running *inside* the box
touches it, so a long job is not self-protecting. */}
- {stopSeconds > 0 && (
- <PanelNote>
- Idle means no SDK, terminal or preview traffic. Work running inside the box does not count — a
- long job can be stopped mid-run.
- </PanelNote>
- )}
+ {stopSeconds > 0 && (
+ <PanelNote>
+ Idle means no SDK, terminal or preview traffic. Work running inside the box does not count — a long
+ job can be stopped mid-run.
+ </PanelNote>
+ )}
- {/* Not indented under Stop: a manually-stopped box still needs
+ {/* Not indented under Stop: a manually-stopped box still needs
waking even with auto-stop off, so this is its own row, not a
modifier of one. */}
- <div className="flex items-center justify-between gap-3">
- <span className="font-sans text-meta font-medium">Wake on access</span>
- <Switch aria-label="Wake on access" checked={autoResume} onCheckedChange={setAutoResumeEnabled} />
- </div>
- {/* Wake is served by the API's own REST/WS proxy
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-sans text-meta font-medium">Wake on access</span>
+ <Switch aria-label="Wake on access" checked={autoResume} onCheckedChange={setAutoResumeEnabled} />
+ </div>
+ {/* Wake is served by the API's own REST/WS proxy
(box-auto-resume.service). The preview proxy only pings
last-activity, so preview traffic keeps a *running* box alive
but cannot bring a stopped one back. */}
- <PanelNote>
- SDK exec, file operations and terminal attach wake a stopped box. Preview URL traffic keeps a
- running box alive but cannot wake a stopped one.
- </PanelNote>
+ <PanelNote>
+ SDK exec, file operations and terminal attach wake a stopped box. Preview URL traffic keeps a running
+ box alive but cannot wake a stopped one.
+ </PanelNote>
- {/* Expressed relative to the stop it follows, not as its own
+ {/* Expressed relative to the stop it follows, not as its own
absolute threshold — see the `autoDelete` derivation above. */}
- <SelectField
- label={stopSeconds > 0 ? 'Delete after stopping' : 'Delete when idle'}
- ariaLabel="Delete after stopping"
- value={deleteDelaySeconds}
- options={DELETE_DELAY_OPTIONS}
- onChange={setDeleteDelaySeconds}
- />
- {/* Same shape as CappedResourcesNote above — left rule, tinted
+ <SelectField
+ label={stopSeconds > 0 ? 'Delete after stopping' : 'Delete when idle'}
+ ariaLabel="Delete after stopping"
+ value={deleteDelaySeconds}
+ options={DELETE_DELAY_OPTIONS}
+ onChange={setDeleteDelaySeconds}
+ />
+ {/* Same shape as CappedResourcesNote above — left rule, tinted
ground, mono 11px — in the destructive tone. */}
- {deleteDelaySeconds > 0 && (
- <p className="border-l-2 border-destructive/60 bg-destructive/5 px-3 py-2 font-sans text-meta leading-relaxed text-destructive">
- Permanent. The box and everything on its disk are gone — this cannot be undone.
- </p>
- )}
- </div>
- </div>
- </>
- )}
+ {deleteDelaySeconds > 0 && (
+ <p className="border-l-2 border-destructive/60 bg-destructive/5 px-3 py-2 font-sans text-meta leading-relaxed text-destructive">
+ Permanent. The box and everything on its disk are gone — this cannot be undone.
+ </p>
+ )}
+ </div>
+ </div>
<div className="-mx-6">
+ {!memoryValid && (
+ <p role="alert" className="text-destructive">
+ Enter memory in whole MiB increments, at least 0.125 GiB.
+ </p>
+ )}
{!cpuValid && (
<p role="alert" className="text-destructive">
Enter at least 0.125 CPU with up to three decimal places.
</p>
)}
- <BoxPriceRow cpu={cpu} memory={memory} disk={disk} />
{/* Keep blocking reasons outside collapsible options, within the scrollable body. */}
{(lifecycleError || mountError) && (
<p className="border-t border-border px-6 pt-3 font-sans text-meta text-destructive">
@@ -1147,7 +1237,35 @@ export const CreateBoxDialog = ({
)}
</div>
</FormDialogBody>
- <DialogFooter>
+ <DialogFooter className="flex-wrap items-center">
+ <div className="mr-auto flex basis-full flex-wrap items-center gap-x-4 gap-y-2 text-left sm:basis-auto">
+ <div>
+ <div className="text-meta text-muted-foreground">Estimated total</div>
+ <div className="font-mono text-em">
+ {!cpuValid || !memoryValid
+ ? '—'
+ : !config.billingApiUrl
+ ? '$0.00'
+ : selectedQuote
+ ? formatPriceCents(selectedQuote.totalCents)
+ : pricesQuery.isLoading
+ ? '—'
+ : 'Unavailable'}{' '}
+ <span className="font-sans text-meta text-muted-foreground">/ hr</span>
+ </div>
+ </div>
+ {cpuValid && memoryValid && config.billingApiUrl && selectedQuote && (
+ <BoxPriceBreakdown quote={selectedQuote} />
+ )}
+ {!config.billingApiUrl && <span className="text-meta text-muted-foreground">No usage charges</span>}
+ {config.billingApiUrl && !selectedQuote && (
+ <p role="status" className="basis-full text-meta text-muted-foreground">
+ {pricesQuery.isLoading
+ ? 'Fetching current rates.'
+ : 'Current rates could not be loaded. Usage is still metered — this box is not free.'}
+ </p>
+ )}
+ </div>
<AsciiButton className="h-11 sm:h-9" type="button" onClick={() => setOpen(false)}>
Cancel
</AsciiButton>
@@ -1159,6 +1277,7 @@ export const CreateBoxDialog = ({
disabled={
submitting ||
!cpuValid ||
+ !memoryValid ||
!selectedOrganization?.id ||
!nameValid ||
Boolean(lifecycleError) ||