The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(dashboard): show subscription savings in Create Box (BUI-2034) (#3031)
Manda1773e1eb9f62
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.mdindex ab0ce548c..87a407a89 100644--- a/apps/dashboard/README.md+++ b/apps/dashboard/README.md@@ -32,6 +32,31 @@ 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.+## Subscription value when creating a Box++The price footer compares the selected CPU, memory and disk configuration with+subscription included usage. The published **PAYG estimate** stays primary for all+users, including subscribers. A muted supplementary line expresses the percentage+lower effective hourly cost within included usage (75% for a fourfold quota ratio).+The summary says "with a subscription", without implying the benefit is exclusive+to Starter. Price breakdown keeps a concise allowance assumption and PAYG overage explanation,+without repeating plan-specific monthly pricing or an effective dollar estimate.+The ratio is the catalog monthly price divided by included usage value, shared with+Billing Plans; it never uses the wallet purchase multiplier.++The price breakdown retains published per-resource consumption and explains that+the estimate assumes the full monthly allowance is used. It is not an invoice or+historical paid-price calculation. Remaining quota is consumed at published rates;+ordinary wallet funding uses those same rates after quota is exhausted.+Trials, expired cycles, unmatched/custom plans, quota mismatches and read errors do+not produce a paid-benefit claim. Converted trials and scheduled cancellations+retain paid benefits while otherwise eligible. Organization placeholder data is ignored.++PAYG recommendations use the same documented numeric Box limits as the Billing+benefits table. Unknown tiers or configurations beyond those limits do not get a+plan-specific quote. View plans opens a separate tab, preserving the mounted create+draft without storing environment variables or triggering payment or creation.+## New-account email policyFirst-account verification is enabled by the API's `TURNSTILE_SITEKEY`. Withoutdiff --git a/apps/dashboard/src/components/Box/BoxPriceSummary.test.tsx b/apps/dashboard/src/components/Box/BoxPriceSummary.test.tsxnew file mode 100644index 000000000..798eadd3e--- /dev/null+++ b/apps/dashboard/src/components/Box/BoxPriceSummary.test.tsx@@ -0,0 +1,89 @@+// @vitest-environment jsdom+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BoxPriceSummary } from './BoxPriceSummary'+import type { OrganizationPlan } from '@/billing-api'+const state = vi.hoisted(() => ({+ owner: true,+ catalog: {+ isSuccess: true,+ isError: false,+ isPlaceholderData: false,+ data: [{ id: 'starter', name: 'Starter', priceMonthlyCents: 500, includedQuotaCents: 2000, selfServe: true }],+ },+ subscription: { isSuccess: true, isError: false, isPlaceholderData: false, data: null as OrganizationPlan | null },+}))+vi.mock('@/hooks/queries/usePlansQuery', () => ({ usePlansQuery: () => state.catalog }))+vi.mock('@/hooks/queries/billingQueries', () => ({ useOwnerPlanQuery: () => state.subscription }))+vi.mock('@/hooks/useSelectedOrganization', () => ({+ useSelectedOrganization: () => ({+ authenticatedUserOrganizationMember: { role: state.owner ? 'owner' : 'member' },+ }),+}))+let root: Root+let host: HTMLDivElement+function render(currency = 'USD') {+ act(() =>+ root.render(+ <BoxPriceSummary+ quote={{ totalCents: 6.66, lines: [] }}+ spec={{ cpu: 1, memory: 1, disk: 10 }}+ currency={currency}+ />,+ ),+ )+ return host.textContent!+}+beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ state.owner = true+ state.subscription = { isSuccess: true, isError: false, isPlaceholderData: false, data: null }+ state.catalog.isSuccess = true+ state.catalog.isError = false+ host = document.createElement('div')+ document.body.append(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ document.body.innerHTML = ''+})+describe('Box subscription summary', () => {+ it('keeps PAYG primary and links plans in another tab without initiating checkout', () => {+ expect(render()).toContain('PAYG estimate$0.0666')+ expect(host.textContent).toContain('75% lower effective hourly cost with a subscription')+ expect(host.textContent).not.toContain('4× included usage per dollar')+ expect(host.querySelector('a')?.target).toBe('_blank')+ expect(host.querySelector('a')?.getAttribute('href')).toBe('/dashboard/billing?tab=plans')+ })+ it('keeps PAYG primary for subscribed users too', () => {+ state.subscription.data = {+ planId: 'starter',+ planName: 'Starter',+ status: 'active',+ cycleFrom: new Date(Date.now() - 10000),+ cycleTo: new Date(Date.now() + 86400000),+ includedQuotaCents: 2000,+ quotaConsumedCents: 100,+ quotaRemainingCents: 1900,+ }+ expect(render()).toContain('PAYG estimate$0.0666')+ expect(host.textContent).toContain('75% lower effective hourly cost with a subscription')+ })+ it.each(['loading', 'error', 'placeholder', 'member', 'currency', 'catalog-error'])(+ 'does not infer a subscription benefit from %s',+ (scenario) => {+ if (scenario === 'loading') state.subscription.isSuccess = false+ if (scenario === 'error') state.subscription.isError = true+ if (scenario === 'placeholder') state.subscription.isPlaceholderData = true+ if (scenario === 'member') state.owner = false+ if (scenario === 'catalog-error') state.catalog.isError = true+ const text = render(scenario === 'currency' ? 'EUR' : 'USD')+ expect(text).not.toContain('effective')+ expect(text).not.toContain('4×')+ expect(text).toContain('PAYG estimate')+ },+ )+})diff --git a/apps/dashboard/src/components/Box/BoxPriceSummary.tsx b/apps/dashboard/src/components/Box/BoxPriceSummary.tsxnew file mode 100644index 000000000..0b9f1bd32--- /dev/null+++ b/apps/dashboard/src/components/Box/BoxPriceSummary.tsx@@ -0,0 +1,103 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { AsciiButton } from '@/components/ascii'+import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'+import { useOwnerPlanQuery } from '@/hooks/queries/billingQueries'+import { usePlansQuery } from '@/hooks/queries/usePlansQuery'+import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'+import { boxSubscriptionValue, subscriptionValue } from '@/lib/subscription-value'+import { formatPriceCents, type BoxHourlyPrice, type BoxSpec } from '@/lib/box-price'+import { RoutePath } from '@/enums/RoutePath'++export function BoxPriceSummary({+ quote,+ spec,+ currency,+}: {+ quote: BoxHourlyPrice+ spec: BoxSpec+ currency?: string+}) {+ const catalog = usePlansQuery()+ const subscription = useOwnerPlanQuery()+ const { authenticatedUserOrganizationMember } = useSelectedOrganization()+ const owner = authenticatedUserOrganizationMember?.role === 'owner'+ const ready =+ owner &&+ currency === 'USD' &&+ catalog.isSuccess &&+ subscription.isSuccess &&+ !catalog.isPlaceholderData &&+ !subscription.isPlaceholderData &&+ !catalog.isError &&+ !subscription.isError+ const comparison = ready ? boxSubscriptionValue(catalog.data, subscription.data, spec, quote) : undefined+ const value = subscriptionValue(comparison?.plan)+ const active = comparison?.active && value != null+ const savingsPercent = value ? Math.floor((1 - value.costRatio) * 10000) / 100 : undefined+ const price = (cents: number) => formatPriceCents(cents, 8)+ return (+ <div className="min-w-0 space-y-1">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1">+ <div>+ <div className="text-meta text-muted-foreground">PAYG estimate</div>+ <div className="font-mono text-em">+ {price(quote.totalCents)} <span className="font-sans text-meta text-muted-foreground">/ hr</span>+ </div>+ </div>+ <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 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>+ <span className="tabular-nums text-foreground">{formatPriceCents(line.subtotalCents, 6)}</span>+ </div>+ ))}+ </div>+ <div className="mt-3 flex items-baseline justify-between gap-3 border-t border-border pt-3 text-body">+ <span>PAYG / quota consumption</span>+ <span className="font-mono">{price(quote.totalCents)} / hr</span>+ </div>+ {value && (+ <p className="mt-3 text-meta text-muted-foreground">+ Savings assume full use of the monthly included allowance. Additional usage is charged at PAYG rates.+ </p>+ )}+ </PopoverContent>+ </Popover>+ </div>+ {value && (+ <p className="flex flex-wrap items-baseline gap-x-2 gap-y-1 text-meta text-muted-foreground">+ <span>{savingsPercent}% lower effective hourly cost with a subscription</span>+ {!active && (+ <a+ className="resource-guide-link inline-flex min-h-6 items-center"+ href={`${RoutePath.BILLING}?tab=plans`}+ target="_blank"+ rel="noopener noreferrer"+ aria-label="View plans (opens in a new tab)"+ >+ View plans ↗+ </a>+ )}+ </p>+ )}+ {comparison?.note && <p className="text-meta text-muted-foreground">{comparison.note}</p>}+ </div>+ )+}diff --git a/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx b/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsxindex 8e7edb356..3826926a6 100644--- a/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx+++ b/apps/dashboard/src/components/Box/CreateBoxDialog.test.tsx@@ -63,6 +63,8 @@ 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,}))diff --git a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx b/apps/dashboard/src/components/Box/CreateBoxDialog.tsxindex 443c20cd3..c4d0c3288 100644--- a/apps/dashboard/src/components/Box/CreateBoxDialog.tsx+++ b/apps/dashboard/src/components/Box/CreateBoxDialog.tsx@@ -14,7 +14,7 @@ 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 { BoxPriceSummary } from './BoxPriceSummary'import { RoutePath } from '@/enums/RoutePath'import { useCreateBoxMutation } from '@/hooks/mutations/useCreateBoxMutation'import { useConfig } from '@/hooks/useConfig'@@ -267,43 +267,6 @@ function CappedResourcesNote({ items }: { items: { label: string; unit: string;)}-// ── Price ───────────────────────────────────────────────────────────────────-function BoxPriceBreakdown({ quote }: { quote: NonNullable<ReturnType<typeof boxHourlyPrice>> }) {- return (- <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 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>- <span className="tabular-nums text-foreground">{formatPriceCents(line.subtotalCents, 6)}</span>- </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>- )-}-// ── Size ────────────────────────────────────────────────────────────────────// Previously buried in a collapsed "Advanced Options" section whose only// content was ever these three numbers — cost and headroom are as@@ -1239,23 +1202,26 @@ export const CreateBoxDialog = ({</FormDialogBody><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)+ {cpuValid && memoryValid && config.billingApiUrl && selectedQuote ? (+ <BoxPriceSummary+ quote={selectedQuote}+ spec={{ cpu, memory, disk }}+ currency={pricesQuery.data?.currency}+ />+ ) : (+ <div>+ <div className="text-meta text-muted-foreground">Estimated total</div>+ <div className="font-mono text-em">+ {!cpuValid || !memoryValid+ ? '—'+ : !config.billingApiUrl+ ? '$0.00': pricesQuery.isLoading? '—'- : 'Unavailable'}{' '}- <span className="font-sans text-meta text-muted-foreground">/ hr</span>+ : 'Unavailable'}+ <span className="font-sans text-meta text-muted-foreground"> / hr</span>+ </div></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 && (diff --git a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsxindex 28d9e7b98..985ec482d 100644--- a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx+++ b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx@@ -74,6 +74,19 @@ function RouteProbe() {}describe('billing surface contracts', () => {+ it('uses catalog money for the subscription value comparison', () => {+ const host = render(+ <MemoryRouter>+ <PlanComparison plans={catalog} />+ </MemoryRouter>,+ )+ expect(host.querySelector('thead')?.textContent).toContain('$149')+ const quota = [...host.querySelectorAll('tr')].find(+ (tr) => tr.querySelector('th')?.textContent === 'Included usage value',+ )+ expect(quota?.textContent).toContain('$250')+ })+it('compares documented limits, prices and bonuses without inventing billing cycles', () => {const host = render(<MemoryRouter>@@ -83,9 +96,9 @@ describe('billing surface contracts', () => {const row = (label: string) =>[...host.querySelectorAll('tr')].find((tr) => tr.querySelector('th')?.textContent === label)!expect(host.querySelector('thead')?.textContent).toContain('Starter')- expect(host.querySelector('thead')?.textContent).toContain('Starter$5')+ expect(host.querySelector('thead')?.textContent).toContain('Starter$149')expect(host.querySelector('thead')?.textContent).not.toContain('/ month')- expect(row('Bonus amount').textContent).toContain('—Not specified$20$400')+ expect(row('Included usage value').textContent).toContain('$30$250$900')expect(row('Max Box size').textContent).toContain('1C · 2G · 10G')expect([...row('Max concurrency').querySelectorAll('td')].map((td) => td.textContent)).toEqual(['2',@@ -145,7 +158,7 @@ describe('billing surface contracts', () => {</MemoryRouter>,)const headers = host.querySelectorAll('thead th')- expect(headers[1].textContent).toContain('Team$100')+ expect(headers[1].textContent).toContain('Team$499')expect(headers[2].textContent).toContain('Pay as you go')expect(headers[3].textContent).toContain('Unrecognized$12.34')const row = [...host.querySelectorAll('tr')].find((tr) => tr.querySelector('th')?.textContent === 'Hosted secrets')!@@ -182,7 +195,7 @@ describe('billing surface contracts', () => {<PlanComparison plans={catalog} /></MemoryRouter>,)- for (const label of ['Usage funding', 'Bonus amount', 'Trial eligibility', 'Volumes']) {+ for (const label of ['Usage funding', 'Trial eligibility', 'Volumes']) {const row = [...host.querySelectorAll('tr')].find((tr) => tr.querySelector('th')?.textContent === label)!expect(row.querySelector('[aria-hidden="true"]')?.textContent).toBe('—')expect(row.querySelector('.sr-only')?.textContent).toBe('Not specified')@@ -222,7 +235,7 @@ describe('billing surface contracts', () => {<RouteProbe /></MemoryRouter>,)- expect(host.querySelector('thead')?.textContent).toContain('Starter$5')+ expect(host.querySelector('thead')?.textContent).toContain('Starter$149')expect(host.querySelectorAll('thead a[href="https://boxlite.ai/contact"]')).toHaveLength(3)expect([...host.querySelectorAll('thead button')].every((button) => button.disabled)).toBe(true)expect(host.querySelector('output')?.textContent).toBe('/')@@ -235,7 +248,7 @@ describe('billing surface contracts', () => {</MemoryRouter>,)const starter = host.querySelectorAll('thead th')[1]- expect(starter.textContent).toContain('Starter$5')+ expect(starter.textContent).toContain(`Starter$${priceMonthlyCents / 100}`)if (priceMonthlyCents === 500) {expect(starter.querySelector('a')).toBeNull()const button = starter.querySelector('button')!diff --git a/apps/dashboard/src/components/billing/PlanComparison.tsx b/apps/dashboard/src/components/billing/PlanComparison.tsxindex 70ad4749c..ff901f542 100644--- a/apps/dashboard/src/components/billing/PlanComparison.tsx+++ b/apps/dashboard/src/components/billing/PlanComparison.tsx@@ -9,6 +9,7 @@ import { BOXLITE_CONTACT_URL, BOXLITE_SUBSCRIPTION_DOCS_URL } from '@/constants/import { RoutePath } from '@/enums/RoutePath'import { generatePath, useNavigate } from 'react-router-dom'import './PlanComparison.css'+import { subscriptionValue, formatUsageMultiple } from '@/lib/subscription-value'const currency = (cents: number) =>new Intl.NumberFormat('en-US', {@@ -163,11 +164,7 @@ export function PlanComparison({<span>{presentation?.name ?? plan.name}</span>{index !== 0 && (<span className="font-mono text-em font-normal text-foreground">- {presentation- ? currency(presentation.priceCents)- : plan.priceMonthlyCents == null- ? 'Custom'- : currency(plan.priceMonthlyCents)}+ {plan.priceMonthlyCents == null ? 'Custom' : currency(plan.priceMonthlyCents)}</span>)}</div>@@ -238,12 +235,29 @@ export function PlanComparison({))}{custom}</ComparisonRow>- <ComparisonRow label="Bonus amount">+ <ComparisonRow label="Included usage value">{plans.map((plan) => {- const bonusCents = PLAN_PRESENTATION[planTierIndex(plan.name)]?.bonusCents+ const includedCents = plan.includedQuotaCentsreturn (<td key={plan.id} className={CELL}>- {bonusCents != null ? currency(bonusCents) : <UnspecifiedValue />}+ {includedCents === null ? (+ 'Unlimited'+ ) : includedCents != null ? (+ currency(includedCents)+ ) : (+ <UnspecifiedValue />+ )}+ </td>+ )+ })}+ {custom}+ </ComparisonRow>+ <ComparisonRow label="Usage per dollar">+ {plans.map((plan) => {+ const value = subscriptionValue(plan)+ return (+ <td key={plan.id} className={CELL}>+ {value ? `${formatUsageMultiple(value.usageMultiple)}× PAYG` : <UnspecifiedValue />}</td>)})}@@ -282,6 +296,10 @@ export function PlanComparison({</tbody></table></div>+ <p className="mt-4 text-body text-muted-foreground">+ Monthly fees and included usage come from the current plan catalog. The effective cost assumes the full+ allowance is used; unused allowance expires. Additional usage is charged at PAYG rates.+ </p><ahref={BOXLITE_SUBSCRIPTION_DOCS_URL}target="_blank"diff --git a/apps/dashboard/src/components/billing/planBenefits.ts b/apps/dashboard/src/components/billing/planBenefits.tsindex 03be1773e..ba03dc596 100644--- a/apps/dashboard/src/components/billing/planBenefits.ts+++ b/apps/dashboard/src/components/billing/planBenefits.ts@@ -7,9 +7,9 @@ type BenefitRow = { label: string; values: readonly [string | null, string | nultype BenefitGroup = { title: string; rows: BenefitRow[] }export const PLAN_PRESENTATION = [- { name: 'Pay as you go', priceCents: 0, bonusCents: null },- { name: 'Starter', priceCents: 500, bonusCents: 2000 },- { name: 'Team', priceCents: 10000, bonusCents: 40000 },+ { name: 'Pay as you go', priceCents: 0 },+ { name: 'Starter', priceCents: 500 },+ { name: 'Team', priceCents: 10000 },] as const// Names identify the legacy and replacement tiers; API order is not an identity.@@ -30,12 +30,25 @@ export function planTierIndex(name: string): number {}}+export const PLAN_BOX_LIMITS = [+ { cpu: 1, memory: 2, disk: 10 },+ { cpu: 2, memory: 4, disk: 20 },+ { cpu: 16, memory: 32, disk: 100 },+] as const+export const PLAN_BENEFITS: BenefitGroup[] = [{title: 'Resource limits',rows: [{ label: 'Max Boxes', values: ['20', '40', '1,000'] },- { label: 'Max Box size', values: ['1C · 2G · 10G', '2C · 4G · 20G', '16C · 32G · 100G'] },+ {+ label: 'Max Box size',+ values: PLAN_BOX_LIMITS.map(({ cpu, memory, disk }) => `${cpu}C · ${memory}G · ${disk}G`) as [+ string,+ string,+ string,+ ],+ },{ label: 'Max concurrency', values: ['2', '4', '1,000'] },],},diff --git a/apps/dashboard/src/lib/subscription-value.spec.ts b/apps/dashboard/src/lib/subscription-value.spec.tsnew file mode 100644index 000000000..d2711360c--- /dev/null+++ b/apps/dashboard/src/lib/subscription-value.spec.ts@@ -0,0 +1,92 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { describe, expect, it } from 'vitest'+import type { OrganizationPlan, Plan, UsagePrices } from '@/billing-api'+import { boxHourlyPrice } from './box-price'+import { boxSubscriptionValue, subscriptionValue } from './subscription-value'+const plans: Plan[] = [+ {+ id: 'starter',+ name: 'Starter',+ priceMonthlyCents: 500,+ includedQuotaCents: 2000,+ selfServe: true,+ concurrencyLimit: 4,+ },+ {+ id: 'team',+ name: 'Team',+ priceMonthlyCents: 10000,+ includedQuotaCents: 40000,+ selfServe: true,+ concurrencyLimit: 1000,+ },+]+const prices: UsagePrices = {+ schemaVersion: 1,+ currency: 'USD',+ prices: [+ { code: 'cpu', unit: 'core_hour', unitPriceCents: 5.04 },+ { code: 'mem', unit: 'gib_hour', unitPriceCents: 1.44 },+ { code: 'disk', unit: 'gib_hour', unitPriceCents: 0.018 },+ ],+}+const spec = { cpu: 1, memory: 1, disk: 10 }+const quote = boxHourlyPrice(prices, spec)!+const now = +new Date('2026-11-23')+const subscription: OrganizationPlan = {+ planId: 'starter',+ planName: 'Starter',+ status: 'active',+ cycleFrom: new Date('2026-11-01'),+ cycleTo: new Date('2026-12-01'),+ includedQuotaCents: 2000,+ quotaConsumedCents: 500,+ quotaRemainingCents: 1500,+}+const resolve = (over: Partial<OrganizationPlan> = {}) =>+ boxSubscriptionValue(plans, { ...subscription, ...over }, spec, quote, now)+describe('subscription value', () => {+ it('derives economics from the catalog and follows each metered resource', () => {+ expect(subscriptionValue(plans[0])).toEqual({ costRatio: 0.25, usageMultiple: 4 })+ expect(subscriptionValue({ ...plans[0], priceMonthlyCents: 1000 })?.costRatio).toBe(0.5)+ expect(quote.totalCents * subscriptionValue(plans[0])!.costRatio).toBeCloseTo(1.665)+ for (const key of ['cpu', 'memory', 'disk'] as const) {+ const changed = boxHourlyPrice(prices, { ...spec, [key]: spec[key] * 2 })!+ expect(changed.totalCents * subscriptionValue(plans[0])!.costRatio).toBeGreaterThan(1.665)+ }+ })+ it.each([null, 0, -1, NaN, Infinity])('does not invent a benefit for invalid quota %s', (quota) => {+ expect(subscriptionValue({ ...plans[0], includedQuotaCents: quota })).toBeNull()+ })+ it('only offers a public plan that supports the selected size', () => {+ expect(boxSubscriptionValue(plans, null, spec, quote, now).plan?.id).toBe('starter')+ expect(boxSubscriptionValue(plans, null, { ...spec, cpu: 4 }, quote, now).plan?.id).toBe('team')+ expect(boxSubscriptionValue(plans, null, { ...spec, disk: 101 }, quote, now).plan).toBeUndefined()+ })+ it('retains current benefits for scheduled cancellation', () => {+ expect(resolve({ cancelAtPeriodEnd: true }).active).toBe(true)+ })+ it.each([0, 1])('does not discount a full hour with only %s quota cents', (remaining) => {+ expect(resolve({ quotaRemainingCents: remaining }).active).toBe(false)+ })+ it.each([+ { status: 'past_due' as const },+ { entitlements: 'suspended' as const },+ { planId: 'custom' },+ { includedQuotaCents: 2500 },+ { quotaRemainingCents: null },+ { cycleTo: new Date('2026-11-20') },+ ])('declines unsupported current-plan claims: %j', (over) => expect(resolve(over).active).toBe(false))+ it('distinguishes ongoing trials from converted paid plans', () => {+ const trial = {+ startedAt: new Date('2026-11-01'),+ endsAt: new Date('2026-11-04'),+ conversionAmountCents: 500,+ currency: 'USD' as const,+ }+ for (const conversionState of ['not_attempted', 'pending', 'failed'] as const) {+ expect(resolve({ trial: { ...trial, conversionState } }).active).toBe(false)+ }+ expect(resolve({ trial: { ...trial, conversionState: 'succeeded' } }).active).toBe(true)+ })+})diff --git a/apps/dashboard/src/lib/subscription-value.ts b/apps/dashboard/src/lib/subscription-value.tsnew file mode 100644index 000000000..dbbbdc2d6--- /dev/null+++ b/apps/dashboard/src/lib/subscription-value.ts@@ -0,0 +1,78 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import type { OrganizationPlan, Plan } from '@/billing-api'+import type { BoxHourlyPrice, BoxSpec } from './box-price'+import { PLAN_BOX_LIMITS, planTierIndex } from '@/components/billing/planBenefits'++/** Catalog economics, not the ledger debit rate or the customer's paid invoice. */+export function subscriptionValue(plan: Plan | undefined) {+ const price = plan?.priceMonthlyCents+ const quota = plan?.includedQuotaCents+ if (+ !plan?.selfServe ||+ price == null ||+ quota == null ||+ !Number.isFinite(price) ||+ !Number.isFinite(quota) ||+ price <= 0 ||+ quota <= price+ )+ return null+ return { costRatio: price / quota, usageMultiple: quota / price }+}++export function boxSubscriptionValue(+ plans: Plan[],+ subscription: OrganizationPlan | null,+ spec: BoxSpec,+ quote: BoxHourlyPrice,+ now = Date.now(),+) {+ if (subscription?.trial && subscription.trial.conversionState !== 'succeeded') {+ return { active: false, note: 'Trial usage · paid-plan estimates do not apply.' }+ }+ if (subscription === null || subscription.status === 'canceled') {+ // Public limits share their source with Billing's benefits table. Unknown tiers cannot be recommended.+ const plan = [...plans]+ .sort((a, b) => (a.priceMonthlyCents ?? Infinity) - (b.priceMonthlyCents ?? Infinity))+ .find((candidate) => {+ const limits = PLAN_BOX_LIMITS[planTierIndex(candidate.name)]+ return (+ subscriptionValue(candidate) &&+ limits &&+ spec.cpu <= limits.cpu &&+ spec.memory <= limits.memory &&+ spec.disk <= limits.disk+ )+ })+ return { plan, active: false, note: undefined }+ }+ if (subscription.status !== 'active' || subscription.entitlements === 'suspended') {+ return { active: false, note: 'Plan coverage is not confirmed.' }+ }+ if (!(+new Date(subscription.cycleFrom) <= now && now < +new Date(subscription.cycleTo))) {+ return { active: false, note: 'Plan cycle needs refreshing.' }+ }+ const remaining = subscription.quotaRemainingCents+ if (remaining != null && Number.isFinite(remaining) && remaining < quote.totalCents) {+ return {+ active: false,+ note:+ remaining <= 0+ ? 'Included usage used up · PAYG rates apply.'+ : 'Included usage covers less than one hour · the rest uses PAYG rates.',+ }+ }+ const plan = plans.find(+ (candidate) =>+ candidate.id === subscription.planId &&+ candidate.includedQuotaCents === subscription.includedQuotaCents &&+ subscriptionValue(candidate),+ )+ if (!plan || remaining == null || !Number.isFinite(remaining)) {+ return { active: false, note: 'Plan-specific effective cost is unavailable.' }+ }+ return { plan, active: true, note: undefined }+}++export const formatUsageMultiple = (multiple: number) =>+ new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(Math.floor(multiple * 100) / 100)diff --git a/docs/contributing/README.md b/docs/contributing/README.mdindex 0555ebc9b..62505f12c 100644--- a/docs/contributing/README.md+++ b/docs/contributing/README.md@@ -36,6 +36,8 @@ How to build, test, and change the code.Dated root-cause analyses and design studies, newest first.+- 2026-11-23 · [Create Box subscription value](investigations/2026-11-23-create-box-subscription-value.md): catalog-derived subscription savings beside the PAYG estimate, billing-state rules, and draft-preserving plan access.+- 2026-11-19 · [Trial discovery in Welcome](investigations/2026-11-19-trial-discovery-preview.md): frontend onboarding study, mock boundaries, direct completion and full walkthrough screenshots.- 2026-11-13 · [Runner data-disk performance scaling](investigations/2026-11-13-runner-data-disk-performance-scaling.md): expansion raises provisioned IOPS/throughput proportionally, clipped to the per-disk ceiling; capacity never waits for performance.diff --git a/docs/contributing/investigations/2026-11-23-create-box-subscription-value.md b/docs/contributing/investigations/2026-11-23-create-box-subscription-value.mdnew file mode 100644index 000000000..5a508a013--- /dev/null+++ b/docs/contributing/investigations/2026-11-23-create-box-subscription-value.md@@ -0,0 +1,86 @@+# Create Box subscription value++Create Box should compare the selected configuration with included subscription usage in its existing price footer, without an upsell modal.++## Evidence and scope++The Console's [`Plan`](../../../apps/dashboard/src/billing-api/types/Plan.ts) contract supplies monthly price and included quota.+[`OrganizationPlan`](../../../apps/dashboard/src/billing-api/types/OrganizationPlan.ts) supplies cycle, quota, trial and cancellation state, but no paid subscription amount.+[`boxHourlyPrice`](../../../apps/dashboard/src/lib/box-price.ts) calculates CPU, memory and disk consumption from published rates.++The catalog's monthly price divided by included quota is therefore a **catalog-based effective estimate**, conditional on fully using that quota.+It is not the debit rate, an invoice prediction, or a guarantee of the customer's historical acquisition cost.+The live catalog determines the ratio, not a hard-coded fourfold multiplier or presentation constants.++## Proposed behavior++Keep one primary create action and the existing price breakdown popover.+For PAYG, retain the full resource estimate and add one muted catalog comparison for configurations within verified published plan limits: `75% lower effective hourly cost with a subscription · View plans ↗` for the documented $5/$20 example and a $0.0666/h configuration.+The Plan API does not expose per-plan resource limits. Do not select the cheapest plan and imply it supports an arbitrary custom Box; omit its hourly offer when eligibility is unverified.+For every user, keep the PAYG estimate primary. A matching active paid plan with sufficient quota gets the same secondary percentage-saving explanation.+Show the percentage reduction in the muted summary line; calculate it from the catalog ratio. Keep only a concise full-allowance assumption and PAYG overage explanation in Price breakdown; omit plan-specific monthly pricing and effective dollar estimates.+State that quota is consumed at the published rate, then ordinary wallet funds pay for usage at that same rate.++Use a real link opening Billing Plans in a new tab, explicitly identified as such, so the mounted creation draft survives unchanged.+Do not auto-select a plan, initiate checkout, or alter creation requests.+Billing compares API-provided monthly price and included value using the same ratio helper.++| State | Price behavior |+| --- | --- |+| No subscription | Published PAYG estimate plus lowest-priced eligible catalog plan comparison |+| Active, matched plan | PAYG estimate remains primary; percentage advantage is secondary |+| Scheduled cancellation | Same benefit until the current cycle expires |+| Exhausted or insufficient quota | Published estimate; explain remaining coverage instead of promising a discounted full hour |+| Active/failed trial, past due, custom/unmatched, mismatched cycle quota | Published estimate with appropriate funding context; no paid-rate claim |+| Loading, error, previous-organization placeholder | Published estimate only; never infer PAYG from missing data |+| No billing configuration | Existing no-usage-charges presentation |++## Alternatives and implementation++Reuse existing React Query hooks and Radix popover; avoid new dependencies, modal nesting and per-keystroke requests.+An inline plan picker would complicate the creation transaction; navigating the same tab would require persistence of potentially sensitive form fields.+The selected new-tab link preserves draft ownership without serializing secrets.+React documents that state belongs to the mounted component tree: <https://react.dev/learn/preserving-and-resetting-state>.+Keep keyboard and focus behavior in the existing shared popover rather than introducing a custom disclosure.++Use one pure catalog-ratio helper shared by creation and Billing, with explicit finite positive USD values.+Trial metadata can remain after conversion: `trial.conversionState === 'succeeded'` is a paid subscription, not a currently free trial.+Use a small price-summary component for billing reads and state decisions; configuration quantities remain owned by CreateBoxDialog.+Small nonzero estimates retain enough decimal precision to avoid displaying free usage.++## Validation++Test the new calculation and state contract against the real price-estimation function, including changed CPU/memory/disk, malformed prices, custom catalogs, expired cycles, trial and quota exhaustion.+Verify Billing renders catalog amounts rather than presentation constants.+Verify the create draft survives opening Plans; inspect keyboard dismissal, narrow layouts and light/dark themes.+Local mock scenarios demonstrate the fourfold policy but do not assert the production catalog has those values.++No billing policy, backend mutation, deployment, payment or real Box creation is included.++## Observed validation++The Billing catalog-source regression failed against the untouched production files+(`$149` was replaced by the static `$5` presentation) and passed after implementation.+The new subscription estimator has no previous equivalent; its unit tests cover+catalog ratios, all three resource changes, plan size eligibility, trial conversion,+quota exhaustion, cycle expiry and unsupported states.++133 focused tests passed, including creation, Billing and query-state presentation.+The Dashboard build and subsequent TypeScript check passed. Browser verification+confirmed the eight local scenarios, small-spec precision, original draft retention+when Plans opens in a new tab, Escape returning focus to Price breakdown, and+390px light-theme layout without horizontal overflow. Dark theme was also inspected.+This verifies local presentation with fixtures, not live charging or deployment.+++## Screenshots++Default 1 vCPU / 1 GiB / 10 GiB configuration in a local fixture account:++| Before | After |+| --- | --- |+|  |  |++The shared price breakdown explains the catalog estimate and quota-consumption assumptions:++diff --git a/docs/contributing/investigations/assets/create-box-subscription-value/after.png b/docs/contributing/investigations/assets/create-box-subscription-value/after.pngnew file mode 100644index 000000000..c7fc01e38Binary files /dev/null and b/docs/contributing/investigations/assets/create-box-subscription-value/after.png differdiff --git a/docs/contributing/investigations/assets/create-box-subscription-value/before.png b/docs/contributing/investigations/assets/create-box-subscription-value/before.pngnew file mode 100644index 000000000..3400324dcBinary files /dev/null and b/docs/contributing/investigations/assets/create-box-subscription-value/before.png differdiff --git a/docs/contributing/investigations/assets/create-box-subscription-value/breakdown.png b/docs/contributing/investigations/assets/create-box-subscription-value/breakdown.pngnew file mode 100644index 000000000..b19f3a710Binary files /dev/null and b/docs/contributing/investigations/assets/create-box-subscription-value/breakdown.png differ