Skip to content

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

feat(dashboard): continue plan upgrades after card setup (#3026)

Ricky Chin9fcfb98528ae
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index 40f427841..ab0ce548c 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -297,6 +297,22 @@ Billing separates account status in Overview from the grouped Plans comparison.
See [subscription plans](docs/subscription-cards/README.md) for source facts,
frontend presentation, catalogue-price checks and the local mock preview.
+When an owner confirms an upgrade without a saved card, returning to Billing in
+the same tab continues the selected subscription automatically. The confirmation
+lasts 30 minutes and belongs to the signed-in owner and organization. Billing
+reads the wallet again on return. If the card is still missing, Billing checks
+twice more at one-second intervals, then ends the attempt. Once the card is
+visible, Billing checks the current plan before submitting. The bank may still ask
+the owner to authenticate the payment. **Add payment method** saves a card
+independently.
+
+Card status is organization-wide. A card added concurrently by another owner
+can satisfy the check. Closing the tab ends the handoff.
+
+The [before](docs/subscription-cards/upgrade-return-before.png) and
+[after](docs/subscription-cards/upgrade-return-after.png) views show Billing
+after the same simulated card setup.
+
## Commands
Run these from `apps/`:
diff --git a/apps/dashboard/docs/subscription-cards/upgrade-return-after.png b/apps/dashboard/docs/subscription-cards/upgrade-return-after.png
new file mode 100644
index 000000000..9081087f8
Binary files /dev/null and b/apps/dashboard/docs/subscription-cards/upgrade-return-after.png differ
diff --git a/apps/dashboard/docs/subscription-cards/upgrade-return-before.png b/apps/dashboard/docs/subscription-cards/upgrade-return-before.png
new file mode 100644
index 000000000..315fbe92e
Binary files /dev/null and b/apps/dashboard/docs/subscription-cards/upgrade-return-before.png differ
diff --git a/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx b/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx
new file mode 100644
index 000000000..75409dde4
--- /dev/null
+++ b/apps/dashboard/src/components/billing/PlanUpgradeReturn.tsx
@@ -0,0 +1,74 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+
+import { useUpgradePlanMutation } from '@/hooks/mutations/useUpgradePlanMutation'
+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 { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
+import { useEffect } from 'react'
+import { useAuth } from 'react-oidc-context'
+import { toast } from 'sonner'
+
+export function PlanUpgradeReturn({ selection, onFinish }: { selection: PendingPlanUpgrade; onFinish: () => void }) {
+ const { user } = useAuth()
+ const { selectedOrganization, organizationMembersStatus, authenticatedUserOrganizationMember } =
+ useSelectedOrganization()
+ const { billingApi } = useApi()
+ const { mutateAsync: upgrade } = useUpgradePlanMutation()
+ const organizationId = selectedOrganization?.id
+ const userId = user?.profile.sub
+ const isOwner = authenticatedUserOrganizationMember?.role === OrganizationUserRoleEnum.OWNER
+
+ useEffect(() => {
+ if (!userId || !organizationId || organizationMembersStatus === 'loading') return
+ let active = true
+ async function resume() {
+ try {
+ if (
+ organizationId !== selection.organizationId ||
+ userId !== selection.userId ||
+ organizationMembersStatus !== 'ready' ||
+ !isOwner ||
+ selection.expiresAt <= Date.now()
+ ) {
+ return
+ }
+
+ 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
+ const plan = await billingApi.getOrganizationPlan(organizationId)
+ if (!active || (plan?.planId === selection.planId && plan.status !== 'canceled')) return
+ if (selection.expiresAt <= Date.now() || !clearPendingPlanUpgrade(selection)) return
+
+ const url = await upgrade({ organizationId, planId: selection.planId })
+ if (!active) return
+ if (url) window.location.href = url
+ else toast.success('Plan upgraded successfully')
+ } catch (error) {
+ if (active) handleApiError(error, 'Could not complete the plan upgrade')
+ } finally {
+ if (active) {
+ clearPendingPlanUpgrade(selection)
+ onFinish()
+ }
+ }
+ }
+ void resume()
+ return () => {
+ active = false
+ }
+ }, [billingApi, isOwner, onFinish, organizationId, organizationMembersStatus, selection, upgrade, userId])
+
+ return (
+ <div className="page-container py-6" role="status">
+ Checking your plan upgrade…
+ </div>
+ )
+}
diff --git a/apps/dashboard/src/hooks/useConnectCard.ts b/apps/dashboard/src/hooks/useConnectCard.ts
index 16f947611..c8c0f85a0 100644
--- a/apps/dashboard/src/hooks/useConnectCard.ts
+++ b/apps/dashboard/src/hooks/useConnectCard.ts
@@ -1,6 +1,7 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { createElement, useCallback } from 'react'
import { toast } from 'sonner'
+import { clearPendingPlanUpgrade } from '@/lib/pending-plan-upgrade'
import { useFetchOwnerCheckoutUrlQuery, useIsOwnerCheckoutUrlFetching } from './queries/billingQueries'
export function useConnectCard() {
@@ -8,6 +9,7 @@ export function useConnectCard() {
const isPending = useIsOwnerCheckoutUrlFetching()
const connectCard = useCallback(async () => {
+ clearPendingPlanUpgrade()
const newWindow = window.open('', '_blank')
try {
const url = await fetchCheckoutUrl()
diff --git a/apps/dashboard/src/lib/auth-session.ts b/apps/dashboard/src/lib/auth-session.ts
index 5cd39f4dd..6a2b0cb2d 100644
--- a/apps/dashboard/src/lib/auth-session.ts
+++ b/apps/dashboard/src/lib/auth-session.ts
@@ -6,6 +6,7 @@
import { RoutePath } from '@/enums/RoutePath'
import { CI_CALLBACK_PATH, clearCiConnectSession } from './ci-connect'
import { ORGANIZATION_SESSION_KEY } from './organization-session'
+import { clearPendingPlanUpgrade } from './pending-plan-upgrade'
const SIGN_IN_INTENT_KEY = 'boxlite-just-logged-out'
type SignInIntent = { signedOut: boolean; returnTo: string }
@@ -48,6 +49,7 @@ export function getSignInIntent(): SignInIntent | null {
}
export function markJustLoggedOut(returnTo?: unknown) {
+ clearPendingPlanUpgrade()
sessionStorage.setItem(SIGN_IN_INTENT_KEY, JSON.stringify({ signedOut: true, returnTo: safeReturnTo(returnTo) }))
sessionStorage.removeItem(ORGANIZATION_SESSION_KEY)
clearCiConnectSession()
diff --git a/apps/dashboard/src/lib/pending-plan-upgrade.ts b/apps/dashboard/src/lib/pending-plan-upgrade.ts
new file mode 100644
index 000000000..6b7dd0380
--- /dev/null
+++ b/apps/dashboard/src/lib/pending-plan-upgrade.ts
@@ -0,0 +1,51 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+
+const key = 'boxlite.billing.pendingUpgrade'
+const checkoutWindowMs = 30 * 60 * 1000
+
+export type PendingPlanUpgrade = {
+ userId: string
+ organizationId: string
+ planId: string
+ expiresAt: number
+}
+
+export function rememberPlanUpgrade(selection: Omit<PendingPlanUpgrade, 'expiresAt'>) {
+ try {
+ sessionStorage.setItem(key, JSON.stringify({ ...selection, expiresAt: Date.now() + checkoutWindowMs }))
+ return true
+ } catch {
+ return false
+ }
+}
+
+// Only the page holding this confirmation can claim it before submitting.
+export function clearPendingPlanUpgrade(selection?: PendingPlanUpgrade): boolean {
+ try {
+ if (selection && sessionStorage.getItem(key) !== JSON.stringify(selection)) return false
+ sessionStorage.removeItem(key)
+ return true
+ } catch {
+ return false
+ }
+}
+
+export function readPendingPlanUpgrade(): PendingPlanUpgrade | null {
+ try {
+ const stored = sessionStorage.getItem(key)
+ if (!stored) return null
+ const value = JSON.parse(stored)
+ if (
+ typeof value?.userId === 'string' &&
+ typeof value.organizationId === 'string' &&
+ typeof value.planId === 'string' &&
+ Number.isFinite(value.expiresAt) &&
+ value.expiresAt > Date.now()
+ ) {
+ return value
+ }
+ } catch {
+ return null
+ }
+ return null
+}
diff --git a/apps/dashboard/src/pages/Billing.tsx b/apps/dashboard/src/pages/Billing.tsx
index 7246c3875..efb02819b 100644
--- a/apps/dashboard/src/pages/Billing.tsx
+++ b/apps/dashboard/src/pages/Billing.tsx
@@ -9,6 +9,7 @@ import { BalanceLowBanner } from '@/components/billing/BalanceLowBanner'
import { BillingAlerts } from '@/components/billing/BillingAlerts'
import { PlansSection } from '@/components/billing/PlansSection'
import { PlanSection } from '@/components/billing/PlanSection'
+import { PlanUpgradeReturn } from '@/components/billing/PlanUpgradeReturn'
import { UsageSection } from '@/components/billing/UsageSection'
import { WalletSection } from '@/components/billing/WalletSection'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
@@ -17,6 +18,8 @@ import { useConfig } from '@/hooks/useConfig'
import { Clock, Cpu, Database, MemoryStick, type LucideIcon } from '@/components/ui/icon'
import { Link, useSearchParams } from 'react-router-dom'
import { usePageTitle } from '@/hooks/usePageTitle'
+import { readPendingPlanUpgrade } from '@/lib/pending-plan-upgrade'
+import { useCallback, useState } from 'react'
const TAB_PANE = 'py-6'
@@ -85,6 +88,8 @@ function BillingComingSoon() {
function Billing() {
usePageTitle('Billing')
const config = useConfig()
+ const [pendingUpgrade, setPendingUpgrade] = useState(readPendingPlanUpgrade)
+ const finishUpgradeReturn = useCallback(() => setPendingUpgrade(null), [])
// Controlled, so the page-level balance warning can send the user to Wallet.
const [searchParams, setSearchParams] = useSearchParams()
const requestedTab = searchParams.get('tab')
@@ -100,6 +105,9 @@ function Billing() {
if (!config.billingApiUrl) {
return <BillingComingSoon />
}
+ if (pendingUpgrade) {
+ return <PlanUpgradeReturn selection={pendingUpgrade} onFinish={finishUpgradeReturn} />
+ }
return (
<Tabs value={tab} onValueChange={setTab} className="w-full gap-0">
diff --git a/apps/dashboard/src/pages/BillingPlanChange.tsx b/apps/dashboard/src/pages/BillingPlanChange.tsx
index 2abda841e..16b82d742 100644
--- a/apps/dashboard/src/pages/BillingPlanChange.tsx
+++ b/apps/dashboard/src/pages/BillingPlanChange.tsx
@@ -17,9 +17,10 @@ import { usePlansQuery } from '@/hooks/queries/usePlansQuery'
import { useConfig } from '@/hooks/useConfig'
import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'
import { handleApiError } from '@/lib/error-handling'
+import { clearPendingPlanUpgrade, rememberPlanUpgrade } from '@/lib/pending-plan-upgrade'
import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
import { format } from 'date-fns'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { Navigate, useNavigate, useParams } from 'react-router-dom'
import { toast } from 'sonner'
import { usePageTitle } from '@/hooks/usePageTitle'
@@ -41,7 +42,20 @@ function BillingPlanChange() {
const plansQuery = usePlansQuery()
const upgradePlan = useUpgradePlanMutation()
const downgradePlan = useDowngradePlanMutation()
- const [leaving, setLeaving] = useState(false)
+ const [submission, setSubmission] = useState<'idle' | 'confirming' | 'redirecting'>('idle')
+ useEffect(() => {
+ // Back from Stripe abandons this checkout, including when the browser
+ // restores the confirmation page from its back/forward cache.
+ function resetConfirmation(event: PageTransitionEvent) {
+ if (event.persisted) {
+ clearPendingPlanUpgrade()
+ setSubmission('idle')
+ }
+ }
+ clearPendingPlanUpgrade()
+ window.addEventListener('pageshow', resetConfirmation)
+ return () => window.removeEventListener('pageshow', resetConfirmation)
+ }, [])
// Members load in the background from an empty list
// (SelectedOrganizationProvider.tsx:97-113), so a missing member means
@@ -110,19 +124,27 @@ function BillingPlanChange() {
return <Navigate to={RoutePath.BILLING} replace />
}
- const pending = upgradePlan.isPending || downgradePlan.isPending || leaving
+ const pending = submission !== 'idle' || upgradePlan.isPending || downgradePlan.isPending
// Only a downgrade defers, and a downgrade always has a live cycle to defer
// into — but read it defensively rather than asserting the branch.
const rollDay = planQuery.data ? format(planQuery.data.cycleTo, 'MMM d, yyyy') : 'the next billing cycle'
const handleConfirm = async () => {
+ setSubmission('confirming')
try {
if (summary.action === 'upgrade') {
+ const { data: wallet } = await walletQuery.refetch({ throwOnError: true })
const checkoutUrl = await upgradePlan.mutateAsync({ organizationId: selectedOrganization.id, planId })
if (checkoutUrl) {
- // Hold the pending state through the hand-off: the browser takes a
- // moment to leave, and an idle-looking button invites a second click.
- setLeaving(true)
+ if (wallet?.creditCardConnected === false && authenticatedUserOrganizationMember?.userId) {
+ const saved = rememberPlanUpgrade({
+ userId: authenticatedUserOrganizationMember.userId,
+ organizationId: selectedOrganization.id,
+ planId,
+ })
+ if (!saved) toast.info('After verifying your card, return to Plans to finish subscribing.')
+ }
+ setSubmission('redirecting')
window.location.href = checkoutUrl
return
}
@@ -137,6 +159,7 @@ function BillingPlanChange() {
// organization now holds.
navigate(RoutePath.BILLING, { replace: true })
} catch (error) {
+ setSubmission('idle')
handleApiError(error, `Failed to ${summary.action} organization plan`)
}
}
@@ -152,6 +175,12 @@ function BillingPlanChange() {
))}
</Panel>
<PanelNote>{summary.effect}</PanelNote>
+ {summary.action === 'upgrade' && walletQuery.data?.creditCardConnected === false && (
+ <PanelNote>
+ After you verify your card, we’ll continue your subscription to {summary.target?.name ?? planId}{' '}
+ automatically.
+ </PanelNote>
+ )}
</section>
{(summary.quotaNote || summary.walletNote || summary.caveats.length > 0) && (
@@ -175,7 +204,7 @@ function BillingPlanChange() {
className="inline-flex items-center gap-2"
>
{pending && <Spinner className="size-3.5" />}
- {leaving ? 'Redirecting to Stripe…' : summary.confirmLabel}
+ {submission === 'redirecting' ? 'Redirecting to Stripe…' : summary.confirmLabel}
</AsciiButton>
{/* Cancelling mid-request would leave the user unsure whether the
change went through, so it waits with the confirm button. */}
diff --git a/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx
new file mode 100644
index 000000000..feea4ba2a
--- /dev/null
+++ b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx
@@ -0,0 +1,266 @@
+// @vitest-environment jsdom
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { StrictMode, act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+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 { RoutePath } from '@/enums/RoutePath'
+import Billing from '../Billing'
+import BillingPlanChange from '../BillingPlanChange'
+
+const api = vi.hoisted(() => ({
+ getOrganizationPlan: vi.fn(),
+ getOrganizationWallet: vi.fn(),
+ getUsagePrices: 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/useConfig', () => ({ useConfig: () => ({ billingApiUrl: 'https://billing.example.test' }) }))
+vi.mock('react-oidc-context', () => ({
+ useAuth: () => ({ user: { profile: { sub: viewer.userId, email_verified: true } } }),
+}))
+vi.mock('@/hooks/useSelectedOrganization', () => ({
+ useSelectedOrganization: () => {
+ const member = { organizationId: viewer.organizationId, userId: viewer.userId, role: viewer.role }
+ return {
+ selectedOrganization: { id: viewer.organizationId, name: 'Acme' },
+ authenticatedUserOrganizationMember: member,
+ organizationMembers: [member],
+ organizationMembersStatus: 'ready',
+ }
+ },
+}))
+
+const pro = {
+ id: 'pro',
+ name: 'Pro',
+ priceMonthlyCents: 14_900,
+ includedQuotaCents: 25_000,
+ concurrencyLimit: 100,
+ selfServe: true,
+}
+const wallet = { name: 'Acme', balanceCents: 0, ongoingBalanceCents: 0, creditCardConnected: false }
+const setupUrl = 'https://checkout.stripe.com/c/pay/cs_test_setup'
+const authenticationUrl = 'https://invoice.stripe.com/i/test_authentication'
+let location: URL, host: HTMLDivElement, root: Root | undefined, client: QueryClient
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ vi.resetAllMocks()
+ Object.assign(viewer, { organizationId: 'org-1', userId: 'user-1', role: 'owner' })
+ sessionStorage.clear()
+ api.getOrganizationPlan.mockResolvedValue(null)
+ api.getOrganizationWallet.mockResolvedValue(wallet)
+ api.listPlans.mockResolvedValue([pro])
+ api.getUsagePrices.mockResolvedValue({ schemaVersion: 1, currency: 'USD', prices: [] })
+ api.upgradePlan.mockResolvedValueOnce(setupUrl).mockResolvedValue(undefined)
+ location = new URL(window.location.href)
+ vi.stubGlobal(
+ 'window',
+ new Proxy(window, {
+ get: (target, key) => (key === 'location' ? location : Reflect.get(target, key, target)),
+ }),
+ )
+ host = document.createElement('div')
+ document.body.append(host)
+})
+
+async function unmount() {
+ if (!root) return
+ await act(async () => root!.unmount())
+ root = undefined
+ client.clear()
+}
+
+afterEach(async () => {
+ await unmount()
+ host.remove()
+ sessionStorage.clear()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+// A document navigation drops the React tree and its queries but keeps the tab's session storage.
+async function visit(path: string) {
+ await unmount()
+ location = new URL(path, 'https://console.example.test')
+ root = createRoot(host)
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
+ await act(async () =>
+ root!.render(
+ <StrictMode>
+ <QueryClientProvider client={client}>
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route path={RoutePath.BILLING_PLAN_CHANGE} element={<BillingPlanChange />} />
+ <Route path={RoutePath.BILLING} element={<Billing />} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>
+ </StrictMode>,
+ ),
+ )
+}
+
+async function eventually(assert: () => void, timeout = 1000) {
+ await vi.waitFor(
+ async () => {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ assert()
+ },
+ { timeout },
+ )
+}
+
+async function confirmPlan(expectedUrl = setupUrl) {
+ await visit(`${RoutePath.BILLING_PLAN}/pro`)
+ const subscribe = () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Subscribe')
+ await eventually(() => expect(subscribe()?.disabled).toBe(false))
+ await act(async () => subscribe()!.click())
+ await eventually(() => expect(location.href).toBe(expectedUrl))
+ expect(api.upgradePlan).toHaveBeenCalledExactlyOnceWith('org-1', 'pro')
+}
+
+async function returnToBilling() {
+ await visit(RoutePath.BILLING)
+ await eventually(() => {
+ expect(host.querySelector('h1')?.textContent).toBe('Billing')
+ expect(client.isFetching()).toBe(0)
+ expect(client.isMutating()).toBe(0)
+ }, 5000)
+}
+
+function connectCard() {
+ api.getOrganizationWallet.mockResolvedValue({ ...wallet, creditCardConnected: true })
+}
+
+it('submits the confirmed plan once after card setup, including across a Billing reload', async () => {
+ await confirmPlan()
+ connectCard()
+ await returnToBilling()
+ await eventually(() =>
+ expect(api.upgradePlan.mock.calls).toEqual([
+ ['org-1', 'pro'],
+ ['org-1', 'pro'],
+ ]),
+ )
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(2)
+})
+
+it('leaves a canceled card setup closed when a card is later added independently', async () => {
+ await confirmPlan()
+ await returnToBilling()
+ connectCard()
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+}, 10_000)
+
+it('abandons the upgrade when Back restores its confirmation page', async () => {
+ await confirmPlan()
+ await act(async () => {
+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))
+ })
+ const cancel = [...host.querySelectorAll('button')].find((button) => button.textContent === 'Cancel')!
+ expect(cancel.disabled).toBe(false)
+ connectCard()
+ await act(async () => cancel.click())
+ await eventually(() => expect(host.querySelector('h1')?.textContent).toBe('Billing'))
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+})
+
+it('does not submit an expired checkout on a later Billing visit', async () => {
+ await confirmPlan()
+ connectCard()
+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 24 * 60 * 60 * 1000)
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+})
+
+it('waits for the saved card to become visible before submitting the plan', async () => {
+ await confirmPlan()
+ let cardConnected = false
+ const walletRead = vi.fn(() => Promise.resolve({ ...wallet, creditCardConnected: cardConnected }))
+ api.getOrganizationWallet.mockImplementation(walletRead)
+ await visit(RoutePath.BILLING)
+ await eventually(() => expect(walletRead).toHaveBeenCalled())
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+ expect(host.querySelector('[role="status"]')?.textContent).toMatch(/checking/i)
+ cardConnected = true
+ await eventually(() => expect(api.upgradePlan).toHaveBeenCalledTimes(2), 5000)
+ expect(api.upgradePlan).toHaveBeenLastCalledWith('org-1', 'pro')
+}, 10_000)
+
+it('skips an upgrade when the confirmed plan is already active on return', async () => {
+ await confirmPlan()
+ connectCard()
+ api.getOrganizationPlan.mockResolvedValue({
+ planId: pro.id,
+ planName: pro.name,
+ status: 'active',
+ cycleFrom: new Date('2026-11-01'),
+ cycleTo: new Date('2026-12-01'),
+ includedQuotaCents: 25_000,
+ quotaConsumedCents: 0,
+ quotaRemainingCents: 25_000,
+ })
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+})
+
+it('follows the resumed payment authentication URL without submitting again on its return', async () => {
+ api.upgradePlan.mockResolvedValueOnce(authenticationUrl)
+ await confirmPlan()
+ connectCard()
+ await visit(RoutePath.BILLING)
+ await eventually(() => expect(location.href).toBe(authenticationUrl))
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(2)
+})
+
+it('keeps an existing-card payment authentication separate from card setup', async () => {
+ connectCard()
+ api.upgradePlan.mockReset().mockResolvedValueOnce(authenticationUrl)
+ await confirmPlan(authenticationUrl)
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+})
+
+it.each([
+ ['getOrganizationPlan', 1],
+ ['upgradePlan', 2],
+] as const)('shows a %s failure and leaves any further submission to the owner', async (operation, expectedCalls) => {
+ await confirmPlan()
+ connectCard()
+ api[operation].mockRejectedValueOnce(new BoxliteError('Billing request failed'))
+ await returnToBilling()
+ await eventually(() => expect(toast.error).toHaveBeenCalled())
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(expectedCalls)
+})
+
+it.each([
+ ['organizationId', 'org-2'],
+ ['userId', 'user-2'],
+ ['role', 'member'],
+] as const)('does not submit across a change in %s', async (field, value) => {
+ await confirmPlan()
+ connectCard()
+ viewer[field] = value
+ await returnToBilling()
+ expect(api.upgradePlan).toHaveBeenCalledTimes(1)
+})
+
+it('opens ordinary Billing with a connected card without submitting an upgrade', async () => {
+ connectCard()
+ await returnToBilling()
+ expect(api.upgradePlan).not.toHaveBeenCalled()
+})