The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(dashboard): show free trials beside plan actions (#3034)
Ricky Chin3abb06a226a0
diff --git a/apps/dashboard/docs/subscription-cards/README.md b/apps/dashboard/docs/subscription-cards/README.mdindex 2b63cdf74..da0583a2c 100644--- a/apps/dashboard/docs/subscription-cards/README.md+++ b/apps/dashboard/docs/subscription-cards/README.md@@ -29,8 +29,6 @@ the user can contact support. A Go or Starter catalogue price of 500 cents matchthe existing confirmation route. Any differing price retains the contactfallback; the UI does not round or rewrite a server charge. Existing plan IDsremain unchanged.-The table does not activate trials or upcoming features. Trial eligibility is-presented as documented (3 days with card verification), not an activation CTA.Hosted secrets and key management are the same capability per product clarification,shown once as Hosted secrets. UndefinedFunder support and Region support are omitted pending product clarification.@@ -42,8 +40,8 @@ Browser back/forward and direct links restore the selected tab. Owners can useexisting current/scheduled/upgrade/downgrade actions. Other members can comparepublic plans but are directed to their organization owner to change a plan.For owners with confirmed subscription data, accounts without a live subscription show the zero-priced PAYG tier as current,-matching Overview, and cannot enter subscription checkout for that tier. Existing-APIs, charge calculations and paid-plan confirmation routes are unchanged.+matching Overview, and cannot enter subscription checkout for that tier.+The upgrade action uses the catalogue plan ID and the existing confirmation route.Loading uses a status message; unspecified values include screen-reader text.Retention is split into its reference point and maximum time after that point:@@ -51,6 +49,16 @@ PAYG uses overdue time; paid tiers use subscription end. All apply only whenpayment is overdue. These are maximum periods, not guarantees. Log retentionhas no documented duration and is kept separate.+### Free trial offers++Owners see a gold ribbon beside the action on plans with a free trial, for example **Free Trial 3 Days**.+It fits inside the existing button row and wraps in narrow columns. For this offer, the **Trial eligibility**+row reads **3 days · card verification required**. Owners can retry from Plans if offers are temporarily unavailable.++| Plan actions | With a three-day trial |+| --- | --- |+|  |  |+## ValidationCheck Overview-to-Plans navigation, direct URLs and history, catalogue loading,@@ -92,13 +100,15 @@ and [light theme: final row and Custom column](../../../../docs/contributing/invuses the existing mock catalogue matching the supplied screenshot. No realcheckout or payment is performed by this preview.+Use `/dashboard/billing?preview=trial-eligible&tab=plans` in the mock dashboard to see the Starter+and Team ribbons for an owner with a default card and no subscription.+## Source audit (2026-11-17)- Names: PAYG is the display name replacing for Notion Free; Starter andTeam use the document names. Prices are 5 and 100, with no inferred period.- Bonuses: 20 and 400, no inferred issue frequency, expiry or credit type.-- Trials: 3 days with card verification on the two paid tiers; no trial activation- behavior is added.+- Trial availability and duration are shown per plan.- Box limits: 20/40/1000 total Boxes, 1C·2G·10G / 2C·4G·20G / 16C·32G·100G,and 2/4/1000 maximum runtime concurrency. CI sharing is a table row, not a footer.- Retention: overdue-only, with the reference point and maximum offset separated.diff --git a/apps/dashboard/docs/subscription-cards/trial-header-before.png b/apps/dashboard/docs/subscription-cards/trial-header-before.pngnew file mode 100644index 000000000..70c1bce65Binary files /dev/null and b/apps/dashboard/docs/subscription-cards/trial-header-before.png differdiff --git a/apps/dashboard/docs/subscription-cards/trial-header.png b/apps/dashboard/docs/subscription-cards/trial-header.pngnew file mode 100644index 000000000..4d765f680Binary files /dev/null and b/apps/dashboard/docs/subscription-cards/trial-header.png differdiff --git a/apps/dashboard/src/api/apiClient.test.ts b/apps/dashboard/src/api/apiClient.test.tsindex 7236cb48d..8aedf2a3c 100644--- a/apps/dashboard/src/api/apiClient.test.ts+++ b/apps/dashboard/src/api/apiClient.test.ts@@ -167,13 +167,26 @@ async function makeClient(headers,config: cfg,}- if (status >= 200 && status < 300) return response+ if (!cfg.validateStatus || cfg.validateStatus(status)) return responsethrow new axios.AxiosError(`Request failed with status code ${status}`, undefined, cfg, undefined, response)}const { ApiClient } = await import('./apiClient')return new ApiClient(config, 'tok', onUnauthorized)}+it('uses the renewed token for billing requests', async () => {+ const requests: import('axios').InternalAxiosRequestConfig[] = []+ const api = await makeClient(vi.fn(), 200, [], requests)+ api.setAccessToken('renewed-token')+ await api.billingApi.listPlans()+ expect(requests[0].headers.Authorization).toBe('Bearer renewed-token')+})++it.each([204, 401, 403, 503])('preserves HTTP %i when eligibility has no decision', async (status) => {+ const api = await makeClient(vi.fn(), status)+ await expect(api.billingApi.getPlanTrialEligibility('org')).rejects.toMatchObject({ cause: { response: { status } } })+})+describe('ApiClient registration deadline', () => {let api: import('./apiClient').ApiClientlet send: ReturnType<typeof vi.fn<import('axios').AxiosAdapter>>diff --git a/apps/dashboard/src/api/apiClient.ts b/apps/dashboard/src/api/apiClient.tsindex 1c93afb3c..cb9c5e994 100644--- a/apps/dashboard/src/api/apiClient.ts+++ b/apps/dashboard/src/api/apiClient.ts@@ -680,6 +680,7 @@ export class ApiClient {public setAccessToken(accessToken: string) {this.config.accessToken = accessToken+ this._billingApi.setAccessToken(accessToken)}public get boxApi() {diff --git a/apps/dashboard/src/billing-api/billingApiClient.test.ts b/apps/dashboard/src/billing-api/billingApiClient.test.tsindex 089958a43..bf3dca7cd 100644--- a/apps/dashboard/src/billing-api/billingApiClient.test.ts+++ b/apps/dashboard/src/billing-api/billingApiClient.test.ts@@ -107,6 +107,24 @@ describe('getOrganizationPlan', () => {})})+describe('plan trial eligibility', () => {+ it.each([+ { plans: [] },+ {+ plans: [+ { name: 'Go', eligible: true, durationSeconds: 5400 },+ { name: 'Team', eligible: false, durationSeconds: 0 },+ ],+ },+ ])('reads the organization offer list in one GET', async ({ plans }) => {+ const api = serve({ plans })+ expect(await api.getPlanTrialEligibility('org-1')).toEqual(plans)+ expect(requestedUrls).toEqual(['http://billing.test/api/billing/organization/org-1/plan/trial-eligibility'])+ expect(requestedMethod).toBe('get')+ expect(requestedData).toBeUndefined()+ })+})+describe('upgradePlan', () => {it('returns the checkout URL when a first subscribe needs one', async () => {const api = serve({ url: 'https://checkout.stripe.com/pay/cs_test_123' })diff --git a/apps/dashboard/src/billing-api/billingApiClient.ts b/apps/dashboard/src/billing-api/billingApiClient.tsindex a229aa174..c0e37373d 100644--- a/apps/dashboard/src/billing-api/billingApiClient.ts+++ b/apps/dashboard/src/billing-api/billingApiClient.ts@@ -20,6 +20,7 @@ import {PaymentMethod,PaymentUrl,Plan,+ PlanTrialEligibility,SeriesGranularity,UsageFundingBucket,UsagePrices,@@ -48,12 +49,8 @@ export class BillingApiClient {private axiosInstance: AxiosInstanceconstructor(apiUrl: string, accessToken: string) {- this.axiosInstance = axios.create({- baseURL: apiUrl,- headers: {- Authorization: `Bearer ${accessToken}`,- },- })+ this.axiosInstance = axios.create({ baseURL: apiUrl })+ this.setAccessToken(accessToken)this.axiosInstance.interceptors.response.use((response) => {@@ -62,11 +59,15 @@ export class BillingApiClient {(error) => {const errorMessage = error.response?.data?.message || error.response?.data || error.message || String(error)- throw BoxliteError.fromString(String(errorMessage))+ throw BoxliteError.fromString(String(errorMessage), { cause: error })},)}+ public setAccessToken(accessToken: string) {+ this.axiosInstance.defaults.headers.common.Authorization = `Bearer ${accessToken}`+ }+public async getOrganizationWallet(organizationId: string): Promise<OrganizationWallet> {const response = await this.axiosInstance.get(`/organization/${organizationId}/wallet`)return response.data@@ -178,6 +179,14 @@ export class BillingApiClient {return response.data}+ public async getPlanTrialEligibility(organizationId: string): Promise<PlanTrialEligibility[]> {+ const { data } = await this.axiosInstance.get<{ plans: PlanTrialEligibility[] }>(+ `/organization/${encodeURIComponent(organizationId)}/plan/trial-eligibility`,+ { validateStatus: (status) => status === 200 },+ )+ return data.plans+ }+/*** Commerce serves this one anonymously, but it is reached through this client* anyway so the dashboard keeps a single billing base URL. The bearer tokendiff --git a/apps/dashboard/src/billing-api/types/Plan.ts b/apps/dashboard/src/billing-api/types/Plan.tsindex d56280096..6fa150c15 100644--- a/apps/dashboard/src/billing-api/types/Plan.ts+++ b/apps/dashboard/src/billing-api/types/Plan.ts@@ -23,3 +23,9 @@ export type Plan = {concurrencyLimit: number | nullselfServe: boolean}++export type PlanTrialEligibility = {+ name: string+ eligible: boolean+ durationSeconds: number+}diff --git a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsxindex c81e1eb8f..28d9e7b98 100644--- a/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx+++ b/apps/dashboard/src/components/billing/BillingSurfaces.render.test.tsx@@ -105,6 +105,33 @@ describe('billing surface contracts', () => {expect(row('Key management')).toBeUndefined()expect(row('Enterprise SSO').textContent).toContain('Coming soon')})+ it.each([+ [1, '1 Second'],+ [3600, '1 Hour'],+ [5400, '1h 30m'],+ [86401, '1d 1s'],+ ])('shows the exact %i-second offer alongside the regular price', (durationSeconds, label) => {+ const host = render(+ <MemoryRouter>+ <PlanComparison+ plans={[+ { ...catalog[1], name: 'Starter', priceMonthlyCents: 500 },+ { ...catalog[2], name: 'Team', priceMonthlyCents: 10000 },+ ]}+ trialOffers={[+ { name: 'Team', eligible: true, durationSeconds },+ { name: 'Starter', eligible: true, durationSeconds: 259200 },+ ]}+ />+ </MemoryRouter>,+ )+ const [, starter, team] = host.querySelectorAll('thead th')+ expect(starter.textContent).toContain('Free Trial 3 Days')+ expect(team.textContent).toContain('Team$100')+ expect(team.textContent).toContain(`Free Trial ${label}`)+ const row = [...host.querySelectorAll('tr')].find((tr) => tr.cells[0].textContent === 'Trial eligibility')!+ expect(row.cells[2].textContent).toBe(`${String(label).toLowerCase()} · card verification required`)+ })it('keeps documented benefits attached to named tiers when the catalogue is reordered or incomplete', () => {const host = render(<MemoryRouter>diff --git a/apps/dashboard/src/components/billing/PlanComparison.css b/apps/dashboard/src/components/billing/PlanComparison.cssindex ffc255592..e1a7edcc9 100644--- a/apps/dashboard/src/components/billing/PlanComparison.css+++ b/apps/dashboard/src/components/billing/PlanComparison.css@@ -14,6 +14,64 @@min-width: var(--plan-table-width);}+/* The ribbon sits inside the action's existing 32px row. Its available width+ follows the button, including when a catalogue price requires Contact us. */+.plan-trial-space {+ position: relative;+ flex: 1 1 0;+ min-width: 0;+ container: plan-trial / inline-size;+}++.plan-trial-ribbon {+ position: absolute;+ inset: 0 auto auto 0;+ transform: translateY(-50%);+ width: max-content;+ max-width: 100%;+ color: #3d2a0f;+ font-size: 11.5px;+ font-weight: 600;+ line-height: 13px;+ text-align: center;+ white-space: nowrap;+}++.plan-trial-ribbon::before {+ content: '';+ position: absolute;+ right: 100%;+ top: 2px;+ border: solid transparent;+ border-width: 0 0 4px 3px;+ border-bottom-color: #906221;+}++.plan-trial-face {+ display: block;+ overflow: hidden;+ padding: 2px 7px 2px 4px;+ background: linear-gradient(109deg, #d4a75b, #f9e5b6 32%, #edca87 80%, #f9e5b6);+ clip-path: polygon(0 0, 100% 0, calc(100% - 5px) 50%, 100% 100%, 0 100%);+}++.plan-trial-face > span {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ font-weight: 500;+}++@container plan-trial (min-width: 108px) {+ .plan-trial-face {+ padding-block: 5px;+ text-overflow: ellipsis;+ }+ .plan-trial-face > span {+ display: inline;+ }+}+/* Use the page's vertical scroll when the comparison fits the available contentwidth. Narrow layouts retain local scrolling and a pinned feature column. */@container (min-width: 1000px) {diff --git a/apps/dashboard/src/components/billing/PlanComparison.tsx b/apps/dashboard/src/components/billing/PlanComparison.tsxindex 88a75ab5b..70ad4749c 100644--- a/apps/dashboard/src/components/billing/PlanComparison.tsx+++ b/apps/dashboard/src/components/billing/PlanComparison.tsx@@ -1,7 +1,7 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */import { Fragment, type CSSProperties, type ReactNode } from 'react'-import { OrganizationPlan, Plan } from '@/billing-api'+import type { OrganizationPlan, Plan, PlanTrialEligibility } from '@/billing-api'import { AsciiButton } from '@/components/ascii'import { planCardCta } from '@/components/billing/planChange'import { PLAN_BENEFITS, PLAN_PRESENTATION, planTierIndex } from '@/components/billing/planBenefits'@@ -20,6 +20,25 @@ const currency = (cents: number) =>const CELL = 'border-b border-border px-4 py-2.5 text-left align-top font-normal'const LABEL = `${CELL} sticky left-0 z-10 bg-background text-muted-foreground`+function formatTrialDuration(seconds: number) {+ const units = [+ [86400, 'Day', 'd'],+ [3600, 'Hour', 'h'],+ [60, 'Minute', 'm'],+ [1, 'Second', 's'],+ ] as const+ const parts: string[] = []+ let remaining = seconds+ for (const [size, name, suffix] of units) {+ const count = Math.floor(remaining / size)+ if (!count) continue+ if (count * size === seconds) return `${count} ${name}${count === 1 ? '' : 's'}`+ parts.push(`${count}${suffix}`)+ remaining %= size+ }+ return parts.join(' ')+}+function UnspecifiedValue() {return (<>@@ -47,10 +66,14 @@ export function PlanComparison({plans,organizationPlan,canManage = true,+ trialOffers,+ checkingTrials = false,}: {plans: Plan[]organizationPlan?: OrganizationPlan | nullcanManage?: boolean+ trialOffers?: PlanTrialEligibility[]+ checkingTrials?: boolean}) {const navigate = useNavigate()// No live subscription is wallet-funded PAYG, as in the account Overview.@@ -63,6 +86,21 @@ export function PlanComparison({const currentPriceCents = plans.find((plan) => plan.id === currentId)?.priceMonthlyCents ?? nullconst columnCount = plans.length + 2const custom = <td className={`${CELL} text-muted-foreground`}>By agreement</td>+ const durations = new Map<string, string | null>()+ for (const offer of trialOffers ?? []) {+ if (offer.eligible === false) durations.set(offer.name, null)+ else if (offer.eligible === true && Number.isSafeInteger(offer.durationSeconds) && offer.durationSeconds > 0) {+ durations.set(offer.name, formatTrialDuration(offer.durationSeconds))+ }+ }++ function trialDetails(name: string) {+ if (checkingTrials) return 'Checking eligibility…'+ const duration = durations.get(name)+ if (duration === null) return 'Not eligible'+ if (!duration) return <UnspecifiedValue />+ return <>{duration.toLowerCase()} · card verification required</>+ }if (!plans.length) {return (@@ -108,6 +146,7 @@ export function PlanComparison({{plans.map((plan) => {const index = planTierIndex(plan.name)const presentation = PLAN_PRESENTATION[index]+ const trialDuration = durations.get(plan.name)const priceMatches = !presentation || plan.priceMonthlyCents === presentation.priceCentsconst cta =plan.id === currentId@@ -132,25 +171,36 @@ export function PlanComparison({</span>)}</div>- {!priceMatches && canManage && !cta.disabled ? (- <a- href={BOXLITE_CONTACT_URL}- target="_blank"- rel="noopener noreferrer"- className="inline-flex h-8 items-center justify-center border border-border px-3 text-meta hover:border-border-selected focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- Contact us ↗- </a>- ) : (- <AsciiButton- className="h-8 w-auto px-3"- variant={cta.disabled ? 'quiet' : 'secondary'}- disabled={!canManage || cta.disabled}- onClick={() => navigate(generatePath(RoutePath.BILLING_PLAN_CHANGE, { planId: plan.id }))}- >- {canManage ? cta.label : 'Owner managed'}- </AsciiButton>- )}+ <div className="flex w-full items-center gap-1.5">+ {!priceMatches && canManage && !cta.disabled ? (+ <a+ href={BOXLITE_CONTACT_URL}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex h-8 shrink-0 items-center justify-center whitespace-nowrap border border-border px-3 text-meta hover:border-border-selected focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ Contact us ↗+ </a>+ ) : (+ <AsciiButton+ className="h-8 w-auto px-3"+ variant={cta.disabled ? 'quiet' : 'secondary'}+ disabled={!canManage || cta.disabled}+ onClick={() => navigate(generatePath(RoutePath.BILLING_PLAN_CHANGE, { planId: plan.id }))}+ >+ {canManage ? cta.label : 'Owner managed'}+ </AsciiButton>+ )}+ {trialDuration && (+ <span className="plan-trial-space">+ <span className="plan-trial-ribbon" title={`Free Trial ${trialDuration}`}>+ <span className="plan-trial-face">+ Free Trial <span>{trialDuration}</span>+ </span>+ </span>+ </span>+ )}+ </div></div></th>)@@ -202,14 +252,10 @@ export function PlanComparison({<ComparisonRow label="Trial eligibility">{plans.map((plan) => (<td key={plan.id} className={CELL}>- {planTierIndex(plan.name) === 1 || planTierIndex(plan.name) === 2 ? (- '3-day free trial · card verification required'- ) : (- <UnspecifiedValue />- )}+ {trialDetails(plan.name)}</td>))}- {custom}+ <td className={`${CELL} text-muted-foreground`}>{trialDetails('Enterprise')}</td></ComparisonRow>{PLAN_BENEFITS.map((group) => (<Fragment key={group.title}>diff --git a/apps/dashboard/src/components/billing/PlansSection.test.tsx b/apps/dashboard/src/components/billing/PlansSection.test.tsxindex 7aeb04b16..1cfa579ba 100644--- a/apps/dashboard/src/components/billing/PlansSection.test.tsx+++ b/apps/dashboard/src/components/billing/PlansSection.test.tsx@@ -3,6 +3,7 @@import { act } from 'react'import { createRoot, type Root } from 'react-dom/client'import { MemoryRouter } from 'react-router-dom'+import { AxiosError } from 'axios'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { PlansSection } from './PlansSection'@@ -12,10 +13,28 @@ const state = vi.hoisted(() => ({isLoading: false,isError: false,refetch: vi.fn(),- data: [{ id: 'payg', name: 'NoSubscription', priceMonthlyCents: 0, selfServe: true }],+ data: [+ { id: 'payg', name: 'NoSubscription', priceMonthlyCents: 0, selfServe: true },+ { id: 'team', name: 'Team', priceMonthlyCents: 10000, selfServe: true },+ { id: 'starter', name: 'Go', priceMonthlyCents: 500, selfServe: true },+ ],},subscription: { isLoading: false, isError: false, refetch: vi.fn(), data: null },+ eligibility: {+ isSuccess: true,+ isFetching: false,+ isError: false,+ error: null as Error | null,+ refetch: vi.fn(),+ data: [+ { name: 'Go', eligible: true, durationSeconds: 259200 },+ { name: 'Team', eligible: false, durationSeconds: 0 },+ { name: 'Enterprise', eligible: false, durationSeconds: 0 },+ ],+ },+ signinRedirect: vi.fn(),}))+vi.mock('react-oidc-context', () => ({ useAuth: () => ({ signinRedirect: state.signinRedirect }) }))vi.mock('@/hooks/useSelectedOrganization', () => ({useSelectedOrganization: () => ({selectedOrganization: { id: 'org' },@@ -23,7 +42,10 @@ vi.mock('@/hooks/useSelectedOrganization', () => ({}),}))vi.mock('@/hooks/queries/usePlansQuery', () => ({ usePlansQuery: () => state.catalog }))-vi.mock('@/hooks/queries/billingQueries', () => ({ useOwnerPlanQuery: () => state.subscription }))+vi.mock('@/hooks/queries/billingQueries', () => ({+ useOwnerPlanQuery: () => state.subscription,+ useOwnerTrialEligibilityQuery: () => state.eligibility,+}))let root: Rootfunction render() {const host = document.createElement('div')@@ -31,7 +53,7 @@ function render() {act(() => {root = createRoot(host)root.render(- <MemoryRouter>+ <MemoryRouter initialEntries={['/dashboard/billing?tab=plans']}><PlansSection /></MemoryRouter>,)@@ -44,6 +66,10 @@ beforeEach(() => {state.catalog.isLoading = falsestate.catalog.isError = falsestate.subscription.isError = false+ state.eligibility.isSuccess = true+ state.eligibility.isFetching = false+ state.eligibility.isError = false+ state.eligibility.error = nullvi.clearAllMocks()})afterEach(() => {@@ -51,6 +77,44 @@ afterEach(() => {document.body.innerHTML = ''})describe('Plans section states', () => {+ it('matches each trial offer to its catalogue name', () => {+ const host = render()+ const row = [...host.querySelectorAll('tr')].find(+ (tr) => tr.querySelector('th')?.textContent === 'Trial eligibility',+ )!+ expect(row.cells[2].textContent).toBe('Not eligible')+ expect(row.cells[4].textContent).toBe('Not eligible')+ expect(host.querySelectorAll('thead th')[3].textContent).toContain('Free Trial 3 Days')+ expect(host.querySelectorAll('thead th')[2].textContent).not.toContain('Free Trial')+ })+ it('keeps the comparison available while fresh eligibility is pending', () => {+ state.eligibility.isFetching = true+ const host = render()+ expect(host.querySelector('thead')?.textContent).not.toContain('Free Trial')+ expect(host.textContent).toContain('Checking eligibility')+ expect(host.textContent).not.toContain('Not eligible')+ })+ it.each([401, 403, 503])('handles eligibility HTTP %i without presenting a trial decision', (status) => {+ const cause = new AxiosError('Request failed')+ Object.assign(cause, { response: { status } })+ state.eligibility.error = new Error('Request failed', { cause })+ state.eligibility.isError = true+ state.eligibility.isSuccess = false+ const host = render()+ const notice = host.querySelector('[role="alert"]')!+ expect(host.querySelector('table')).not.toBeNull()+ expect(host.textContent).not.toContain('Not eligible')+ expect(host.querySelector('thead')?.textContent).not.toContain('Free Trial')+ if (status === 403) {+ expect(notice.textContent).toContain('organization owner')+ expect(notice.querySelector('button')).toBeNull()+ } else {+ act(() => notice.querySelector('button')!.click())+ if (status === 401)+ expect(state.signinRedirect).toHaveBeenCalledWith({ state: { returnTo: '/dashboard/billing?tab=plans' } })+ else expect(state.eligibility.refetch).toHaveBeenCalledOnce()+ }+ })it('shows a loading surface instead of an empty comparison during catalogue loading', () => {state.catalog.isLoading = trueconst host = render()@@ -70,6 +134,7 @@ describe('Plans section states', () => {const host = render()expect(host.querySelector('table')).not.toBeNull()expect(host.textContent).toContain('Ask your organization owner')+ expect(host.querySelector('thead')?.textContent).not.toContain('Free Trial')expect(host.querySelector('thead button')?.disabled).toBe(true)expect(host.querySelector('a[href="https://boxlite.ai/contact"]')).not.toBeNull()})diff --git a/apps/dashboard/src/components/billing/PlansSection.tsx b/apps/dashboard/src/components/billing/PlansSection.tsxindex e966b4f34..e628aff3b 100644--- a/apps/dashboard/src/components/billing/PlansSection.tsx+++ b/apps/dashboard/src/components/billing/PlansSection.tsx@@ -2,24 +2,63 @@import { PlanComparison } from './PlanComparison'import { Button } from '@/components/ui/button'import { Skeleton } from '@/components/ui/skeleton'-import { useOwnerPlanQuery } from '@/hooks/queries/billingQueries'+import { useOwnerPlanQuery, useOwnerTrialEligibilityQuery } from '@/hooks/queries/billingQueries'import { usePlansQuery } from '@/hooks/queries/usePlansQuery'import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'+import { prepareSignIn } from '@/lib/auth-session'import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'+import { isAxiosError } from 'axios'+import { useAuth } from 'react-oidc-context'+import { useLocation } from 'react-router-dom'export function PlansSection() {const { selectedOrganization, authenticatedUserOrganizationMember } = useSelectedOrganization()const catalog = usePlansQuery()const subscription = useOwnerPlanQuery()+ const eligibility = useOwnerTrialEligibilityQuery()+ const { signinRedirect } = useAuth()+ const location = useLocation()const canManage = Boolean(selectedOrganization && authenticatedUserOrganizationMember?.role === OrganizationUserRoleEnum.OWNER,)const loading = catalog.isLoading || (canManage && subscription.isLoading)const error = catalog.isError || (canManage && subscription.isError)+ const cause = eligibility.error?.cause+ const status = isAxiosError(cause) ? cause.response?.status : undefined+ const checkingTrials = canManage && eligibility.isFetching+ const trialOffers = canManage && eligibility.isSuccess && !checkingTrials ? eligibility.data : undefined+ function signInAgain() {+ const returnTo = location.pathname + location.search + location.hash+ prepareSignIn(returnTo)+ void signinRedirect({ state: { returnTo } })+ }return (<section className="plans-section">{!canManage && (- <p className="mb-4 text-body text-muted-foreground">Ask your organization owner to change plans.</p>+ <p className="mb-4 text-body text-muted-foreground">+ Ask your organization owner to check free trials or change plans.+ </p>+ )}+ {canManage && eligibility.isError && (+ <div role="alert" className="mb-4 flex flex-wrap items-center gap-2 text-body">+ {status === 403 ? (+ 'Only an organization owner can check free trial eligibility.'+ ) : status === 401 ? (+ <>+ Sign in again to check free trial eligibility.+ <Button size="sm" variant="outline" onClick={signInAgain}>+ Sign in again+ </Button>+ </>+ ) : (+ <>+ Trial eligibility is temporarily unavailable.+ <Button size="sm" variant="outline" onClick={() => void eligibility.refetch()}>+ Retry trial eligibility+ </Button>+ </>+ )}+ </div>)}{error ? (<div role="alert" className="border border-border p-6">@@ -46,6 +85,8 @@ export function PlansSection() {plans={catalog.data?.filter((plan) => plan.selfServe) ?? []}organizationPlan={subscription.data}canManage={canManage}+ trialOffers={trialOffers}+ checkingTrials={checkingTrials}/>)}</section>diff --git a/apps/dashboard/src/components/tests/PlanTrialEligibility.integration.test.tsx b/apps/dashboard/src/components/tests/PlanTrialEligibility.integration.test.tsxnew file mode 100644index 000000000..a9b1ed00c--- /dev/null+++ b/apps/dashboard/src/components/tests/PlanTrialEligibility.integration.test.tsx@@ -0,0 +1,87 @@+// @vitest-environment jsdom+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { keepPreviousData, QueryClient, QueryClientProvider } from '@tanstack/react-query'+import axios from 'axios'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+import { expect, it, vi } from 'vitest'+import { BillingApiClient, type PlanTrialEligibility } from '@/billing-api'+import { PlansSection } from '../billing/PlansSection'++const scope = vi.hoisted(() => ({ organizationId: 'a', subject: 'first', role: 'member' }))+let billingApi: BillingApiClient+vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ billingApi }) }))+vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({ billingApiUrl: '/billing' }) }))+vi.mock('react-oidc-context', () => ({ useAuth: () => ({ user: { profile: { sub: scope.subject } } }) }))+vi.mock('@/hooks/useSelectedOrganization', () => ({+ useSelectedOrganization: () => ({+ selectedOrganization: { id: scope.organizationId },+ authenticatedUserOrganizationMember: { role: scope.role },+ }),+}))++it('isolates trial ribbons by owner and organization through delayed responses', async () => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ const offers = (durationSeconds: number) => [{ name: 'Go', eligible: true, durationSeconds }]+ const pending = Promise.withResolvers<PlanTrialEligibility[]>()+ const lookup = vi+ .fn()+ .mockResolvedValueOnce(offers(259200))+ .mockReturnValueOnce(pending.promise)+ .mockResolvedValueOnce(offers(5400))+ const originalAdapter = axios.defaults.adapter+ axios.defaults.adapter = async (config) => {+ let data: unknown = {}+ if (config.url === '/plan') data = [{ id: 'starter', name: 'Go', priceMonthlyCents: 500, selfServe: true }]+ if (config.url?.endsWith('/trial-eligibility'))+ data = { plans: await lookup(config.url, config.headers.Authorization) }+ return { status: 200, statusText: 'OK', data, headers: {}, config }+ }+ billingApi = new BillingApiClient('/billing', 'first-token')+ const client = new QueryClient({ defaultOptions: { queries: { placeholderData: keepPreviousData } } })+ const host = document.createElement('div')+ const root = createRoot(host)+ const render = () =>+ act(() =>+ root.render(+ <QueryClientProvider client={client}>+ <MemoryRouter>+ <PlansSection />+ </MemoryRouter>+ </QueryClientProvider>,+ ),+ )+ const waitForText = (expected: string) =>+ vi.waitFor(async () => {+ await act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)))+ expect(host.textContent).toContain(expected)+ })+ const ribbon = () => host.querySelector('.plan-trial-ribbon')?.textContent+ try {+ render()+ await waitForText('Owner managed')+ expect(lookup).not.toHaveBeenCalled()+ scope.role = 'owner'+ render()+ await waitForText('Free Trial 3 Days')+ scope.organizationId = 'b'+ render()+ expect(ribbon()).toBeUndefined()+ scope.subject = 'second'+ billingApi.setAccessToken('second-token')+ render()+ await waitForText('Free Trial 1h 30m')+ await act(async () => pending.resolve(offers(60)))+ expect(ribbon()).toBe('Free Trial 1h 30m')+ expect(lookup.mock.calls).toEqual([+ ['/organization/a/plan/trial-eligibility', 'Bearer first-token'],+ ['/organization/b/plan/trial-eligibility', 'Bearer first-token'],+ ['/organization/b/plan/trial-eligibility', 'Bearer second-token'],+ ])+ } finally {+ act(() => root.unmount())+ client.clear()+ axios.defaults.adapter = originalAdapter+ }+})diff --git a/apps/dashboard/src/hooks/queries/billingQueries.ts b/apps/dashboard/src/hooks/queries/billingQueries.tsindex 20d8e3659..1c0250afc 100644--- a/apps/dashboard/src/hooks/queries/billingQueries.ts+++ b/apps/dashboard/src/hooks/queries/billingQueries.ts@@ -8,7 +8,11 @@ import type { OrganizationWallet } from '@/billing-api/types/OrganizationWallet'import type { SeriesGranularity } from '@/billing-api'import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'-import { UseQueryOptions } from '@tanstack/react-query'+import { useQuery, type UseQueryOptions } from '@tanstack/react-query'+import { useAuth } from 'react-oidc-context'+import { useApi } from '../useApi'+import { useConfig } from '../useConfig'+import { queryKeys } from './queryKeys'import { useOrganizationBillingPortalUrlQuery } from './useOrganizationBillingPortalUrlQuery'import {useFetchOrganizationCheckoutUrlQuery,@@ -48,6 +52,25 @@ export function useOwnerPlanQuery() {return useOrganizationPlanQuery(scope)}+export function useOwnerTrialEligibilityQuery() {+ const { organizationId, enabled } = useSelectedOrgBillingScope()+ const { user } = useAuth()+ const { billingApi } = useApi()+ const { billingApiUrl } = useConfig()+ const subject = user?.profile.sub+ return useQuery({+ queryKey: queryKeys.organization.trialEligibility(organizationId, subject),+ queryFn: () => billingApi.getPlanTrialEligibility(organizationId),+ enabled: Boolean(enabled && subject && billingApiUrl),+ // An offer belongs to this owner and organization for this visit to Plans.+ placeholderData: undefined,+ staleTime: 0,+ gcTime: 0,+ refetchOnWindowFocus: false,+ retry: false,+ })+}+export function useOwnerBillingPortalUrlQuery() {const scope = useSelectedOrgBillingScope()return useOrganizationBillingPortalUrlQuery(scope)diff --git a/apps/dashboard/src/hooks/queries/queryKeys.ts b/apps/dashboard/src/hooks/queries/queryKeys.tsindex aaa16c434..f13d8c09f 100644--- a/apps/dashboard/src/hooks/queries/queryKeys.ts+++ b/apps/dashboard/src/hooks/queries/queryKeys.ts@@ -45,6 +45,8 @@ export const queryKeys = {},plan: (organizationId: string) => [...queryKeys.organization.all, organizationId, 'plan'] as const,+ trialEligibility: (organizationId: string, subject?: string) =>+ [...queryKeys.organization.plan(organizationId), 'trial-eligibility', subject] as const,wallet: (organizationId: string) => [...queryKeys.organization.all, organizationId, 'wallet'] as const,},user: {diff --git a/apps/dashboard/src/mocks/handlers.ts b/apps/dashboard/src/mocks/handlers.tsindex 9cf801d50..7a364560c 100644--- a/apps/dashboard/src/mocks/handlers.ts+++ b/apps/dashboard/src/mocks/handlers.ts@@ -114,6 +114,20 @@ function boxesPullingThrough(credential: { registryHost: string; repositoryPrefi})}+function planCatalogHandlers(catalog: () => Plan[]) {+ return [+ http.get(`${BILLING_API_URL}/plan`, () => HttpResponse.json(catalog())),+ http.get(`${BILLING_API_URL}/organization/:organizationId/plan/trial-eligibility`, () => {+ const hasTrial = billingPreview === 'trial-eligible' && MOCK_PAYMENT_METHODS.some((method) => method.isDefault)+ const plans = catalog().map((plan) => {+ const eligible = hasTrial && plan.selfServe && (plan.priceMonthlyCents ?? 0) > 0+ return { name: plan.name, eligible, durationSeconds: eligible ? 259200 : 0 }+ })+ return HttpResponse.json({ plans }, { headers: { 'Cache-Control': 'private, no-store' } })+ }),+ ]+}+export const handlers = [...resourceStateHandlers(API_URL),...ciHandlers(newUserPreview),@@ -548,9 +562,17 @@ export const handlers = [],})}),- http.get(`${BILLING_API_URL}/plan`, async () => {- if (billingPreview === 'subscription-cards') {- return HttpResponse.json<Plan[]>([+ ...planCatalogHandlers(() => {+ const enterprise: Plan = {+ id: 'enterprise',+ name: 'Enterprise',+ priceMonthlyCents: null,+ includedQuotaCents: null,+ concurrencyLimit: null,+ selfServe: false,+ }+ if (billingPreview === 'subscription-cards' || billingPreview === 'trial-eligible') {+ return [{id: 'starter',name: 'NoSubscription',@@ -575,12 +597,13 @@ export const handlers = [concurrencyLimit: 1000,selfServe: true,},- ])+ ...(billingPreview === 'trial-eligible' ? [enterprise] : []),+ ]}// Mirrors the billing service's own standard-plan catalog (Subscription.md// v2 §3). Enterprise carries nulls — the contact-sales card, not missing// data — and is not self-serve.- return HttpResponse.json<Plan[]>([+ return [{id: 'starter',name: 'Starter',@@ -605,15 +628,8 @@ export const handlers = [concurrencyLimit: 1_000,selfServe: true,},- {- id: 'enterprise',- name: 'Enterprise',- priceMonthlyCents: null,- includedQuotaCents: null,- concurrencyLimit: null,- selfServe: false,- },- ])+ enterprise,+ ]}),http.get(`${BILLING_API_URL}/organization/:organizationId/wallet`, async () => {const preview = billingPreview@@ -677,7 +693,7 @@ export const handlers = [}),http.get(`${BILLING_API_URL}/organization/:organizationId/plan`, async () => {const preview = billingPreview- if (newUserPreview || preview === 'balance-wallet') return HttpResponse.json({})+ if (newUserPreview || preview === 'balance-wallet' || preview === 'trial-eligible') return HttpResponse.json({})const empty = preview === 'balance-empty' || preview === 'balance-wallet-fallback'// Mirrors the billing service's own mock seed: pro, a quarter used,// pinned mid-cycle so the meter renders deterministically. The real