The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
fix(dashboard): show free trial countdown (#2930)
Lhfcws7ca6f13e91dd
diff --git a/apps/dashboard/docs/subscription-cards/README.md b/apps/dashboard/docs/subscription-cards/README.mdindex 3f543b732..0a1ed7057 100644--- a/apps/dashboard/docs/subscription-cards/README.md+++ b/apps/dashboard/docs/subscription-cards/README.md@@ -20,9 +20,10 @@ and missing tiers do not change the mapping; unknown names receive no inferred baccessible as unspecified, never unsupported. Custom terms are negotiated.Plans displays the documented names and bonuses with the approved $5 Starter-price, without adding a monthly cycle or grant cadence. Overview retains real account data. While a subscription-trial awaits conversion, its monthly price carries a `FREE TRIAL` label with the total hours derived from Commerce's-trial timestamps. A self-serve action+price, without adding a monthly cycle or grant cadence. Overview retains real account data. While conversion is+`not_attempted`, Active Plan shows the remaining trial days and This Cycle uses Commerce's trial timestamps for its+date range and countdown. A `pending` response keeps the expired trial window in `cycleFrom`/`cycleTo`; a `succeeded`+response reanchors them to the paid cycle. A self-serve actionis available only when its catalogue price matches the displayed price; otherwisethe user can contact support. A Go or Starter catalogue price of 500 cents matches the $5 display and usesthe existing confirmation route. Any differing price retains the contactdiff --git a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsxindex b81602442..c81e1eb8f 100644--- a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx+++ b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx@@ -58,6 +58,7 @@ beforeAll(() => {afterEach(() => {act(() => root?.unmount())document.body.innerHTML = ''+ vi.useRealTimers()})function render(content: ReactNode) {const host = document.createElement('div')@@ -228,7 +229,9 @@ describe('billing surface contracts', () => {expect(host.textContent).not.toContain('no subscription')expect(host.textContent).not.toContain('FREE TRIAL')})- it('labels an active subscription trial with its total duration in hours', () => {+ it('shows the remaining trial time in the active subscription summary', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-08-04T00:00:00.000Z'))const host = render(<CycleOverviewwallet={wallet}@@ -245,7 +248,9 @@ describe('billing surface contracts', () => {catalogPlan={catalog[1]}/>,)- expect(host.textContent).toContain('Pro$149/mo(FREE TRIAL for 144 hours)')+ expect(host.textContent).toContain('Pro$149/mo')+ expect(host.textContent).toContain('FREE TRIAL')+ expect(host.textContent).toMatch(/3\s*days\s*left/)})it('shows grant progress across the summary width and retains plan guidance', () => {const host = render(diff --git a/apps/dashboard/src/components/billing/CycleOverview.tsx b/apps/dashboard/src/components/billing/CycleOverview.tsxindex 491fa1230..f99587f2a 100644--- a/apps/dashboard/src/components/billing/CycleOverview.tsx+++ b/apps/dashboard/src/components/billing/CycleOverview.tsx@@ -12,6 +12,7 @@ import { useUsagePricesQuery } from '@/hooks/queries/useUsagePricesQuery'import { formatPriceCents } from '@/lib/box-price'import { handleApiError } from '@/lib/error-handling'import { formatAmount, formatWholeDollars } from '@/lib/utils'+import { differenceInCalendarDays } from 'date-fns'import { toast } from 'sonner'/**@@ -76,6 +77,9 @@ export function CycleOverview({}) {const mode = billingMode(wallet, organizationPlan)const scheduled = scheduledChange({ plan: organizationPlan, catalog })+ const activeTrial =+ mode.kind === 'plan' && mode.plan.trial?.conversionState === 'not_attempted' ? mode.plan.trial : null+ const trialDaysLeft = activeTrial ? Math.max(0, differenceInCalendarDays(activeTrial.endsAt, new Date())) : nullreturn (<section>@@ -101,11 +105,9 @@ export function CycleOverview({{formatWholeDollars(catalogPlan.priceMonthlyCents)}/mo</span>)}- {mode.kind === 'plan' && mode.plan.trial?.conversionState === 'not_attempted' && (+ {activeTrial && (<span className="font-mono text-em text-muted-foreground">- (FREE TRIAL for{' '}- {Math.round((mode.plan.trial.endsAt.getTime() - mode.plan.trial.startedAt.getTime()) / 3_600_000)}{' '}- hours)+ (FREE TRIAL · {trialDaysLeft} {trialDaysLeft === 1 ? 'day' : 'days'} left)</span>)}{mode.kind === 'plan' && mode.plan.status.toLowerCase() !== 'active' && (diff --git a/apps/dashboard/src/components/billing/ThisCycleCard.render.test.tsx b/apps/dashboard/src/components/billing/ThisCycleCard.render.test.tsxindex cfa284a0d..2627af44f 100644--- a/apps/dashboard/src/components/billing/ThisCycleCard.render.test.tsx+++ b/apps/dashboard/src/components/billing/ThisCycleCard.render.test.tsx@@ -7,9 +7,10 @@import { act } from 'react'import { createRoot, type Root } from 'react-dom/client'import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import { OrganizationPlan } from '@/billing-api'import { ThisCycleCard } from './ThisCycleCard'-const plan = {+const plan: OrganizationPlan = {planId: 'pro',planName: 'Pro',status: 'active' as const,@@ -48,6 +49,8 @@ describe('ThisCycleCard quota summary', () => {act(() => root?.unmount())root = nulldocument.body.innerHTML = ''+ delete plan.trial+ vi.useRealTimers()})it('renders quota remaining from the plan response', () => {@@ -68,4 +71,27 @@ describe('ThisCycleCard quota summary', () => {expect(label?.parentElement?.textContent).not.toContain('$62.50')expect(document.body.textContent).not.toContain('Quota consumed')})++ it('trial countdown renders the trial deadline instead of the monthly cycle', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-08-14T12:00:00.000Z'))+ plan.trial = {+ startedAt: new Date('2026-08-05T12:00:00.000Z'),+ endsAt: new Date('2026-08-17T12:00:00.000Z'),+ conversionAmountCents: 14900,+ currency: 'USD',+ conversionState: 'not_attempted',+ }+ const host = document.createElement('div')+ document.body.appendChild(host)++ act(() => {+ root = createRoot(host)+ root.render(<ThisCycleCard />)+ })++ expect(document.body.textContent).toContain('Pro · Aug 5 – Aug 17')+ expect(document.body.textContent).toMatch(/Free trial ends in\s*3\s*days/)+ expect(document.body.textContent).not.toContain('Cycle ends in')+ })})diff --git a/apps/dashboard/src/components/billing/ThisCycleCard.test.ts b/apps/dashboard/src/components/billing/ThisCycleCard.test.tsindex fff2b7155..1270649bc 100644--- a/apps/dashboard/src/components/billing/ThisCycleCard.test.ts+++ b/apps/dashboard/src/components/billing/ThisCycleCard.test.ts@@ -32,6 +32,75 @@ describe('cycleFacts', () => {expect(facts.window).toBe('Aug 5 – Sep 5')})+ it('trial countdown uses the trial window while conversion has not been attempted', () => {+ const facts = cycleFacts(+ {+ ...plan,+ trial: {+ startedAt: new Date('2026-08-05T12:00:00.000Z'),+ endsAt: new Date('2026-08-17T12:00:00.000Z'),+ conversionAmountCents: 14900,+ currency: 'USD',+ conversionState: 'not_attempted',+ },+ },+ now,+ )+ expect(facts).toMatchObject({+ daysLeft: 3,+ rollDay: 'Aug 17',+ window: 'Aug 5 – Aug 17',+ trialActive: true,+ })+ })++ it('trial countdown keeps the trial window while conversion is pending', () => {+ const facts = cycleFacts(+ {+ ...plan,+ cycleTo: new Date('2026-08-17T12:00:00.000Z'),+ trial: {+ startedAt: new Date('2026-08-05T12:00:00.000Z'),+ endsAt: new Date('2026-08-17T12:00:00.000Z'),+ conversionAmountCents: 14900,+ currency: 'USD',+ conversionState: 'pending',+ },+ },+ new Date('2026-08-17T12:00:00.000Z'),+ )+ expect(facts).toMatchObject({+ daysLeft: 0,+ rollDay: 'Aug 17',+ window: 'Aug 5 – Aug 17',+ trialActive: false,+ })+ })++ it('trial countdown uses the reanchored paid cycle after conversion succeeds', () => {+ const facts = cycleFacts(+ {+ ...plan,+ cycleFrom: new Date('2026-08-17T12:00:00.000Z'),+ cycleTo: new Date('2026-09-17T12:00:00.000Z'),+ trial: {+ startedAt: new Date('2026-08-05T12:00:00.000Z'),+ endsAt: new Date('2026-08-17T12:00:00.000Z'),+ conversionAmountCents: 14900,+ currency: 'USD',+ conversionState: 'succeeded',+ },+ },+ new Date('2026-08-20T12:00:00.000Z'),+ )+ expect(facts).toMatchObject({+ daysLeft: 28,+ rollDay: 'Sep 17',+ window: 'Aug 17 – Sep 17',+ trialActive: false,+ })+ })+it('never counts below zero after the cycle lapsed', () => {expect(cycleFacts(plan, new Date('2026-09-20T12:00:00.000Z')).daysLeft).toBe(0)})diff --git a/apps/dashboard/src/components/billing/ThisCycleCard.tsx b/apps/dashboard/src/components/billing/ThisCycleCard.tsxindex 6ce6db617..bd97b606c 100644--- a/apps/dashboard/src/components/billing/ThisCycleCard.tsx+++ b/apps/dashboard/src/components/billing/ThisCycleCard.tsx@@ -21,12 +21,15 @@ import { differenceInCalendarDays, format } from 'date-fns'* testable without a DOM.*/export function cycleFacts(plan: OrganizationPlan, now: Date, catalog: Plan[] = []) {+ const activeTrial = plan.trial?.conversionState === 'not_attempted' ? plan.trial : null+ const periodFrom = activeTrial?.startedAt ?? plan.cycleFrom+ const periodTo = activeTrial?.endsAt ?? plan.cycleTo// Clamping to 0 swallowed "already over": a cycle whose roll date has// passed rendered a large `0` beside "ends in", which reads as "today".- const rawDaysLeft = differenceInCalendarDays(plan.cycleTo, now)+ const rawDaysLeft = differenceInCalendarDays(periodTo, now)const daysLeft = Math.max(0, rawDaysLeft)const ended = rawDaysLeft < 0- const rollDay = format(plan.cycleTo, 'MMM d')+ const rollDay = format(periodTo, 'MMM d')// Shared with the Overview panel: a scheduled cancellation outranks the// downgrade queued behind it, so this tab cannot promise a roll the other// tab says will never come.@@ -37,10 +40,11 @@ export function cycleFacts(plan: OrganizationPlan, now: Date, catalog: Plan[] =queued?.kind === 'downgrade' ? (catalog.find((entry) => entry.id === queued.planId)?.name ?? queued.planId) : nullreturn {unlimited: plan.includedQuotaCents === null,+ trialActive: activeTrial !== null,daysLeft,ended,rollDay,- window: `${format(plan.cycleFrom, 'MMM d')} – ${rollDay}`,+ window: `${format(periodFrom, 'MMM d')} – ${rollDay}`,note:plan.status === 'canceled'? `Canceled — quota stays usable until ${rollDay}, then pay-as-you-go from the wallet`@@ -53,8 +57,8 @@ export function cycleFacts(plan: OrganizationPlan, now: Date, catalog: Plan[] =}/**- * The current billing cycle at a glance: quota remaining from the plan's- * grant, the wallet that funds the overage, and when the cycle rolls. Every+ * The current trial or billing cycle at a glance: quota remaining from the plan's+ * grant, the wallet that funds the overage, and when the current period ends. Every* number is the billing service's own — the plan block and the wallet — so* the meter here is the meter settlement charges by. Renders nothing when* the organization has no live plan: there is no cycle to show, and@@ -86,7 +90,7 @@ export function ThisCycleCard() {}if (!plan) return null- const { unlimited, daysLeft, ended, rollDay, window, note } = cycleFacts(plan, new Date(), plans ?? [])+ const { unlimited, trialActive, daysLeft, ended, rollDay, window, note } = cycleFacts(plan, new Date(), plans ?? [])return (<section>@@ -99,9 +103,17 @@ export function ThisCycleCard() {sub={unlimited ? 'unlimited quota' : `of ${formatAmount(plan.includedQuotaCents ?? 0)} included`}/>{ended ? (- <Metric label="Cycle" value="Ended" sub={`rolled ${rollDay}`} />+ <Metric+ label={trialActive ? 'Free trial' : 'Cycle'}+ value="Ended"+ sub={`${trialActive ? 'ended' : 'rolled'} ${rollDay}`}+ />) : (- <Metric label="Cycle ends in" value={String(daysLeft)} sub={daysLeft === 1 ? 'day' : 'days'} />+ <Metric+ label={trialActive ? 'Free trial ends in' : 'Cycle ends in'}+ value={String(daysLeft)}+ sub={daysLeft === 1 ? 'day' : 'days'}+ />)}</div>diff --git a/apps/dashboard/src/pages/Billing.trial.render.test.tsx b/apps/dashboard/src/pages/Billing.trial.render.test.tsxnew file mode 100644index 000000000..048a0ea5d--- /dev/null+++ b/apps/dashboard/src/pages/Billing.trial.render.test.tsx@@ -0,0 +1,109 @@+// @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 { MemoryRouter } from 'react-router-dom'+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'+import Billing from './Billing'++vi.mock('@/hooks/useConfig', () => ({+ useConfig: () => ({ billingApiUrl: 'https://billing.example.test' }),+}))+vi.mock('@/hooks/queries/billingQueries', () => ({+ useOwnerPlanQuery: () => ({+ data: {+ planId: 'pro',+ planName: 'Pro',+ status: 'active',+ cycleFrom: new Date('2026-08-01T00:00:00.000Z'),+ cycleTo: new Date('2026-08-07T00:00:00.000Z'),+ includedQuotaCents: 25_000,+ quotaConsumedCents: 0,+ quotaRemainingCents: 25_000,+ trial: {+ startedAt: new Date('2026-08-01T00:00:00.000Z'),+ endsAt: new Date('2026-08-07T00:00:00.000Z'),+ conversionAmountCents: 14_900,+ currency: 'USD',+ conversionState: 'not_attempted',+ },+ },+ isError: false,+ }),+ useOwnerWalletQuery: () => ({+ data: {+ name: 'Test',+ balanceCents: 2_000,+ ongoingBalanceCents: 1_000,+ creditCardConnected: true,+ },+ isError: false,+ }),+}))+vi.mock('@/hooks/queries/usePlansQuery', () => ({+ usePlansQuery: () => ({+ data: [+ {+ id: 'pro',+ name: 'Pro',+ priceMonthlyCents: 14_900,+ includedQuotaCents: 25_000,+ concurrencyLimit: 100,+ selfServe: true,+ },+ ],+ isError: false,+ }),+}))+vi.mock('@/hooks/useSelectedOrganization', () => ({+ useSelectedOrganization: () => ({+ selectedOrganization: { id: 'org-1' },+ authenticatedUserOrganizationMember: { role: OrganizationUserRoleEnum.OWNER },+ }),+}))+vi.mock('@/components/billing/BillingAlerts', () => ({ BillingAlerts: () => null }))+vi.mock('@/components/billing/BalanceLowBanner', () => ({ BalanceLowBanner: () => null }))+vi.mock('@/components/billing/PlansSection', () => ({ PlansSection: () => null }))+vi.mock('@/components/billing/UsageSection', () => ({ UsageSection: () => <div>Usage section</div> }))+vi.mock('@/components/billing/WalletSection', () => ({ WalletSection: () => null }))++describe('Billing trial overview', () => {+ let root: Root | null = null++ beforeAll(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ })++ afterEach(() => {+ act(() => root?.unmount())+ root = null+ document.body.innerHTML = ''+ vi.useRealTimers()+ })++ it('shows the trial countdown on the default Overview tab', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-08-04T00:00:00.000Z'))+ const host = document.createElement('div')+ document.body.appendChild(host)++ act(() => {+ root = createRoot(host)+ root.render(+ <MemoryRouter initialEntries={['/dashboard/billing']}>+ <Billing />+ </MemoryRouter>,+ )+ })++ expect(host.textContent).toContain('Active Plan')+ expect(host.textContent).toContain('Pro$149/mo')+ expect(host.textContent).toMatch(/FREE TRIAL\s*·\s*3\s*days\s*left/)+ expect(host.textContent).not.toContain('Usage section')+ })+})