The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(console): connect Welcome to subscription checkout (#3130)
Ricky Chinb1f541f5af74
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.mdindex cccb2c3ed..30916945a 100644--- a/apps/dashboard/README.md+++ b/apps/dashboard/README.md@@ -734,8 +734,8 @@ ID as a confirmed selection. See [Organization context](#organization-context).## New-user onboarding-The welcome flow saves organization intent, then offers card setup, promo redemption,-or direct entry to Quickstart.+The welcome flow saves organization intent, then offers live subscriptions through+Billing, card setup, promo redemption, or direct entry to Quickstart.[Onboarding](onboarding.md) describes the dedicated Quickstart page, public image templates,server-backed prompt drafts, completion state, and deployment requirements.@@ -1584,7 +1584,7 @@ three options disabled, and other existing fixtures exercise missing fields.Run the mock Dashboard and open `/dashboard/welcome?preview=trial-onboarding`. The entry starts at organization naming, continues through the existing use-case selection, then offers Starter/Team selection, simulated card verification, explicit activation confirmation and immediate navigation to the existing Quickstart. Add `&step=plans` to inspect the third step directly. Returning from plan choice preserves the use-case selection. Use `&scenario=ineligible` or `&scenario=unavailable` to review alternative fixtures; the default is eligible. Product UI contains no preview tooling or simulation labels. Refresh resets the prototype.-This entry requires development mode and `VITE_ENABLE_MOCKING=true`; the prototype module is excluded from production builds. It never invokes payment APIs or writes simulated subscription results to the Billing cache. Prices and plan concurrency reuse the current presentation source; no trial quota is inferred from bonus credits. Shipping this flow needs a server-confirmed eligibility/price quote and a mutation that rejects eligibility changes instead of silently charging. Registration/authentication and default Welcome remain unchanged.+This entry requires development mode and `VITE_ENABLE_MOCKING=true`. The prototype module is excluded from production builds. It never invokes payment APIs or writes simulated subscription results to the Billing cache. Prices and plan concurrency reuse the prototype's presentation data. The production flow uses [Billing confirmation before card setup](onboarding.md#choosing-a-subscription).The choice step also offers “Explore console — no card required”, completing Welcome without verifying a card or activating a plan. “Have a coupon? Redeem code” expands an independent form: use `ACME50` for simulated success, an empty code for required-field feedback, or another code for invalid/expired feedback. Successful trial confirmation and coupon redemption complete Welcome immediately and enter Quickstart, without a separate success screen or another click. Coupon balances are not persisted to the shared mock wallet. Both alternative paths use existing Welcome completion and lead to Quickstart.diff --git a/apps/dashboard/onboarding.md b/apps/dashboard/onboarding.mdindex 89b199487..34c1eee44 100644--- a/apps/dashboard/onboarding.md+++ b/apps/dashboard/onboarding.md@@ -1,7 +1,30 @@# New-user onboarding-Welcome collects the organization name and use case before offering card setup,-promo redemption, or direct entry to Quickstart.+Welcome collects the organization name and use case before offering subscriptions,+card setup, promo redemption, or direct entry to Quickstart.++## Choosing a subscription++Owners without a live subscription see the self-serve paid plans from Commerce.+The Console shows the trial duration when Commerce returns a current offer for+that owner and organization. **Choose** opens the shared Billing confirmation.+**Subscribe** confirms the displayed monthly fee, charged after an eligible trial+or at activation when no trial applies.++When a card is needed, Billing opens Commerce's card setup in the same tab.+On return, Billing checks ownership, the wallet, the current subscription and+the confirmed monthly price before submitting the subscription once. The same-tab+handoff is scoped to the owner and organization and expires after 30 minutes.+The wallet reports whether the organization has a card. Another owner's card+setup can satisfy that check. If the catalog price has changed or another plan+has become active, the owner returns to Welcome to choose again. The subscription+API determines the final price and eligibility when it applies the move.++A redirect from the subscription request leads to a read-only plan check on+return. Welcome completes and opens Quickstart when Commerce reports the chosen+plan active. Unconfirmed bank payments remain in Billing for the owner to check.+The standalone card, promo and exploration options below are available from+the same Welcome step.## Card setup and optional creditsdiff --git a/apps/dashboard/src/components/billing/PlanComparison.tsx b/apps/dashboard/src/components/billing/PlanComparison.tsxindex 4e2d0f68a..7569e1553 100644--- a/apps/dashboard/src/components/billing/PlanComparison.tsx+++ b/apps/dashboard/src/components/billing/PlanComparison.tsx@@ -10,6 +10,7 @@ import { RoutePath } from '@/enums/RoutePath'import { generatePath, useNavigate } from 'react-router-dom'import './PlanComparison.css'import { subscriptionValue, formatUsageMultiple } from '@/lib/subscription-value'+import { trialDuration } from '@/lib/trial-offer'const currency = (cents: number) =>new Intl.NumberFormat('en-US', {@@ -21,25 +22,6 @@ 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 (<>@@ -91,10 +73,9 @@ export function PlanComparison({const 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))- }+ const duration = trialDuration(offer)+ if (duration) durations.set(offer.name, duration)+ else if (offer.eligible === false) durations.set(offer.name, null)}function trialDetails(name: string) {diff --git a/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx b/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsxindex 75409dde4..856124376 100644--- a/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx+++ b/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx@@ -1,17 +1,21 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */import { useUpgradePlanMutation } from '@/hooks/mutations/useUpgradePlanMutation'+import { RoutePath } from '@/enums/RoutePath'import { useApi } from '@/hooks/useApi'import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'import { handleApiError } from '@/lib/error-handling'-import { clearPendingPlanUpgrade, type PendingPlanUpgrade } from '@/lib/pending-plan-upgrade'+import { isActivePlan, recordWelcomeCompletion } from '@/lib/first-run'+import { clearPendingPlanUpgrade, rememberPlanUpgrade, type PendingPlanUpgrade } from '@/lib/pending-plan-upgrade'import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'import { useEffect } from 'react'import { useAuth } from 'react-oidc-context'+import { useNavigate } from 'react-router-dom'import { toast } from 'sonner'export function PlanUpgradeReturn({ selection, onFinish }: { selection: PendingPlanUpgrade; onFinish: () => void }) {const { user } = useAuth()+ const navigate = useNavigate()const { selectedOrganization, organizationMembersStatus, authenticatedUserOrganizationMember } =useSelectedOrganization()const { billingApi } = useApi()@@ -24,6 +28,8 @@ export function PlanUpgradeReturn({ selection, onFinish }: { selection: PendingPif (!userId || !organizationId || organizationMembersStatus === 'loading') returnlet active = trueasync function resume() {+ let destination: RoutePath.WELCOME | RoutePath.QUICKSTART | undefined+ const { planId, welcome } = selectiontry {if (organizationId !== selection.organizationId ||@@ -35,28 +41,67 @@ export function PlanUpgradeReturn({ selection, onFinish }: { selection: PendingPreturn}- let wallet = await billingApi.getOrganizationWallet(organizationId)- // The browser can return before card verification reaches the wallet.- for (let attempt = 0; active && !wallet.creditCardConnected && attempt < 2; attempt++) {- await new Promise((resolve) => setTimeout(resolve, 1000))- if (!active) return- wallet = await billingApi.getOrganizationWallet(organizationId)+ if (welcome?.phase === 'setup') destination = RoutePath.WELCOME+ if (welcome?.phase !== 'payment') {+ let wallet = await billingApi.getOrganizationWallet(organizationId)+ // The browser can return before card verification reaches the wallet.+ for (let attempt = 0; active && !wallet.creditCardConnected && attempt < 2; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 1000))+ if (!active) return+ wallet = await billingApi.getOrganizationWallet(organizationId)+ }+ if (!active || !wallet.creditCardConnected) return}- if (!active || !wallet.creditCardConnected) returnconst plan = await billingApi.getOrganizationPlan(organizationId)- if (!active || (plan?.planId === selection.planId && plan.status !== 'canceled')) return+ if (!active) return+ if (plan?.planId === planId && plan.status !== 'canceled') {+ destination = welcome && isActivePlan(plan, planId) ? RoutePath.QUICKSTART : undefined+ return+ }+ if (welcome?.phase === 'payment') {+ toast.info('Check Billing for your subscription status.')+ return+ }+ if (welcome) {+ if (plan && plan.status !== 'canceled') return+ const catalog = await billingApi.listPlans()+ if (!active) return+ if (+ !catalog.some(+ (plan) => plan.id === planId && plan.selfServe && plan.priceMonthlyCents === welcome.priceMonthlyCents,+ )+ ) {+ toast.info('The plan details changed. Review the subscription again.')+ return+ }+ }if (selection.expiresAt <= Date.now() || !clearPendingPlanUpgrade(selection)) return- const url = await upgrade({ organizationId, planId: selection.planId })+ const url = await upgrade({ organizationId, planId })if (!active) return- if (url) window.location.href = url- else toast.success('Plan upgraded successfully')+ if (url) {+ if (welcome) {+ rememberPlanUpgrade({ ...selection, welcome: { ...welcome, phase: 'payment' } })+ }+ destination = undefined+ window.location.href = url+ } else if (welcome) {+ destination = undefined+ const activatedPlan = await billingApi.getOrganizationPlan(organizationId)+ if (isActivePlan(activatedPlan, planId)) destination = RoutePath.QUICKSTART+ } else {+ toast.success('Plan upgraded successfully')+ }} catch (error) {if (active) handleApiError(error, 'Could not complete the plan upgrade')} finally {if (active) {clearPendingPlanUpgrade(selection)onFinish()+ if (destination === RoutePath.QUICKSTART) {+ recordWelcomeCompletion(selection.userId, selection.organizationId)+ }+ if (destination) navigate(destination, { replace: true })}}}@@ -64,7 +109,7 @@ export function PlanUpgradeReturn({ selection, onFinish }: { selection: PendingPreturn () => {active = false}- }, [billingApi, isOwner, onFinish, organizationId, organizationMembersStatus, selection, upgrade, userId])+ }, [billingApi, isOwner, navigate, onFinish, organizationId, organizationMembersStatus, selection, upgrade, userId])return (<div className="page-container py-6" role="status">diff --git a/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx b/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsxindex ed08f5fe7..527a7b9da 100644--- a/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx+++ b/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx@@ -15,6 +15,7 @@ import { getLocalStorageItem } from '@/lib/local-storage'import FirstBoxAtmosphere from './FirstBoxAtmosphere'import WelcomeJourneyArtwork from './WelcomeJourneyArtwork'import WelcomeCreditsStep from './WelcomeCreditsStep'+import WelcomePlanOptions from './WelcomePlanOptions'const trialPreviewEnabled =import.meta.env.DEV &&@@ -337,6 +338,7 @@ function WelcomeForm({ initial }: { initial: FirstRunWelcome }) {) : (<WelcomeCreditsSteponContinue={complete}+ planOptions={<WelcomePlanOptions />}illustrationRef={setIllustrationAnchor}useCase={welcome.useCase}onBack={() => {diff --git a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsxindex 9e107b8ad..ca87c258b 100644--- a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx+++ b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx@@ -1,5 +1,5 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */-import { useCallback, useEffect, useRef, useState, type Ref } from 'react'+import { useCallback, useEffect, useRef, useState, type ReactNode, type Ref } from 'react'import { AsciiButton } from '@/components/ascii'import { ArrowRightIcon, Check, CreditCardIcon, Loader2 } from '@/components/ui/icon'import { useConnectCard } from '@/hooks/useConnectCard'@@ -53,13 +53,16 @@ export default function WelcomeCreditsStep({onContinue,useCase,illustrationRef,+ planOptions,}: {onBack: () => voidonContinue: () => voiduseCase?: FirstRunUseCase | nullillustrationRef?: Ref<HTMLDivElement>+ planOptions?: ReactNode}) {- const { selectedOrganization, authenticatedUserOrganizationMember } = useSelectedOrganization()+ const { selectedOrganization, organizationMembersStatus, authenticatedUserOrganizationMember } =+ useSelectedOrganization()const isOwner = authenticatedUserOrganizationMember?.role === OrganizationUserRoleEnum.OWNERconst { connectCard, isPending: connecting } = useConnectCard()const wallet = useOwnerWalletQuery({@@ -111,6 +114,11 @@ export default function WelcomeCreditsStep({</div><div className="border-t border-border pt-7 lg:border-l lg:border-t-0 lg:pl-14 lg:pt-1">+ {isOwner && organizationMembersStatus === 'ready' && !couponMessage && planOptions && (+ <fieldset disabled={busy} className="min-w-0">+ {planOptions}+ </fieldset>+ )}{!ready && (<><h2 className="mt-3 text-em font-medium">Connect your card</h2>diff --git a/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx b/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsxnew file mode 100644index 000000000..461c1d800--- /dev/null+++ b/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx@@ -0,0 +1,80 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import { AsciiButton } from '@/components/ascii'+import { RoutePath } from '@/enums/RoutePath'+import { useOwnerPlanQuery, useOwnerTrialEligibilityQuery } from '@/hooks/queries/billingQueries'+import { usePlansQuery } from '@/hooks/queries/usePlansQuery'+import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'+import { isPaidSelfServePlan } from '@/lib/first-run'+import { trialDuration } from '@/lib/trial-offer'+import { formatAmount } from '@/lib/utils'+import { useAuth } from 'react-oidc-context'+import { generatePath, useNavigate } from 'react-router-dom'++export default function WelcomePlanOptions() {+ const { selectedOrganization } = useSelectedOrganization()+ const { user } = useAuth()+ const navigate = useNavigate()+ const subscription = useOwnerPlanQuery()+ const catalog = usePlansQuery()+ const eligibility = useOwnerTrialEligibilityQuery()+ const plans = catalog.data?.filter(isPaidSelfServePlan) ?? []++ if (+ !selectedOrganization ||+ !user ||+ !subscription.isSuccess ||+ (subscription.data && subscription.data.status !== 'canceled') ||+ !catalog.isSuccess ||+ !plans.length+ ) {+ return null+ }++ const welcomeSubscription = { organizationId: selectedOrganization.id, userId: user.profile.sub }+ const offers = eligibility.isSuccess && !eligibility.isFetching ? eligibility.data : undefined+ return (+ <section className="mb-6 border-b border-border pb-6" aria-labelledby="welcome-plans-heading">+ <h2 id="welcome-plans-heading" className="text-em font-medium">+ Choose a plan+ </h2>+ <ul className="mt-4 space-y-2">+ {plans.map((plan) => {+ const duration = trialDuration(offers?.find((offer) => offer.name === plan.name))+ return (+ <li+ key={plan.id}+ className="flex flex-wrap items-center justify-between gap-3 border border-border px-4 py-3"+ >+ <div>+ <div className="text-body font-medium">{plan.name}</div>+ <div className="text-meta text-muted-foreground">+ {duration && `${duration.toLowerCase()} free, then `}+ {formatAmount(plan.priceMonthlyCents)} / month+ </div>+ </div>+ <AsciiButton+ size="sm"+ onClick={() =>+ navigate(generatePath(RoutePath.BILLING_PLAN_CHANGE, { planId: plan.id }), {+ state: { welcomeSubscription },+ })+ }+ >+ Choose {plan.name}+ </AsciiButton>+ </li>+ )+ })}+ </ul>+ {eligibility.isError && (+ <button+ type="button"+ onClick={() => void eligibility.refetch()}+ className="mt-3 text-meta underline underline-offset-4"+ >+ Retry trial eligibility+ </button>+ )}+ </section>+ )+}diff --git a/apps/dashboard/src/hooks/useWelcomeOnboarding.ts b/apps/dashboard/src/hooks/useWelcomeOnboarding.tsindex a9e74cd27..5b09775a5 100644--- a/apps/dashboard/src/hooks/useWelcomeOnboarding.ts+++ b/apps/dashboard/src/hooks/useWelcomeOnboarding.ts@@ -6,7 +6,7 @@ import { useApi } from './useApi'import { useOrganizations } from './useOrganizations'import { useSelectedOrganization } from './useSelectedOrganization'import { useConfig } from './useConfig'-import { type FirstRunWelcome, type FirstRunUseCase } from '@/lib/first-run'+import { recordWelcomeCompletion, type FirstRunWelcome, type FirstRunUseCase } from '@/lib/first-run'import { LocalStorageKey } from '@/enums/LocalStorageKey'import { setLocalStorageItem } from '@/lib/local-storage'@@ -23,10 +23,8 @@ export function useWelcomeOnboarding(initial: FirstRunWelcome) {useEffect(() => () => controller.current?.abort(), [organizationId])const complete = () => {if (!organizationId || !user?.profile.sub) return- const completed = { ...welcome, completedAt: Date.now() }- setLocalStorageItem(`boxlite:welcome:${user.profile.sub}:${organizationId}`, JSON.stringify(completed))- setLocalStorageItem(`${LocalStorageKey.SkipOnboardingPrefix}${user.profile.sub}`, 'true')- setWelcome(completed)+ const completedAt = recordWelcomeCompletion(user.profile.sub, organizationId, welcome)+ setWelcome({ ...welcome, completedAt })}const action = useMutation({mutationFn: async (diff --git a/apps/dashboard/src/lib/first-run.ts b/apps/dashboard/src/lib/first-run.tsindex eac6d12da..cfdfdde8c 100644--- a/apps/dashboard/src/lib/first-run.ts+++ b/apps/dashboard/src/lib/first-run.ts@@ -1,4 +1,8 @@/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import type { OrganizationPlan, Plan } from '@/billing-api'+import { LocalStorageKey } from '@/enums/LocalStorageKey'+import { getLocalStorageItem, setLocalStorageItem } from './local-storage'+const EXPLORING_USE_CASE = {id: 'exploring',label: 'Just exploring',@@ -59,3 +63,34 @@ export interface FirstRunWelcome {note: stringcompletedAt?: number | null}++export type WelcomeSubscriptionScope = { userId: string; organizationId: string }++export function isPaidSelfServePlan(plan: Plan): plan is Plan & { priceMonthlyCents: number } {+ return (+ plan.selfServe &&+ plan.priceMonthlyCents !== null &&+ Number.isSafeInteger(plan.priceMonthlyCents) &&+ plan.priceMonthlyCents > 0+ )+}++export function isActivePlan(plan: OrganizationPlan | null, planId: string) {+ return plan?.planId === planId && plan.status === 'active'+}++export function recordWelcomeCompletion(userId: string, organizationId: string, welcome?: FirstRunWelcome): number {+ const key = `boxlite:welcome:${userId}:${organizationId}`+ const completedAt = Date.now()+ let saved = welcome+ if (!saved) {+ try {+ saved = JSON.parse(getLocalStorageItem(key) ?? 'null')+ } catch {+ /* Invalid progress must not block completion after checkout. */+ }+ }+ setLocalStorageItem(key, JSON.stringify({ ...saved, completedAt }))+ setLocalStorageItem(`${LocalStorageKey.SkipOnboardingPrefix}${userId}`, 'true')+ return completedAt+}diff --git a/apps/dashboard/src/lib/pending-plan-upgrade.ts b/apps/dashboard/src/lib/pending-plan-upgrade.tsindex 6b7dd0380..02e03eb17 100644--- a/apps/dashboard/src/lib/pending-plan-upgrade.ts+++ b/apps/dashboard/src/lib/pending-plan-upgrade.ts@@ -8,6 +8,7 @@ export type PendingPlanUpgrade = {organizationId: stringplanId: stringexpiresAt: number+ welcome?: { priceMonthlyCents: number; phase: 'setup' | 'payment' }}export function rememberPlanUpgrade(selection: Omit<PendingPlanUpgrade, 'expiresAt'>) {@@ -40,7 +41,11 @@ export function readPendingPlanUpgrade(): PendingPlanUpgrade | null {typeof value.organizationId === 'string' &&typeof value.planId === 'string' &&Number.isFinite(value.expiresAt) &&- value.expiresAt > Date.now()+ value.expiresAt > Date.now() &&+ (value.welcome === undefined ||+ (Number.isSafeInteger(value.welcome?.priceMonthlyCents) &&+ value.welcome.priceMonthlyCents > 0 &&+ (value.welcome.phase === 'setup' || value.welcome.phase === 'payment')))) {return value}diff --git a/apps/dashboard/src/lib/trial-offer.ts b/apps/dashboard/src/lib/trial-offer.tsnew file mode 100644index 000000000..53fec0ba0--- /dev/null+++ b/apps/dashboard/src/lib/trial-offer.ts@@ -0,0 +1,23 @@+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */+import type { PlanTrialEligibility } from '@/billing-api'++export function trialDuration(offer: PlanTrialEligibility | undefined): string | undefined {+ if (offer?.eligible !== true || !Number.isSafeInteger(offer.durationSeconds) || offer.durationSeconds <= 0) return+ const seconds = offer.durationSeconds+ 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(' ')+}diff --git a/apps/dashboard/src/pages/BillingPlanChange.tsx b/apps/dashboard/src/pages/BillingPlanChange.tsxindex 16b82d742..367cfe6f4 100644--- a/apps/dashboard/src/pages/BillingPlanChange.tsx+++ b/apps/dashboard/src/pages/BillingPlanChange.tsx@@ -12,16 +12,25 @@ import { Spinner } from '@/components/ui/spinner'import { RoutePath } from '@/enums/RoutePath'import { useDowngradePlanMutation } from '@/hooks/mutations/useDowngradePlanMutation'import { useUpgradePlanMutation } from '@/hooks/mutations/useUpgradePlanMutation'-import { useOwnerPlanQuery, useOwnerWalletQuery } from '@/hooks/queries/billingQueries'+import { useOwnerPlanQuery, useOwnerTrialEligibilityQuery, useOwnerWalletQuery } from '@/hooks/queries/billingQueries'import { usePlansQuery } from '@/hooks/queries/usePlansQuery'+import { useApi } from '@/hooks/useApi'import { useConfig } from '@/hooks/useConfig'import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'import { handleApiError } from '@/lib/error-handling'+import {+ isActivePlan,+ isPaidSelfServePlan,+ recordWelcomeCompletion,+ type WelcomeSubscriptionScope,+} from '@/lib/first-run'import { clearPendingPlanUpgrade, rememberPlanUpgrade } from '@/lib/pending-plan-upgrade'+import { trialDuration } from '@/lib/trial-offer'+import { formatAmount } from '@/lib/utils'import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'import { format } from 'date-fns'-import { useEffect, useState } from 'react'-import { Navigate, useNavigate, useParams } from 'react-router-dom'+import { useEffect, useRef, useState } from 'react'+import { Navigate, useLocation, useNavigate, useParams } from 'react-router-dom'import { toast } from 'sonner'import { usePageTitle } from '@/hooks/usePageTitle'@@ -34,8 +43,12 @@ import { usePageTitle } from '@/hooks/usePageTitle'function BillingPlanChange() {const { planId = '' } = useParams<{ planId: string }>()const navigate = useNavigate()+ const welcomeSubscription = useLocation().state?.welcomeSubscription as WelcomeSubscriptionScope | undefined+ const backTo = welcomeSubscription ? RoutePath.WELCOME : RoutePath.BILLINGconst config = useConfig()- const { selectedOrganization, organizationMembers, authenticatedUserOrganizationMember } = useSelectedOrganization()+ const { billingApi } = useApi()+ const { selectedOrganization, organizationMembers, organizationMembersStatus, authenticatedUserOrganizationMember } =+ useSelectedOrganization()const planQuery = useOwnerPlanQuery()const walletQuery = useOwnerWalletQuery()@@ -43,6 +56,19 @@ function BillingPlanChange() {const upgradePlan = useUpgradePlanMutation()const downgradePlan = useDowngradePlanMutation()const [submission, setSubmission] = useState<'idle' | 'confirming' | 'redirecting'>('idle')+ const checkoutScope = useRef<AbortController | null>(null)+ useEffect(() => {+ const scope = new AbortController()+ checkoutScope.current = scope+ if (welcomeSubscription) setSubmission('idle')+ return () => scope.abort()+ }, [+ selectedOrganization?.id,+ authenticatedUserOrganizationMember?.userId,+ authenticatedUserOrganizationMember?.role,+ organizationMembersStatus,+ welcomeSubscription,+ ])useEffect(() => {// Back from Stripe abandons this checkout, including when the browser// restores the confirmation page from its back/forward cache.@@ -67,12 +93,20 @@ function BillingPlanChange() {if (!config.billingApiUrl) {return <Navigate to={RoutePath.BILLING} replace />}- if (!selectedOrganization || !membersResolved) {- return <PlanChangeShell>{<Skeleton className="h-[320px] w-full" />}</PlanChangeShell>+ if (!selectedOrganization || (welcomeSubscription ? organizationMembersStatus === 'loading' : !membersResolved)) {+ return <PlanChangeShell backTo={backTo}>{<Skeleton className="h-[320px] w-full" />}</PlanChangeShell>+ }+ if (+ welcomeSubscription &&+ (welcomeSubscription.organizationId !== selectedOrganization.id ||+ (organizationMembersStatus === 'ready' &&+ welcomeSubscription.userId !== authenticatedUserOrganizationMember?.userId))+ ) {+ return <Navigate to={backTo} replace />}- if (!isOwner) {+ if (!isOwner || (welcomeSubscription && organizationMembersStatus !== 'ready')) {return (- <PlanChangeShell>+ <PlanChangeShell backTo={backTo}><Notice title="Plan changes are owner-only">Ask an owner of {selectedOrganization.name} to change the subscription.</Notice>@@ -83,7 +117,7 @@ function BillingPlanChange() {const isError = planQuery.isError || plansQuery.isError || walletQuery.isErrorif (isError) {return (- <PlanChangeShell>+ <PlanChangeShell backTo={backTo}><Panel className="flex flex-col items-center gap-3 px-[22px] py-10"><span className="font-sans text-body text-foreground">Oops, something went wrong</span><span className="font-sans text-meta text-muted-foreground">There was an error loading billing data.</span>@@ -108,7 +142,7 @@ function BillingPlanChange() {// states nothing, so nothing renders until both the catalog and the live plan// have actually landed — no zero-value fallbacks.if (!plansQuery.isSuccess || !planQuery.isSuccess) {- return <PlanChangeShell>{<Skeleton className="h-[320px] w-full" />}</PlanChangeShell>+ return <PlanChangeShell backTo={backTo}>{<Skeleton className="h-[320px] w-full" />}</PlanChangeShell>}const summary = planChangeSummary({@@ -117,11 +151,22 @@ function BillingPlanChange() {plan: planQuery.data,wallet: walletQuery.data,})+ const welcomePlan =+ welcomeSubscription && summary.direction === 'subscribe' && summary.target && isPaidSelfServePlan(summary.target)+ ? summary.target+ : null// An unknown plan id, or one the viewer already has, has no confirmation to// show. `replace` keeps Back from bouncing straight back into the redirect.- if (summary.blocked?.redirect) {- return <Navigate to={RoutePath.BILLING} replace />+ if (summary.blocked?.redirect || (welcomeSubscription && !welcomePlan)) {+ if (welcomeSubscription && submission !== 'idle') {+ return (+ <PlanChangeShell backTo={backTo}>+ <p role="status">Checking your subscription…</p>+ </PlanChangeShell>+ )+ }+ return <Navigate to={backTo} replace />}const pending = submission !== 'idle' || upgradePlan.isPending || downgradePlan.isPending@@ -131,16 +176,46 @@ function BillingPlanChange() {const handleConfirm = async () => {setSubmission('confirming')+ const scope = checkoutScope.current+ const organizationId = selectedOrganization.idtry {if (summary.action === 'upgrade') {- const { data: wallet } = await walletQuery.refetch({ throwOnError: true })- const checkoutUrl = await upgradePlan.mutateAsync({ organizationId: selectedOrganization.id, planId })+ const [{ data: wallet }, current, catalog] = await Promise.all([+ walletQuery.refetch({ throwOnError: true }),+ welcomePlan ? planQuery.refetch({ throwOnError: true }) : undefined,+ welcomePlan ? plansQuery.refetch({ throwOnError: true }) : undefined,+ ])+ if (welcomePlan) {+ if (scope?.signal.aborted) return+ if (typeof wallet?.creditCardConnected !== 'boolean') throw new Error('Could not check your payment method.')+ if (+ (current?.data && current.data.status !== 'canceled') ||+ !catalog?.data?.some(+ (plan) =>+ plan.id === planId && plan.selfServe && plan.priceMonthlyCents === welcomePlan.priceMonthlyCents,+ )+ ) {+ toast.info('Your billing details changed. Review the subscription again.')+ setSubmission('idle')+ return+ }+ }+ // This endpoint proves the redirect is for card setup. An upgrade URL only+ // authorizes checking the resulting plan, even if the wallet changes meanwhile.+ const setup = Boolean(welcomePlan && wallet?.creditCardConnected === false)+ const checkoutUrl = setup+ ? await billingApi.getOrganizationCheckoutUrl(organizationId)+ : await upgradePlan.mutateAsync({ organizationId, planId })+ if (welcomePlan && scope?.signal.aborted) returnif (checkoutUrl) {- if (wallet?.creditCardConnected === false && authenticatedUserOrganizationMember?.userId) {+ if ((welcomePlan || wallet?.creditCardConnected === false) && authenticatedUserOrganizationMember?.userId) {const saved = rememberPlanUpgrade({userId: authenticatedUserOrganizationMember.userId,- organizationId: selectedOrganization.id,+ organizationId,planId,+ ...(welcomePlan && {+ welcome: { priceMonthlyCents: welcomePlan.priceMonthlyCents, phase: setup ? 'setup' : 'payment' },+ }),})if (!saved) toast.info('After verifying your card, return to Plans to finish subscribing.')}@@ -148,7 +223,18 @@ function BillingPlanChange() {window.location.href = checkoutUrlreturn}- toast.success('Plan upgraded successfully')+ if (welcomeSubscription) {+ const plan = await billingApi.getOrganizationPlan(organizationId)+ if (scope?.signal.aborted) return+ if (isActivePlan(plan, planId)) {+ recordWelcomeCompletion(welcomeSubscription.userId, organizationId)+ navigate(RoutePath.QUICKSTART, { replace: true })+ return+ }+ toast.info('Check Billing for your subscription status.')+ } else {+ toast.success('Plan upgraded successfully')+ }} else {await downgradePlan.mutateAsync({ organizationId: selectedOrganization.id, planId })// Name the plan and the day: "at the next billing cycle" left the user@@ -159,24 +245,33 @@ function BillingPlanChange() {// organization now holds.navigate(RoutePath.BILLING, { replace: true })} catch (error) {+ if (welcomePlan && scope?.signal.aborted) returnsetSubmission('idle')handleApiError(error, `Failed to ${summary.action} organization plan`)}}return (- <PlanChangeShell title={summary.title}>+ <PlanChangeShell title={summary.title} backTo={backTo}><div className="flex flex-col gap-6"><section><SectionTitle title={summary.target?.name ?? planId} /><Panel className="px-[22px] py-2">{summary.comparisons.map((comparison) => (- <ComparisonRow key={comparison.label} comparison={comparison} />+ <ComparisonRow+ key={comparison.label}+ comparison={+ welcomePlan && comparison.label === 'Price'+ ? { ...comparison, to: `${formatAmount(welcomePlan.priceMonthlyCents)}/mo` }+ : comparison+ }+ />))}</Panel>- <PanelNote>{summary.effect}</PanelNote>+ {welcomePlan ? <WelcomeSubscriptionTerms plan={welcomePlan} /> : <PanelNote>{summary.effect}</PanelNote>}{summary.action === 'upgrade' && walletQuery.data?.creditCardConnected === false && (<PanelNote>+ {welcomePlan && 'Stripe places a temporary $0.50 hold to verify your card and releases it afterward. '}After you verify your card, we’ll continue your subscription to {summary.target?.name ?? planId}{' '}automatically.</PanelNote>@@ -208,7 +303,7 @@ function BillingPlanChange() {</AsciiButton>{/* Cancelling mid-request would leave the user unsure whether thechange went through, so it waits with the confirm button. */}- <AsciiButton disabled={pending} onClick={() => navigate(RoutePath.BILLING)}>+ <AsciiButton disabled={pending} onClick={() => navigate(backTo)}>Cancel</AsciiButton></div>@@ -218,9 +313,34 @@ function BillingPlanChange() {)}-function PlanChangeShell({ title = 'Change plan', children }: { title?: string; children: React.ReactNode }) {+function WelcomeSubscriptionTerms({ plan }: { plan: { name: string; priceMonthlyCents: number } }) {+ const eligibility = useOwnerTrialEligibilityQuery()+ const duration =+ eligibility.isSuccess && !eligibility.isFetching+ ? trialDuration(eligibility.data.find((offer) => offer.name === plan.name))+ : undefined+ const amount = formatAmount(plan.priceMonthlyCents)+ return (+ <PanelNote>+ {duration && `If you qualify at activation, you pay $0 in subscription fees for ${duration.toLowerCase()}. `}+ You’ll pay {amount} when the trial ends, or {amount} at activation if a trial does not apply. The subscription+ renews monthly at {amount}. Cancel in Billing before the trial ends to avoid the first subscription fee.+ </PanelNote>+ )+}++function PlanChangeShell({+ title = 'Change plan',+ backTo = RoutePath.BILLING,+ children,+}: {+ title?: string+ backTo?: RoutePath+ children: React.ReactNode+}) {usePageTitle(title)const navigate = useNavigate()+ const backLabel = backTo === RoutePath.WELCOME ? 'Back to Welcome' : 'Back to Billing'return (<div className="page-container">@@ -230,9 +350,9 @@ function PlanChangeShell({ title = 'Change plan', children }: { title?: string;variant="ghost"size="icon-sm"className="shrink-0"- aria-label="Back to Billing"- title="Back to Billing"- onClick={() => navigate(RoutePath.BILLING)}+ aria-label={backLabel}+ title={backLabel}+ onClick={() => navigate(backTo)}><ArrowLeft className="size-4" /></Button>diff --git a/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsxindex feea4ba2a..acf24ea56 100644--- a/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx+++ b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx@@ -7,20 +7,32 @@ import { MemoryRouter, Route, Routes } from 'react-router-dom'import { toast } from 'sonner'import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { BoxliteError } from '@/api/errors'+import FirstBoxWelcome from '@/components/first-run/FirstBoxWelcome'import { RoutePath } from '@/enums/RoutePath'import Billing from '../Billing'import BillingPlanChange from '../BillingPlanChange'const api = vi.hoisted(() => ({+ getOrganizationCheckoutUrl: vi.fn(),+ getOrganizationOnboarding: vi.fn(),getOrganizationPlan: vi.fn(),getOrganizationWallet: vi.fn(),+ getPlanTrialEligibility: vi.fn(),getUsagePrices: vi.fn(),+ listAllPaymentMethods: vi.fn(),listPlans: vi.fn(),upgradePlan: vi.fn(),}))const viewer = vi.hoisted(() => ({ organizationId: 'org-1', userId: 'user-1', role: 'owner' }))vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } }))-vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ billingApi: api }) }))+vi.mock('@/hooks/useApi', () => ({+ useApi: () => ({ billingApi: api, getOrganizationOnboarding: api.getOrganizationOnboarding }),+}))+vi.mock('@/hooks/useOrganizations', () => ({ useOrganizations: () => ({ refreshOrganizations: vi.fn() }) }))+vi.mock('@/components/first-run/FirstBoxAtmosphere', () => ({+ default: ({ children }: { children: React.ReactNode }) => children,+}))+vi.mock('@/components/first-run/WelcomeJourneyArtwork', () => ({ default: () => null }))vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({ billingApiUrl: 'https://billing.example.test' }) }))vi.mock('react-oidc-context', () => ({useAuth: () => ({ user: { profile: { sub: viewer.userId, email_verified: true } } }),@@ -55,8 +67,13 @@ beforeEach(() => {vi.resetAllMocks()Object.assign(viewer, { organizationId: 'org-1', userId: 'user-1', role: 'owner' })sessionStorage.clear()+ localStorage.clear()+ api.getOrganizationCheckoutUrl.mockResolvedValue(setupUrl)+ api.getOrganizationOnboarding.mockResolvedValue({ useCase: 'exploring', note: '' })api.getOrganizationPlan.mockResolvedValue(null)api.getOrganizationWallet.mockResolvedValue(wallet)+ api.getPlanTrialEligibility.mockResolvedValue([{ name: pro.name, eligible: true, durationSeconds: 259_200 }])+ api.listAllPaymentMethods.mockResolvedValue([])api.listPlans.mockResolvedValue([pro])api.getUsagePrices.mockResolvedValue({ schemaVersion: 1, currency: 'USD', prices: [] })api.upgradePlan.mockResolvedValueOnce(setupUrl).mockResolvedValue(undefined)@@ -82,6 +99,7 @@ afterEach(async () => {await unmount()host.remove()sessionStorage.clear()+ localStorage.clear()vi.restoreAllMocks()vi.unstubAllGlobals()})@@ -100,6 +118,8 @@ async function visit(path: string) {<Routes><Route path={RoutePath.BILLING_PLAN_CHANGE} element={<BillingPlanChange />} /><Route path={RoutePath.BILLING} element={<Billing />} />+ <Route path={RoutePath.WELCOME} element={<FirstBoxWelcome />} />+ <Route path={RoutePath.QUICKSTART} element={<h1>Quickstart</h1>} /></Routes></MemoryRouter></QueryClientProvider>@@ -264,3 +284,138 @@ it('opens ordinary Billing with a connected card without submitting an upgrade',await returnToBilling()expect(api.upgradePlan).not.toHaveBeenCalled()})++const welcomeProgressKey = 'boxlite:welcome:user-1:org-1'++async function chooseWelcomePlan() {+ await visit(RoutePath.WELCOME)+ const choose = () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Choose Pro')+ await eventually(() => {+ expect(choose()).toBeDefined()+ expect(host.textContent).toContain('3 days free')+ })+ await act(async () => choose()!.click())+ await eventually(() => expect(host.querySelector('h1')?.textContent).toBe('Subscribe'))+ expect(api.getOrganizationCheckoutUrl).not.toHaveBeenCalled()+ expect(api.upgradePlan).not.toHaveBeenCalled()+}++async function subscribeFromWelcome() {+ const subscribe = () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Subscribe')+ await eventually(() => expect(subscribe()?.disabled).toBe(false))+ await act(async () => subscribe()!.click())+}++function activatePlan(status: 'active' | 'past_due' = 'active') {+ api.getOrganizationPlan.mockResolvedValue({+ planId: pro.id,+ planName: pro.name,+ status,+ cycleFrom: new Date('2026-11-01'),+ cycleTo: new Date('2026-12-01'),+ includedQuotaCents: pro.includedQuotaCents,+ quotaConsumedCents: 0,+ quotaRemainingCents: pro.includedQuotaCents,+ })+}++async function expectWelcomeCompleted() {+ await eventually(() => expect(host.querySelector('h1')?.textContent).toBe('Quickstart'))+ expect(JSON.parse(localStorage.getItem(welcomeProgressKey)!)).toMatchObject({ completedAt: expect.any(Number) })+}++it('Welcome subscription confirms the paid terms before card setup and submits exactly once after verification', async () => {+ api.listPlans.mockResolvedValue([{ ...pro, priceMonthlyCents: 14_925 }])+ api.upgradePlan.mockReset().mockImplementation(async () => {+ activatePlan()+ })+ await chooseWelcomePlan()+ await eventually(() => expect(host.textContent).toContain('$149.25 at activation if a trial does not apply'))+ await subscribeFromWelcome()+ await eventually(() => expect(location.href).toBe(setupUrl))+ expect(api.getOrganizationCheckoutUrl).toHaveBeenCalledExactlyOnceWith('org-1')+ expect(api.upgradePlan).not.toHaveBeenCalled()+ expect(localStorage.getItem(welcomeProgressKey)).toBeNull()++ connectCard()+ await visit(RoutePath.BILLING)+ await expectWelcomeCompleted()+ await returnToBilling()+ expect(api.upgradePlan).toHaveBeenCalledExactlyOnceWith('org-1', pro.id)+})++it('Welcome subscription with a saved card completes after the immediate subscription succeeds', async () => {+ connectCard()+ api.upgradePlan.mockReset().mockImplementation(async () => {+ activatePlan()+ })+ await chooseWelcomePlan()+ await subscribeFromWelcome()+ await expectWelcomeCompleted()+ expect(api.upgradePlan).toHaveBeenCalledExactlyOnceWith('org-1', pro.id)+ expect(api.getOrganizationCheckoutUrl).not.toHaveBeenCalled()+})++it.each([true, false])(+ 'Welcome subscription checks bank authentication without resubmitting, cardless=%s',+ async (cardless) => {+ const opaqueUrl = 'https://checkout.stripe.com/c/pay/opaque_return'+ api.getOrganizationCheckoutUrl.mockResolvedValue(opaqueUrl)+ api.upgradePlan.mockReset().mockResolvedValue(opaqueUrl)+ if (!cardless) connectCard()+ await chooseWelcomePlan()+ await subscribeFromWelcome()+ await eventually(() => expect(location.href).toBe(opaqueUrl))+ if (cardless) {+ expect(api.upgradePlan).not.toHaveBeenCalled()+ connectCard()+ await visit(RoutePath.BILLING)+ await eventually(() => expect(location.href).toBe(opaqueUrl))+ }+ expect(localStorage.getItem(welcomeProgressKey)).toBeNull()+ activatePlan()+ await visit(RoutePath.BILLING)+ await expectWelcomeCompleted()+ expect(api.upgradePlan).toHaveBeenCalledExactlyOnceWith('org-1', pro.id)+ },+)++it.each(['price change', 'canceled card setup', 'different plan'])(+ 'Welcome subscription abandons the handoff after %s',+ async (reason) => {+ await chooseWelcomePlan()+ await subscribeFromWelcome()+ await eventually(() => expect(location.href).toBe(setupUrl))+ if (reason !== 'canceled card setup') connectCard()+ if (reason === 'price change') api.listPlans.mockResolvedValue([{ ...pro, priceMonthlyCents: 15_000 }])+ if (reason === 'different plan') api.getOrganizationPlan.mockResolvedValue({ planId: 'another', status: 'active' })+ await visit(RoutePath.BILLING)+ await eventually(() => expect(host.querySelector('[aria-label="Onboarding progress"]')).not.toBeNull(), 5_000)+ expect(api.upgradePlan).not.toHaveBeenCalled()+ expect(localStorage.getItem(welcomeProgressKey)).toBeNull()+ },+)++it('Welcome subscription leaves a payment that is still past due in Billing', async () => {+ connectCard()+ api.upgradePlan.mockReset().mockResolvedValue(authenticationUrl)+ await chooseWelcomePlan()+ await subscribeFromWelcome()+ await eventually(() => expect(location.href).toBe(authenticationUrl))+ activatePlan('past_due')+ await returnToBilling()+ expect(api.upgradePlan).toHaveBeenCalledExactlyOnceWith('org-1', pro.id)+ expect(localStorage.getItem(welcomeProgressKey)).toBeNull()+})++it('Welcome subscription does not continue if the organization changed during setup', async () => {+ await chooseWelcomePlan()+ await subscribeFromWelcome()+ await eventually(() => expect(location.href).toBe(setupUrl))+ connectCard()+ viewer.organizationId = 'org-2'+ await returnToBilling()+ expect(api.upgradePlan).not.toHaveBeenCalled()+ expect(localStorage.getItem(welcomeProgressKey)).toBeNull()+ expect(localStorage.getItem('boxlite:welcome:user-1:org-2')).toBeNull()+})