Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat: move billing management to web dashboard\n\n

Steven Enamakela5b7c9d83e09
diff --git a/app/src/components/rewards/RewardsCouponSection.tsx b/app/src/components/rewards/RewardsCouponSection.tsx
deleted file mode 100644
index 07005c611c..0000000000
--- a/app/src/components/rewards/RewardsCouponSection.tsx
+++ /dev/null
@@ -1,283 +0,0 @@
-import createDebug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { useUser } from '../../hooks/useUser';
-import { useT } from '../../lib/i18n/I18nContext';
-import { useCoreState } from '../../providers/CoreStateProvider';
-import { type CreditBalance, creditsApi, type RedeemedCoupon } from '../../services/api/creditsApi';
-import { Button, TextField } from '../ui';
-
-const log = createDebug('openhuman:rewards-coupons');
-
-function formatUsd(amount: number): string {
- return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
-}
-
-function formatDateTime(value: string | null, pendingLabel: string): string {
- if (!value) return pendingLabel;
- const date = new Date(value);
- return Number.isNaN(date.getTime()) ? pendingLabel : date.toLocaleString();
-}
-
-function redemptionStatusClass(coupon: RedeemedCoupon): string {
- if (coupon.fulfilled) return 'bg-sage-100 dark:bg-sage-500/20 text-sage-700 dark:text-sage-300';
- if (coupon.activationType === 'CONDITIONAL')
- return 'bg-amber-50 dark:bg-amber-500/10 text-amber-800 dark:text-amber-200';
- return 'bg-surface-subtle text-content-secondary';
-}
-
-const RewardsCouponSection = () => {
- const { t } = useT();
- const { snapshot } = useCoreState();
- const { refetch } = useUser();
- const token = snapshot.sessionToken;
-
- const [couponCode, setCouponCode] = useState('');
- const [creditBalance, setCreditBalance] = useState<CreditBalance | null>(null);
- const [redeemedCoupons, setRedeemedCoupons] = useState<RedeemedCoupon[]>([]);
- const [loading, setLoading] = useState(false);
- const [submitLoading, setSubmitLoading] = useState(false);
- const [loadError, setLoadError] = useState<string | null>(null);
- const [submitError, setSubmitError] = useState<string | null>(null);
- const [submitSuccess, setSubmitSuccess] = useState<string | null>(null);
- const latestRequestIdRef = useRef(0);
-
- const loadCouponState = useCallback(async () => {
- if (!token) {
- latestRequestIdRef.current += 1;
- setCreditBalance(null);
- setRedeemedCoupons([]);
- setLoadError(null);
- setLoading(false);
- return;
- }
-
- latestRequestIdRef.current += 1;
- const requestId = latestRequestIdRef.current;
- setLoading(true);
- setLoadError(null);
-
- try {
- log('[load] fetching balance and coupon history');
- const [balance, coupons] = await Promise.all([
- creditsApi.getBalance(),
- creditsApi.getUserCoupons(),
- ]);
-
- if (requestId !== latestRequestIdRef.current) return;
-
- log('[load] loaded balance=%O coupons=%d', balance, coupons.length);
- setCreditBalance(balance);
- setRedeemedCoupons(coupons);
- } catch (error) {
- if (requestId !== latestRequestIdRef.current) return;
- const message =
- error && typeof error === 'object' && 'error' in error
- ? String((error as { error: unknown }).error)
- : 'Could not load reward codes right now.';
- log('[load] failed: %s', message);
- setLoadError(message);
- } finally {
- if (requestId === latestRequestIdRef.current) {
- setLoading(false);
- }
- }
- }, [token]);
-
- useEffect(() => {
- void loadCouponState();
- }, [loadCouponState]);
-
- const handleRedeem = async () => {
- const code = couponCode.trim();
- if (!code || submitLoading) return;
-
- setSubmitLoading(true);
- setSubmitError(null);
- setSubmitSuccess(null);
-
- try {
- log('[redeem] submitting code=%s', code);
- const result = await creditsApi.redeemCoupon(code);
- const successMsg = result.pending
- ? t('rewards.coupon.redeemAccepted')
- .replace('{code}', result.couponCode)
- .replace('{amount}', formatUsd(result.amountUsd))
- : t('rewards.coupon.redeemSuccess')
- .replace('{code}', result.couponCode)
- .replace('{amount}', formatUsd(result.amountUsd));
- setSubmitSuccess(successMsg);
- setCouponCode('');
-
- const refreshResults = await Promise.allSettled([loadCouponState(), refetch()]);
- const refreshFailures = refreshResults.filter(
- (result): result is PromiseRejectedResult => result.status === 'rejected'
- );
- if (refreshFailures.length > 0) {
- log('[redeem] refresh failed count=%d', refreshFailures.length);
- }
-
- log(
- '[redeem] completed code=%s pending=%s amount=%s',
- result.couponCode,
- result.pending,
- result.amountUsd
- );
- } catch (error) {
- const message =
- error && typeof error === 'object' && 'error' in error
- ? String((error as { error: unknown }).error)
- : 'Could not apply that reward code.';
- log('[redeem] failed: %s', message);
- setSubmitError(message);
- } finally {
- setSubmitLoading(false);
- }
- };
-
- if (!token) {
- return null;
- }
-
- return (
- <>
- <section className="bg-surface rounded-2xl shadow-soft border border-line p-6 space-y-5">
- <div className="grid gap-4 sm:grid-cols-2">
- <div className="rounded-xl border border-line bg-surface-muted p-4">
- <div className="text-xs font-medium uppercase tracking-wide text-content-faint">
- {t('rewards.coupon.promoCredits')}
- </div>
- <div className="mt-2 text-2xl font-semibold text-content">
- {creditBalance ? formatUsd(creditBalance.promotionBalanceUsd) : loading ? '…' : '—'}
- </div>
- </div>
- <div className="rounded-xl border border-line bg-surface-muted p-4">
- <div className="text-xs font-medium uppercase tracking-wide text-content-faint">
- {t('rewards.coupon.redeemedCodes')}
- </div>
- <div className="mt-2 text-2xl font-semibold text-content">{redeemedCoupons.length}</div>
- </div>
- </div>
-
- <div className="rounded-xl border border-primary-100 bg-primary-50/40 p-4 space-y-3">
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
- <TextField
- type="text"
- value={couponCode}
- onChange={event => {
- setCouponCode(event.target.value.toUpperCase());
- if (submitError) setSubmitError(null);
- if (submitSuccess) setSubmitSuccess(null);
- }}
- onKeyDown={event => {
- if (event.key === 'Enter') {
- void handleRedeem();
- }
- }}
- placeholder={t('rewards.coupon.placeholder')}
- disabled={submitLoading}
- mono
- className="flex-1"
- />
- <Button
- variant="primary"
- size="md"
- onClick={() => void handleRedeem()}
- disabled={submitLoading || !couponCode.trim()}>
- {submitLoading ? t('rewards.coupon.redeeming') : t('rewards.coupon.redeemButton')}
- </Button>
- </div>
- {submitSuccess ? (
- <div className="rounded-xl border border-sage-200 dark:border-sage-500/30 bg-sage-50 dark:bg-sage-500/10 px-3 py-2 text-sm text-sage-800 dark:text-sage-200">
- {submitSuccess}
- </div>
- ) : null}
- {submitError ? (
- <div className="rounded-xl border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-3 py-2 text-sm text-coral-800 dark:text-coral-200">
- {submitError}
- </div>
- ) : null}
- {loadError ? (
- <div className="rounded-xl border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-3 py-2 text-sm text-coral-800 dark:text-coral-200">
- {loadError}
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => void loadCouponState()}
- className="ml-2 underline">
- {t('common.retry')}
- </Button>
- </div>
- ) : null}
- </div>
- </section>
- <section className="bg-surface rounded-2xl shadow-soft border border-line p-6 space-y-5">
- <div className="space-y-2">
- <div className="flex items-center justify-between gap-3">
- <h3 className="text-sm font-semibold text-content">
- {t('rewards.coupon.recentRedemptions')}
- </h3>
- <Button
- variant="tertiary"
- size="xs"
- onClick={() => void loadCouponState()}
- disabled={loading}
- className="text-content-muted hover:text-content-secondary">
- {t('common.refresh')}
- </Button>
- </div>
-
- {loading && redeemedCoupons.length === 0 ? (
- <p className="text-sm text-content-muted">{t('rewards.coupon.loadingHistory')}</p>
- ) : null}
-
- {redeemedCoupons.length === 0 && !loading && !loadError ? (
- <p className="text-sm text-content-muted rounded-xl border border-dashed border-line px-4 py-6 text-center">
- {t('rewards.coupon.noCodes')}
- </p>
- ) : redeemedCoupons.length > 0 ? (
- <div className="overflow-x-auto rounded-xl border border-line">
- <table className="min-w-full text-sm text-left">
- <thead className="bg-surface-muted text-xs uppercase tracking-wide text-content-muted">
- <tr>
- <th className="px-3 py-2 font-medium">{t('rewards.coupon.colCode')}</th>
- <th className="px-3 py-2 font-medium">{t('rewards.coupon.colReward')}</th>
- <th className="px-3 py-2 font-medium">{t('rewards.coupon.colStatus')}</th>
- <th className="px-3 py-2 font-medium">{t('rewards.coupon.colRedeemed')}</th>
- </tr>
- </thead>
- <tbody className="divide-y divide-line-subtle">
- {redeemedCoupons.map(coupon => (
- <tr
- key={`${coupon.code}-${coupon.redeemedAt ?? coupon.activationType}`}
- className="bg-surface">
- <td className="px-3 py-2 font-mono text-content">{coupon.code}</td>
- <td className="px-3 py-2 text-content-secondary">
- {formatUsd(coupon.amountUsd)}
- </td>
- <td className="px-3 py-2">
- <span
- className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${redemptionStatusClass(coupon)}`}>
- {coupon.fulfilled
- ? t('rewards.coupon.statusApplied')
- : coupon.activationType === 'CONDITIONAL'
- ? t('rewards.coupon.statusPendingAction')
- : t('rewards.coupon.statusRedeemed')}
- </span>
- </td>
- <td className="px-3 py-2 text-xs text-content-muted">
- {formatDateTime(coupon.redeemedAt, t('rewards.coupon.pending'))}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : null}
- </div>
- </section>
- </>
- );
-};
-
-export default RewardsCouponSection;
diff --git a/app/src/components/rewards/RewardsRedeemTab.tsx b/app/src/components/rewards/RewardsRedeemTab.tsx
deleted file mode 100644
index f59b732ac1..0000000000
--- a/app/src/components/rewards/RewardsRedeemTab.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import RewardsCouponSection from './RewardsCouponSection';
-
-export default function RewardsRedeemTab() {
- return (
- <>
- <RewardsCouponSection />
- </>
- );
-}
diff --git a/app/src/components/rewards/__tests__/RewardsCouponSection.test.tsx b/app/src/components/rewards/__tests__/RewardsCouponSection.test.tsx
deleted file mode 100644
index 684badbeb4..0000000000
--- a/app/src/components/rewards/__tests__/RewardsCouponSection.test.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import RewardsCouponSection from '../RewardsCouponSection';
-
-const mocks = vi.hoisted(() => ({
- mockUseCoreState: vi.fn(),
- mockUseUser: vi.fn(),
- mockCreditsApi: { getBalance: vi.fn(), getUserCoupons: vi.fn(), redeemCoupon: vi.fn() },
-}));
-
-vi.mock('../../../providers/CoreStateProvider', () => ({
- useCoreState: () => mocks.mockUseCoreState(),
-}));
-
-vi.mock('../../../hooks/useUser', () => ({ useUser: () => mocks.mockUseUser() }));
-
-vi.mock('../../../services/api/creditsApi', () => ({ creditsApi: mocks.mockCreditsApi }));
-
-describe('RewardsCouponSection', () => {
- const refetch = vi.fn();
-
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.mockUseCoreState.mockReturnValue({ snapshot: { sessionToken: 'test-token' } });
- mocks.mockUseUser.mockReturnValue({ refetch });
- });
-
- it('loads balances and refreshes history after a successful redemption', async () => {
- mocks.mockCreditsApi.getBalance
- .mockResolvedValueOnce({ promotionBalanceUsd: 3, teamTopupUsd: 1 })
- .mockResolvedValueOnce({ promotionBalanceUsd: 8, teamTopupUsd: 1 });
- mocks.mockCreditsApi.getUserCoupons
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([
- {
- code: 'APRL-2026',
- amountUsd: 5,
- redeemedAt: '2026-04-09T19:00:00.000Z',
- activationType: 'IMMEDIATE',
- activationCondition: null,
- fulfilled: true,
- fulfilledAt: '2026-04-09T19:00:01.000Z',
- },
- ]);
- mocks.mockCreditsApi.redeemCoupon.mockResolvedValueOnce({
- couponCode: 'APRL-2026',
- amountUsd: 5,
- pending: false,
- });
-
- render(<RewardsCouponSection />);
-
- expect(await screen.findByText('$3.00')).toBeInTheDocument();
- expect(screen.getByText('No reward codes redeemed yet.')).toBeInTheDocument();
-
- fireEvent.change(screen.getByPlaceholderText('Coupon code'), {
- target: { value: 'aprl-2026' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Redeem Code' }));
-
- expect(
- await screen.findByText('APRL-2026 redeemed. $5.00 was added to your credits.')
- ).toBeInTheDocument();
-
- await waitFor(() => {
- expect(screen.getByText('$8.00')).toBeInTheDocument();
- });
- expect(screen.getByText('APRL-2026')).toBeInTheDocument();
- expect(screen.getByText('Applied')).toBeInTheDocument();
- expect(refetch).toHaveBeenCalledTimes(1);
- });
-
- it('shows backend redemption errors without clearing the existing state', async () => {
- mocks.mockCreditsApi.getBalance.mockResolvedValue({ promotionBalanceUsd: 3, teamTopupUsd: 0 });
- mocks.mockCreditsApi.getUserCoupons.mockResolvedValue([]);
- mocks.mockCreditsApi.redeemCoupon.mockRejectedValueOnce({
- error: 'This coupon has already been used.',
- });
-
- render(<RewardsCouponSection />);
-
- expect(await screen.findByText('$3.00')).toBeInTheDocument();
-
- fireEvent.change(screen.getByPlaceholderText('Coupon code'), {
- target: { value: 'used-code' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Redeem Code' }));
-
- expect(await screen.findByText('This coupon has already been used.')).toBeInTheDocument();
- expect(mocks.mockCreditsApi.getBalance).toHaveBeenCalledTimes(1);
- expect(refetch).not.toHaveBeenCalled();
- });
-
- it('shows pending coupon copy and keeps the current balance until the reward is fulfilled', async () => {
- mocks.mockCreditsApi.getBalance
- .mockResolvedValueOnce({ promotionBalanceUsd: 3, teamTopupUsd: 0 })
- .mockResolvedValueOnce({ promotionBalanceUsd: 3, teamTopupUsd: 0 });
- mocks.mockCreditsApi.getUserCoupons
- .mockResolvedValueOnce([])
- .mockResolvedValueOnce([
- {
- code: 'APRL-2026',
- amountUsd: 5,
- redeemedAt: '2026-04-09T19:00:00.000Z',
- activationType: 'CONDITIONAL',
- activationCondition: 'SUBSCRIBE_PAID_PLAN',
- fulfilled: false,
- fulfilledAt: null,
- },
- ]);
- mocks.mockCreditsApi.redeemCoupon.mockResolvedValueOnce({
- couponCode: 'APRL-2026',
- amountUsd: 5,
- pending: true,
- });
-
- render(<RewardsCouponSection />);
-
- expect(await screen.findByText('$3.00')).toBeInTheDocument();
-
- fireEvent.change(screen.getByPlaceholderText('Coupon code'), {
- target: { value: 'aprl-2026' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Redeem Code' }));
-
- expect(
- await screen.findByText(
- 'APRL-2026 accepted. $5.00 will unlock after the required action is completed.'
- )
- ).toBeInTheDocument();
-
- await waitFor(() => {
- expect(screen.getAllByText('$3.00')).toHaveLength(1);
- });
- expect(screen.getByText('APRL-2026')).toBeInTheDocument();
- expect(screen.getByText('Pending action')).toBeInTheDocument();
- expect(refetch).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/app/src/components/settings/panels/BillingPanel.test.tsx b/app/src/components/settings/panels/BillingPanel.test.tsx
index 9f8bfbc265..ed861267de 100644
--- a/app/src/components/settings/panels/BillingPanel.test.tsx
+++ b/app/src/components/settings/panels/BillingPanel.test.tsx
@@ -4,6 +4,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import BillingPanel from './BillingPanel';
const navigateBack = vi.fn();
+const openUrlMock = vi.fn();
+const getSummaryMock = vi.fn();
+const getTeamUsageMock = vi.fn();
vi.mock('../hooks/useSettingsNavigation', () => ({
useSettingsNavigation: () => ({
@@ -14,185 +17,116 @@ vi.mock('../hooks/useSettingsNavigation', () => ({
}),
}));
-const openUrlMock = vi.fn();
vi.mock('../../../utils/openUrl', () => ({ openUrl: (url: string) => openUrlMock(url) }));
-
-const getCurrentPlanMock = vi.fn();
-const purchasePlanMock = vi.fn();
-const createCoinbaseChargeMock = vi.fn();
-
vi.mock('../../../services/api/billingApi', () => ({
- billingApi: {
- getCurrentPlan: (...args: unknown[]) => getCurrentPlanMock(...args),
- purchasePlan: (...args: unknown[]) => purchasePlanMock(...args),
- createCoinbaseCharge: (...args: unknown[]) => createCoinbaseChargeMock(...args),
- },
+ billingApi: { getSummary: (...args: unknown[]) => getSummaryMock(...args) },
+}));
+vi.mock('../../../services/api/creditsApi', () => ({
+ creditsApi: { getTeamUsage: (...args: unknown[]) => getTeamUsageMock(...args) },
}));
+const summary = {
+ credits: { promotionBalanceUsd: 4.5, teamTopupUsd: 10, totalUsd: 14.5 },
+ plan: {
+ plan: 'PRO',
+ hasActiveSubscription: true,
+ planExpiry: '2026-12-01T00:00:00.000Z',
+ subscription: null,
+ monthlyBudgetUsd: 100,
+ weeklyBudgetUsd: 25,
+ },
+ links: {
+ topUpUrl: 'https://staging.tinyhumans.ai/dashboard?tab=billing',
+ manageUrl: 'https://staging.tinyhumans.ai/dashboard?tab=plans',
+ apiKeysUrl: 'https://staging.tinyhumans.ai/dashboard?tab=api-keys',
+ },
+};
+
+const usage = {
+ remainingUsd: 39.5,
+ cycleBudgetUsd: 25,
+ cycleSpentUsd: 6,
+ cycleStartDate: '2026-09-07T00:00:00.000Z',
+ cycleEndsAt: '2026-09-14T00:00:00.000Z',
+ plan: {
+ plan: 'PRO',
+ name: 'Pro',
+ marginPercent: 10,
+ payAsYouGoMarginPercent: 100,
+ discountVsPayAsYouGoPercent: 90,
+ },
+ insights: {
+ period: { startDate: '2026-09-07', endDate: '2026-09-14' },
+ totals: {
+ inferenceUsd: 5,
+ integrationsUsd: 1,
+ totalUsd: 6,
+ inferenceCalls: 20,
+ integrationCalls: 2,
+ },
+ dailySeries: [],
+ topModels: [],
+ topIntegrations: [],
+ },
+};
+
describe('<BillingPanel />', () => {
beforeEach(() => {
vi.clearAllMocks();
openUrlMock.mockResolvedValue(undefined);
- getCurrentPlanMock.mockResolvedValue({
- plan: 'FREE',
- hasActiveSubscription: false,
- planExpiry: null,
- subscription: null,
- monthlyBudgetUsd: 0,
- weeklyBudgetUsd: 0,
- });
- purchasePlanMock.mockResolvedValue({
- checkoutUrl: 'https://checkout.stripe.com/test',
- sessionId: 'test-session',
- });
- createCoinbaseChargeMock.mockResolvedValue({
- gatewayTransactionId: 'test-gw',
- hostedUrl: 'https://commerce.coinbase.com/test',
- status: 'NEW',
- expiresAt: '2026-01-01T00:00:00Z',
- });
+ getSummaryMock.mockResolvedValue(summary);
+ getTeamUsageMock.mockResolvedValue(usage);
});
- it('renders the plan selector and the dashboard button without auto-opening the browser', async () => {
+ it('shows plan, balances, cycle spend, and total funds remaining', async () => {
render(<BillingPanel />);
- // SubscriptionPlans renders its own title; billing frequency selection is
- // back in-app so users can change their plan without leaving the desktop app.
- expect(screen.getByText('Choose a Plan')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Open billing dashboard' })).toBeInTheDocument();
-
- // getCurrentPlan is called on mount but must not trigger a browser open.
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
- expect(openUrlMock).not.toHaveBeenCalled();
- });
-
- it('loads the current plan tier on mount and passes it to SubscriptionPlans', async () => {
- getCurrentPlanMock.mockResolvedValue({
- plan: 'BASIC',
- hasActiveSubscription: true,
- planExpiry: null,
- subscription: null,
- monthlyBudgetUsd: 20,
- weeklyBudgetUsd: 10,
- });
-
- render(<BillingPanel />);
-
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
- // With BASIC as current tier the BASIC card shows the "Current plan" badge.
- expect(await screen.findByText('Current plan')).toBeInTheDocument();
+ await waitFor(() => expect(getSummaryMock).toHaveBeenCalledTimes(1));
+ expect(getTeamUsageMock).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('PRO')).toBeInTheDocument();
+ expect(screen.getByText('$39.50')).toBeInTheDocument();
+ expect(screen.getByText('$4.50')).toBeInTheDocument();
+ expect(screen.getByText('$10.00')).toBeInTheDocument();
+ expect(screen.getByText(/Spent \$6\.00 this cycle/i)).toBeInTheDocument();
});
- it('upgrade with card payment calls purchasePlan and opens the checkout URL', async () => {
+ it('uses backend-provided dashboard URLs for billing actions', async () => {
render(<BillingPanel />);
+ await screen.findByText('$39.50');
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
-
- // Both BASIC and PRO show upgrade buttons when current tier is FREE.
- const upgradeButtons = screen.getAllByRole('button', { name: 'Upgrade' });
- fireEvent.click(upgradeButtons[0]);
+ fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
- await waitFor(() => expect(purchasePlanMock).toHaveBeenCalledTimes(1));
- expect(purchasePlanMock).toHaveBeenCalledWith('BASIC_MONTHLY');
- await waitFor(() =>
- expect(openUrlMock).toHaveBeenCalledWith('https://checkout.stripe.com/test')
- );
+ expect(openUrlMock).toHaveBeenNthCalledWith(1, summary.links.topUpUrl);
+ expect(openUrlMock).toHaveBeenNthCalledWith(2, summary.links.manageUrl);
});
- // The reason this PR exists: the interval toggle must reach `purchasePlan`.
- // The monthly case above passes on the DEFAULT interval, so it stays green
- // even if `buildPlanId(tier, billingInterval)` is hardcoded back to
- // 'monthly' — i.e. even with the bug in #5865 fully restored. This is the
- // case that fails when that happens.
- it('upgrade after selecting Annual sends the yearly plan id', async () => {
+ it('keeps usable cycle details visible when the aggregate summary fails', async () => {
+ getSummaryMock.mockRejectedValue(new Error('Summary unavailable'));
render(<BillingPanel />);
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
-
- fireEvent.click(screen.getByRole('button', { name: 'Annual' }));
-
- const upgradeButtons = await screen.findAllByRole('button', { name: 'Upgrade' });
- fireEvent.click(upgradeButtons[0]);
- await waitFor(() => expect(purchasePlanMock).toHaveBeenCalledTimes(1));
- expect(purchasePlanMock).toHaveBeenCalledWith('BASIC_YEARLY');
+ expect(await screen.findByText('Summary unavailable')).toBeInTheDocument();
+ expect(screen.getByText('$39.50')).toBeInTheDocument();
+ expect(screen.getByText(/Spent \$6\.00 this cycle/i)).toBeInTheDocument();
});
- // The crypto branch of `handleUpgrade` had no test at all: the mock was
- // declared and stubbed but never asserted on, so the whole branch was
- // unexecuted. Also pins the interval coupling from the Codex P1 — selecting
- // crypto forces `annual`, so the price on screen matches the charge.
- it('upgrade with crypto creates a Coinbase charge and opens the hosted URL', async () => {
- render(<BillingPanel />);
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
-
- fireEvent.click(screen.getByRole('switch'));
-
- const upgradeButtons = await screen.findAllByRole('button', { name: 'Upgrade' });
- fireEvent.click(upgradeButtons[0]);
-
- await waitFor(() => expect(createCoinbaseChargeMock).toHaveBeenCalledTimes(1));
- expect(createCoinbaseChargeMock).toHaveBeenCalledWith('BASIC');
- // Crypto must never go through the Stripe path.
- expect(purchasePlanMock).not.toHaveBeenCalled();
- await waitFor(() =>
- expect(openUrlMock).toHaveBeenCalledWith('https://commerce.coinbase.com/test')
- );
- // Selecting crypto switches the interval to annual, so the monthly
- // button is disabled and the displayed price cannot disagree with the
- // charge that was created.
- expect(screen.getByRole('button', { name: 'Monthly' })).toBeDisabled();
- });
-
- it('opens the billing dashboard when the user clicks the secondary button', async () => {
+ it('keeps plan and balances visible when cycle usage fails', async () => {
+ getTeamUsageMock.mockRejectedValue(new Error('Usage unavailable'));
render(<BillingPanel />);
- fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
- await waitFor(() => expect(openUrlMock).toHaveBeenCalledTimes(1));
- expect(openUrlMock).toHaveBeenLastCalledWith('https://tinyhumans.ai/dashboard');
+ expect(await screen.findByText('Usage unavailable')).toBeInTheDocument();
+ expect(screen.getByText('PRO')).toBeInTheDocument();
+ expect(screen.queryByText('$14.50')).not.toBeInTheDocument();
+ expect(screen.getAllByText('n/a').length).toBeGreaterThanOrEqual(1);
+ expect(screen.getByText(/Unable to load usage data/i)).toBeInTheDocument();
});
- it('invokes the navigation back handler from both the header and the inline button', async () => {
+ it('invokes the navigation back handler from both back buttons', async () => {
render(<BillingPanel />);
+ await screen.findByText('$39.50');
- // The SettingsHeader back button (aria-label "Back") and the inline
- // "Back to settings" button both route through navigateBack.
fireEvent.click(screen.getByRole('button', { name: 'Back' }));
fireEvent.click(screen.getByRole('button', { name: 'Back to settings' }));
expect(navigateBack).toHaveBeenCalledTimes(2);
});
-
- it('shows an error message when getCurrentPlan rejects', async () => {
- getCurrentPlanMock.mockRejectedValue(new Error('Network error'));
-
- render(<BillingPanel />);
-
- await waitFor(() => expect(screen.getByText('Network error')).toBeInTheDocument());
- });
-
- it('shows an error message when purchasePlan rejects', async () => {
- purchasePlanMock.mockRejectedValue(new Error('Payment failed'));
-
- render(<BillingPanel />);
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
-
- const upgradeButtons = screen.getAllByRole('button', { name: 'Upgrade' });
- fireEvent.click(upgradeButtons[0]);
-
- await waitFor(() => expect(screen.getByText('Payment failed')).toBeInTheDocument());
- });
-
- it('shows an error when purchasePlan returns no checkout URL', async () => {
- purchasePlanMock.mockResolvedValue({ checkoutUrl: null, sessionId: 'test-session' });
-
- render(<BillingPanel />);
- await waitFor(() => expect(getCurrentPlanMock).toHaveBeenCalledTimes(1));
-
- const upgradeButtons = screen.getAllByRole('button', { name: 'Upgrade' });
- fireEvent.click(upgradeButtons[0]);
-
- await waitFor(() =>
- expect(screen.getByText('Checkout session did not return a redirect URL')).toBeInTheDocument()
- );
- expect(openUrlMock).not.toHaveBeenCalled();
- });
});
diff --git a/app/src/components/settings/panels/BillingPanel.tsx b/app/src/components/settings/panels/BillingPanel.tsx
index 25c18c253b..91cc480e8b 100644
--- a/app/src/components/settings/panels/BillingPanel.tsx
+++ b/app/src/components/settings/panels/BillingPanel.tsx
@@ -1,92 +1,138 @@
+import createDebug from 'debug';
import { useEffect, useState } from 'react';
import { useT } from '../../../lib/i18n/I18nContext';
import { billingApi } from '../../../services/api/billingApi';
-import type { PlanTier } from '../../../types/api';
+import { creditsApi, type TeamUsage } from '../../../services/api/creditsApi';
+import type { BillingSummaryData } from '../../../types/api';
import { BILLING_DASHBOARD_URL } from '../../../utils/links';
import { openUrl } from '../../../utils/openUrl';
import Button from '../../ui/Button';
import { SettingsStatusLine } from '../controls';
import { useSettingsNavigation } from '../hooks/useSettingsNavigation';
import SettingsPanel from '../layout/SettingsPanel';
-import SubscriptionPlans from './billing/SubscriptionPlans';
-import { buildPlanId } from './billingHelpers';
+import InferenceBudget from './billing/InferenceBudget';
+
+const log = createDebug('openhuman:billing:panel');
+const formatUsd = (amount: number): string => `$${amount.toFixed(2)}`;
const BillingPanel = () => {
const { t } = useT();
const { navigateBack } = useSettingsNavigation();
- const [currentTier, setCurrentTier] = useState<PlanTier>('FREE');
- const [billingInterval, setBillingInterval] = useState<'monthly' | 'annual'>('monthly');
- const [paymentMethod, setPaymentMethod] = useState<'card' | 'crypto'>('card');
- const [isPurchasing, setIsPurchasing] = useState(false);
- const [purchasingTier, setPurchasingTier] = useState<PlanTier | null>(null);
+ const [summary, setSummary] = useState<BillingSummaryData | null>(null);
+ const [teamUsage, setTeamUsage] = useState<TeamUsage | null>(null);
+ const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [planLoading, setPlanLoading] = useState(true);
- const [planKnown, setPlanKnown] = useState(false);
- const paymentConfirmed = false;
useEffect(() => {
- billingApi
- .getCurrentPlan()
- .then(data => {
- setCurrentTier(data.plan);
- setPlanKnown(true);
- })
- .catch(err => setError(err instanceof Error ? err.message : String(err)))
- .finally(() => setPlanLoading(false));
- }, []);
+ let cancelled = false;
+
+ const load = async () => {
+ log('loading billing summary and cycle usage');
+ const [summaryResult, usageResult] = await Promise.allSettled([
+ billingApi.getSummary(),
+ creditsApi.getTeamUsage(),
+ ]);
+ if (cancelled) return;
+
+ if (summaryResult.status === 'fulfilled') {
+ setSummary(summaryResult.value);
+ } else {
+ log('summary load failed error=%s', String(summaryResult.reason));
+ }
- const handleSetPaymentMethod = (method: 'card' | 'crypto') => {
- setPaymentMethod(method);
- if (method === 'crypto') setBillingInterval('annual');
- };
-
- const handleUpgrade = async (tier: PlanTier): Promise<void> => {
- setError(null);
- setIsPurchasing(true);
- setPurchasingTier(tier);
- try {
- if (paymentMethod === 'crypto') {
- const charge = await billingApi.createCoinbaseCharge(tier);
- await openUrl(charge.hostedUrl);
+ if (usageResult.status === 'fulfilled') {
+ setTeamUsage(usageResult.value);
} else {
- const session = await billingApi.purchasePlan(buildPlanId(tier, billingInterval));
- if (session.checkoutUrl) {
- await openUrl(session.checkoutUrl);
- } else {
- throw new Error('Checkout session did not return a redirect URL');
- }
+ log('usage load failed error=%s', String(usageResult.reason));
+ }
+
+ const failure =
+ summaryResult.status === 'rejected'
+ ? summaryResult.reason
+ : usageResult.status === 'rejected'
+ ? usageResult.reason
+ : null;
+ if (failure) {
+ setError(failure instanceof Error ? failure.message : String(failure));
}
- } catch (err) {
- setError(err instanceof Error ? err.message : String(err));
- } finally {
- setIsPurchasing(false);
- setPurchasingTier(null);
- }
- };
+ setLoading(false);
+ log('billing state applied summary=%s usage=%s', summaryResult.status, usageResult.status);
+ };
+
+ void load();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // Only /teams/me/usage includes the remaining subscription-cycle allowance.
+ // The summary's totalUsd is wallet-only (promotion + top-up), so it is not a
+ // safe fallback for the account's true available balance.
+ const availableUsd = teamUsage?.remainingUsd;
+ const topUpUrl = summary?.links.topUpUrl ?? `${BILLING_DASHBOARD_URL}?tab=billing`;
+ const manageUrl = summary?.links.manageUrl ?? BILLING_DASHBOARD_URL;
return (
<SettingsPanel>
- <SettingsStatusLine saving={false} error={error} savingLabel="" />
- <SubscriptionPlans
- currentTier={currentTier}
- billingInterval={billingInterval}
- setBillingInterval={setBillingInterval}
- paymentMethod={paymentMethod}
- setPaymentMethod={handleSetPaymentMethod}
- isPurchasing={isPurchasing}
- purchasingTier={purchasingTier}
- paymentConfirmed={paymentConfirmed}
- upgradesDisabled={planLoading || !planKnown}
- onUpgrade={handleUpgrade}
- />
+ <SettingsStatusLine saving={loading} error={error} savingLabel={t('common.loading')} />
+
+ <section className="rounded-2xl border border-line bg-surface p-4 space-y-4">
+ <div className="space-y-1">
+ <h2 className="text-base font-semibold text-content">
+ {t('settings.billing.movedToWeb')}
+ </h2>
+ <p className="text-sm text-content-muted">{t('settings.billing.movedToWebDesc')}</p>
+ </div>
+
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <SummaryTile
+ label={t('settings.billing.subscription.currentPlan')}
+ value={
+ summary?.plan.plan ??
+ (loading ? '...' : t('settings.billing.inferenceBudget.notAvailable'))
+ }
+ />
+ <SummaryTile
+ label={t('settings.billing.payAsYouGo.available')}
+ value={
+ availableUsd === undefined
+ ? loading
+ ? '...'
+ : t('settings.billing.inferenceBudget.notAvailable')
+ : formatUsd(availableUsd)
+ }
+ />
+ <SummaryTile
+ label={t('settings.billing.payAsYouGo.promotionalCredits')}
+ value={
+ summary
+ ? formatUsd(summary.credits.promotionBalanceUsd)
+ : loading
+ ? '...'
+ : t('settings.billing.inferenceBudget.notAvailable')
+ }
+ />
+ <SummaryTile
+ label={t('settings.billing.payAsYouGo.topUpBalance')}
+ value={
+ summary
+ ? formatUsd(summary.credits.teamTopupUsd)
+ : loading
+ ? '...'
+ : t('settings.billing.inferenceBudget.notAvailable')
+ }
+ />
+ </div>
+ </section>
+
+ <InferenceBudget teamUsage={teamUsage} isLoadingCredits={loading} />
<div className="flex flex-wrap gap-3">
- <Button
- type="button"
- variant="secondary"
- size="md"
- onClick={() => void openUrl(BILLING_DASHBOARD_URL)}>
+ <Button type="button" variant="primary" size="md" onClick={() => void openUrl(topUpUrl)}>
+ {t('settings.billing.payAsYouGo.topUpCredits')}
+ </Button>
+ <Button type="button" variant="secondary" size="md" onClick={() => void openUrl(manageUrl)}>
{t('settings.billing.openDashboard')}
</Button>
<Button type="button" variant="tertiary" size="md" onClick={navigateBack}>
@@ -97,4 +143,11 @@ const BillingPanel = () => {
);
};
+const SummaryTile = ({ label, value }: { label: string; value: string }) => (
+ <div className="rounded-xl border border-line bg-surface-muted px-3 py-3">
+ <div className="text-[11px] text-content-muted">{label}</div>
+ <div className="mt-1 text-lg font-semibold text-content">{value}</div>
+ </div>
+);
+
export default BillingPanel;
diff --git a/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx b/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx
index d9cb799fb0..481574a8f2 100644
--- a/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx
+++ b/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx
@@ -65,11 +65,19 @@ describe('InferenceBudget', () => {
describe('with cycleBudgetUsd > 0', () => {
it('renders remaining / budget text in the header', () => {
- const usage = buildTeamUsage({ remainingUsd: 5, cycleBudgetUsd: 10 });
+ const usage = buildTeamUsage({ remainingUsd: 20, cycleBudgetUsd: 10, cycleSpentUsd: 5 });
render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
expect(screen.getByText(/\$5\.00 \/ \$10\.00 remaining/i)).toBeInTheDocument();
});
+ it('does not count promotional and top-up balances as recurring cycle budget', () => {
+ const usage = buildTeamUsage({ remainingUsd: 30, cycleBudgetUsd: 10, cycleSpentUsd: 8.5 });
+ const { container } = render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
+
+ expect(screen.getByText(/\$1\.50 \/ \$10\.00 remaining/i)).toBeInTheDocument();
+ expect(container.querySelector<HTMLElement>('.bg-amber-500')).toHaveStyle({ width: '15%' });
+ });
+
it('renders cycle-spent and cycle-ends date', () => {
const usage = buildTeamUsage({ cycleSpentUsd: 5, cycleEndsAt: '2026-05-31T00:00:00.000Z' });
render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
@@ -88,6 +96,12 @@ describe('InferenceBudget', () => {
render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
expect(screen.getByText(/Included subscription usage is exhausted/i)).toBeInTheDocument();
});
+
+ it('does not tell users to top up when non-cycle credits remain', () => {
+ const usage = buildTeamUsage({ remainingUsd: 5, cycleSpentUsd: 10 });
+ render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
+ expect(screen.queryByText(/Top up credits to keep using AI/i)).not.toBeInTheDocument();
+ });
});
describe('with cycleBudgetUsd === 0', () => {
diff --git a/app/src/components/settings/panels/billing/InferenceBudget.tsx b/app/src/components/settings/panels/billing/InferenceBudget.tsx
index 28b90ba241..c00a5cea37 100644
--- a/app/src/components/settings/panels/billing/InferenceBudget.tsx
+++ b/app/src/components/settings/panels/billing/InferenceBudget.tsx
@@ -27,6 +27,9 @@ const formatCycleEnds = (iso: string, notAvailable: string): string => {
const InferenceBudget = ({ teamUsage, isLoadingCredits }: InferenceBudgetProps) => {
const { t } = useT();
+ const cycleRemainingUsd = teamUsage
+ ? Math.max(0, teamUsage.cycleBudgetUsd - teamUsage.cycleSpentUsd)
+ : 0;
return (
<div className="rounded-2xl border border-line bg-surface p-3 space-y-3">
@@ -41,7 +44,7 @@ const InferenceBudget = ({ teamUsage, isLoadingCredits }: InferenceBudgetProps)
<span className="text-xs text-content-faint">
{teamUsage.cycleBudgetUsd > 0
? t('settings.billing.inferenceBudget.remainingSummary')
- .replace('{remaining}', fmtUsd(teamUsage.remainingUsd))
+ .replace('{remaining}', fmtUsd(cycleRemainingUsd))
.replace('{budget}', fmtUsd(teamUsage.cycleBudgetUsd))
: t('settings.billing.inferenceBudget.noRecurringPlanBudget')}
</span>
@@ -55,16 +58,16 @@ const InferenceBudget = ({ teamUsage, isLoadingCredits }: InferenceBudgetProps)
<div className="h-1.5 bg-surface-strong rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-300 ${
- teamUsage.remainingUsd <= 0
+ cycleRemainingUsd <= 0
? 'bg-coral-500'
- : teamUsage.remainingUsd / teamUsage.cycleBudgetUsd < 0.2
+ : cycleRemainingUsd / teamUsage.cycleBudgetUsd < 0.2
? 'bg-amber-500'
: 'bg-primary-500'
}`}
style={{
width: `${Math.max(
0,
- Math.min(100, (teamUsage.remainingUsd / teamUsage.cycleBudgetUsd) * 100)
+ Math.min(100, (cycleRemainingUsd / teamUsage.cycleBudgetUsd) * 100)
)}%`,
}}
/>
@@ -86,7 +89,7 @@ const InferenceBudget = ({ teamUsage, isLoadingCredits }: InferenceBudgetProps)
)}
</span>
</div>
- {teamUsage.remainingUsd <= 0 && (
+ {cycleRemainingUsd <= 0 && teamUsage.remainingUsd <= 0 && (
<p className="text-[11px] text-coral-400">
{t('settings.billing.inferenceBudget.exhaustedDesc')}
</p>
diff --git a/app/src/config/__tests__/navConfig.test.ts b/app/src/config/__tests__/navConfig.test.ts
index e61dfcdd50..e0bf475764 100644
--- a/app/src/config/__tests__/navConfig.test.ts
+++ b/app/src/config/__tests__/navConfig.test.ts
@@ -92,14 +92,12 @@ describe('AVATAR_MENU_ITEMS', () => {
expect(cloudOnly).toEqual(['billing', 'invites']);
});
- it('billing uses openUrl; all others use navigate', () => {
+ it('keeps every account-menu destination inside the app', () => {
const openUrlItems = AVATAR_MENU_ITEMS.filter(i => i.kind === 'openUrl').map(i => i.id);
- expect(openUrlItems).toEqual(['billing']);
+ expect(openUrlItems).toEqual([]);
});
- it('opens billing on the authenticated dashboard', () => {
- expect(AVATAR_MENU_ITEMS.find(i => i.id === 'billing')?.target).toBe(
- 'https://tinyhumans.ai/dashboard'
- );
+ it('opens the billing summary before the user chooses a web action', () => {
+ expect(AVATAR_MENU_ITEMS.find(i => i.id === 'billing')?.target).toBe('/settings/billing');
});
});
diff --git a/app/src/config/navConfig.ts b/app/src/config/navConfig.ts
index 2dcb15eba0..c967ee9250 100644
--- a/app/src/config/navConfig.ts
+++ b/app/src/config/navConfig.ts
@@ -5,8 +5,6 @@
* This module is pure data — no JSX, no React imports. Icons are owned by
* BottomTabBar.tsx and mapped from tab.id.
*/
-import { BILLING_DASHBOARD_URL } from '../utils/links';
-
// ── Tab bar ──────────────────────────────────────────────────────────────────
export interface NavTab {
@@ -114,8 +112,8 @@ export const AVATAR_MENU_ITEMS: AvatarMenuItem[] = [
{
id: 'billing',
labelKey: 'nav.avatarMenu.billing',
- target: BILLING_DASHBOARD_URL,
- kind: 'openUrl',
+ target: '/settings/billing',
+ kind: 'navigate',
cloudOnly: true,
},
{
diff --git a/app/src/pages/Rewards.tsx b/app/src/pages/Rewards.tsx
index 777d935023..f0dbf299d0 100644
--- a/app/src/pages/Rewards.tsx
+++ b/app/src/pages/Rewards.tsx
@@ -1,13 +1,12 @@
import createDebug from 'debug';
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { LuGift, LuTicket, LuUsers } from 'react-icons/lu';
+import { LuGift, LuUsers } from 'react-icons/lu';
import { useLocation, useNavigate } from 'react-router-dom';
import EmptyStateCard from '../components/EmptyStateCard';
import { SidebarContent } from '../components/layout/shell/SidebarSlot';
import TwoPaneNav from '../components/layout/TwoPaneNav';
import RewardsCommunityTab from '../components/rewards/RewardsCommunityTab';
-import RewardsRedeemTab from '../components/rewards/RewardsRedeemTab';
import RewardsReferralsTab from '../components/rewards/RewardsReferralsTab';
import SettingsTabbedPage from '../components/settings/layout/SettingsTabbedPage';
import { useT } from '../lib/i18n/I18nContext';
@@ -17,14 +16,14 @@ import type { RewardsSnapshot } from '../types/rewards';
import { isLocalSessionToken } from '../utils/localSession';
/**
- * The three Rewards surfaces. Each is its own page with a sidebar entry rather
+ * The two Rewards surfaces. Each is its own page with a sidebar entry rather
* than a chip tab on one page: they share no state and none of them is a
* refinement of another, so a tab row was hiding two destinations behind a
* third. `?view=` is the address so a page survives a reload and can be linked.
*/
-type RewardsView = 'rewards' | 'referrals' | 'redeem';
+type RewardsView = 'rewards' | 'referrals';
-const VIEWS: readonly RewardsView[] = ['rewards', 'referrals', 'redeem'] as const;
+const VIEWS: readonly RewardsView[] = ['rewards', 'referrals'] as const;
function isRewardsView(value: string): value is RewardsView {
return (VIEWS as readonly string[]).includes(value);
@@ -163,11 +162,6 @@ const Rewards = () => {
label: t('rewards.referrals'),
icon: <LuUsers className="h-4 w-4" />,
},
- {
- value: 'redeem',
- label: t('rewards.coupons'),
- icon: <LuTicket className="h-4 w-4" />,
- },
],
},
]}
@@ -214,25 +208,19 @@ const Rewards = () => {
description: t('rewards.referralSection.subtitle'),
body: <RewardsReferralsTab />,
}
- : view === 'redeem'
- ? {
- title: t('rewards.coupon.title'),
- description: t('rewards.coupon.subtitle'),
- body: <RewardsRedeemTab />,
- }
- : {
- title: t('rewards.title'),
- description: t('rewards.header.desc'),
- body: (
- <RewardsCommunityTab
- error={error}
- isLoading={isLoading}
- onRetry={handleRetry}
- onSilentRefresh={handleSilentRefresh}
- snapshot={rewardsSnapshot}
- />
- ),
- };
+ : {
+ title: t('rewards.title'),
+ description: t('rewards.header.desc'),
+ body: (
+ <RewardsCommunityTab
+ error={error}
+ isLoading={isLoading}
+ onRetry={handleRetry}
+ onSilentRefresh={handleSilentRefresh}
+ snapshot={rewardsSnapshot}
+ />
+ ),
+ };
return (
<>
diff --git a/app/src/pages/__tests__/Rewards.test.tsx b/app/src/pages/__tests__/Rewards.test.tsx
index 96eac63920..8110c28533 100644
--- a/app/src/pages/__tests__/Rewards.test.tsx
+++ b/app/src/pages/__tests__/Rewards.test.tsx
@@ -17,10 +17,6 @@ vi.mock('../../components/rewards/RewardsReferralsTab', () => ({
default: () => <div>Referral Rewards Section</div>,
}));
-vi.mock('../../components/rewards/RewardsRedeemTab', () => ({
- default: () => <div>Rewards Coupon Section</div>,
-}));
-
vi.mock('../../hooks/useUser', () => ({
useUser: () => ({ user: { subscription: { plan: 'FREE', hasActiveSubscription: false } } }),
}));
@@ -224,11 +220,10 @@ describe('Rewards page', () => {
);
expect(screen.getByText('Referral Rewards Section')).toBeInTheDocument();
- expect(screen.queryByText('Rewards Coupon Section')).not.toBeInTheDocument();
expect(screen.queryByText('Earn community roles')).not.toBeInTheDocument();
});
- it('switches to the redeem tab content', async () => {
+ it('falls back to community rewards for the retired redeem URL', async () => {
rewardsApi.getMyRewards.mockResolvedValueOnce({
discord: {
linked: false,
@@ -261,7 +256,7 @@ describe('Rewards page', () => {
</MemoryRouter>
);
- expect(screen.getByText('Rewards Coupon Section')).toBeInTheDocument();
+ expect(await screen.findByText('Earn rewards with OpenHuman')).toBeInTheDocument();
expect(screen.queryByText('Referral Rewards Section')).not.toBeInTheDocument();
});
diff --git a/app/src/services/api/__tests__/billingApi.test.ts b/app/src/services/api/__tests__/billingApi.test.ts
index 0224a4ff60..575a819a51 100644
--- a/app/src/services/api/__tests__/billingApi.test.ts
+++ b/app/src/services/api/__tests__/billingApi.test.ts
@@ -14,6 +14,24 @@ describe('billingApi', () => {
mockCallCoreCommand.mockReset();
});
+ describe('getSummary', () => {
+ it('calls the aggregate billing summary RPC', async () => {
+ const summary = {
+ credits: { promotionBalanceUsd: 2, teamTopupUsd: 3, totalUsd: 5 },
+ plan: { plan: 'FREE', hasActiveSubscription: false },
+ links: {
+ topUpUrl: 'https://tinyhumans.ai/dashboard?tab=billing',
+ manageUrl: 'https://tinyhumans.ai/dashboard?tab=plans',
+ apiKeysUrl: 'https://tinyhumans.ai/dashboard?tab=api-keys',
+ },
+ };
+ mockCallCoreCommand.mockResolvedValue(summary);
+
+ await expect(billingApi.getSummary()).resolves.toEqual(summary);
+ expect(mockCallCoreCommand).toHaveBeenCalledWith('openhuman.billing_get_summary');
+ });
+ });
+
describe('getCurrentPlan', () => {
it('should call openhuman.billing_get_current_plan', async () => {
const planData = {
diff --git a/app/src/services/api/billingApi.ts b/app/src/services/api/billingApi.ts
index ee934349f7..6fc8e3e37e 100644
--- a/app/src/services/api/billingApi.ts
+++ b/app/src/services/api/billingApi.ts
@@ -1,4 +1,5 @@
import type {
+ BillingSummaryData,
CoinbaseChargeData,
CurrentPlanData,
PlanIdentifier,
@@ -12,6 +13,11 @@ import { callCoreCommand } from '../coreCommandClient';
* Billing API endpoints
*/
export const billingApi = {
+ /** Get the read-only billing summary and hosted dashboard links. */
+ getSummary: async (): Promise<BillingSummaryData> => {
+ return await callCoreCommand<BillingSummaryData>('openhuman.billing_get_summary');
+ },
+
/**
* Get the current user's subscription plan
* GET /payments/stripe/currentPlan
diff --git a/app/src/types/api.ts b/app/src/types/api.ts
index fb436080da..ea6da3de6e 100644
--- a/app/src/types/api.ts
+++ b/app/src/types/api.ts
@@ -79,6 +79,12 @@ export interface CurrentPlanData {
weeklyBudgetUsd: number;
}
+export interface BillingSummaryData {
+ credits: { promotionBalanceUsd: number; teamTopupUsd: number; totalUsd: number };
+ plan: CurrentPlanData;
+ links: { topUpUrl: string; manageUrl: string; apiKeysUrl: string };
+}
+
export interface PurchasePlanData {
checkoutUrl: string | null;
sessionId: string;
diff --git a/gitbooks/features/billing-and-usage.md b/gitbooks/features/billing-and-usage.md
index 514fcdfb50..64d5447f05 100644
--- a/gitbooks/features/billing-and-usage.md
+++ b/gitbooks/features/billing-and-usage.md
@@ -50,11 +50,11 @@ Coupon codes are redeemed against the backend (`POST /coupons/redeem`), and you
### Where billing lives in the app
-The desktop **Settings → Billing** panel intentionally has no embedded payment UI. It links out to the hosted web **billing dashboard**, which is the single place to manage plans, cards and invoices. The agent can also read billing state through default-ON tools (plan, balance, transactions, cards, coupons, the Stripe portal link); every money-moving or payment-method mutator ships **default-OFF** behind a `billing_writes` toggle, and card deletion is flagged dangerous.
+The desktop **Settings → Billing** panel is read-only. It shows the current plan, promotional and top-up balances, total remaining funds, current-cycle spend, and usage breakdowns. Buttons link to the hosted web **billing dashboard**, which is the single place to manage plans, top-ups, coupons, cards, and invoices. The agent can also read billing state through default-ON tools (plan, balance, transactions, cards, coupons, the Stripe portal link); every money-moving or payment-method mutator ships **default-OFF** behind a `billing_writes` toggle, and card deletion is flagged dangerous.
### RPC surface
-Namespace `billing`, exposed as `openhuman.billing_*` (15 methods), e.g. `billing_get_current_plan`, `billing_get_balance`, `billing_get_transactions`, `billing_purchase_plan`, `billing_top_up`, `billing_create_coinbase_charge`, `billing_get_cards`, `billing_create_setup_intent`, `billing_update_auto_recharge`, `billing_redeem_coupon`.
+Namespace `billing`, exposed as `openhuman.billing_*` (16 methods), e.g. `billing_get_summary`, `billing_get_current_plan`, `billing_get_balance`, `billing_get_transactions`, `billing_purchase_plan`, `billing_top_up`, `billing_create_coinbase_charge`, `billing_get_cards`, `billing_create_setup_intent`, `billing_update_auto_recharge`, `billing_redeem_coupon`.
---
diff --git a/gitbooks/features/rewards-and-referrals.md b/gitbooks/features/rewards-and-referrals.md
index d750d978e4..788f3317f4 100644
--- a/gitbooks/features/rewards-and-referrals.md
+++ b/gitbooks/features/rewards-and-referrals.md
@@ -1,13 +1,13 @@
---
description: >-
- Invite friends, earn referral credit, redeem promo codes, and unlock Discord
- community roles - the in-app Rewards & Referrals surface.
+ Invite friends, earn referral credit, and unlock Discord community roles in
+ OpenHuman. Promo-code redemption lives in the hosted billing dashboard.
icon: gift
---
# Rewards & Referrals
-OpenHuman bundles three loosely related growth mechanics behind one surface: a **referral program** (share a code, earn credit when friends convert), **promo coupons** (redeem a code for promotional credit), and a **community rewards** track (link Discord, unlock roles as you hit usage milestones). Invite-code management lives on its own screen.
+OpenHuman's Rewards surface bundles a **referral program** (share a code, earn credit when friends convert) and a **community rewards** track (link Discord, unlock roles as you hit usage milestones). Promo coupons are redeemed in the hosted TinyHumans billing dashboard, and invite-code management lives on its own screen.
All of this requires a signed-in backend session. On a local-only session the Rewards page shows an empty state prompting you to sign in - none of these features work offline.
@@ -15,13 +15,12 @@ All of this requires a signed-in backend session. On a local-only session the Re
## The Rewards screen
-Lives at `/rewards` with three chip tabs. The middle **Rewards** (community) tab is selected by default.
+Lives at `/rewards` with two sidebar destinations. **Rewards** (community) is selected by default.
| Tab | What it does |
| ------------- | ----------------------------------------------------------------- |
| **Referrals** | Your referral code, earnings, and referred-user activity |
| **Rewards** | Discord connection, progress ring, and unlockable community roles |
-| **Coupons** | Redeem promo codes for promotional credit + redemption history |
---
@@ -54,11 +53,11 @@ Both fail closed with `no backend session token` when no session is stored.
---
-## Coupons (Redeem)
+## Coupons
-The Coupons tab redeems **promo codes** for promotional credit - separate from referral rewards. Two tiles show your **promo credit balance** (USD) and the **count of redeemed codes**. Enter a code and redeem; redemption is either applied immediately or accepted as **pending** when it's conditional on a later action.
+Coupon redemption and redemption history now live at **TinyHumans Dashboard → Pay as you go**, alongside promotional-credit and top-up balances. OpenHuman's Settings → Billing screen shows the read-only account summary and opens that hosted dashboard for redemption and other billing changes.
-A **recent redemptions** table lists each code, its reward amount, status, and when it was redeemed.
+The hosted dashboard lists each code, its reward amount, status, and redemption time. Redemption is either applied immediately or accepted as **pending** when it is conditional on a later action.
| Coupon status | Meaning |
| -------------- | ----------------------------------------------- |
diff --git a/src/core/jsonrpc_tests.rs b/src/core/jsonrpc_tests.rs
index 546cbeef0b..a08ba05b71 100644
--- a/src/core/jsonrpc_tests.rs
+++ b/src/core/jsonrpc_tests.rs
@@ -498,7 +498,7 @@ fn http_schema_dump_includes_openhuman_and_core_methods() {
assert!(
methods
.iter()
- .any(|m| m.method == "openhuman.billing_get_current_plan"),
+ .any(|m| m.method == "openhuman.billing_get_summary"),
"schema dump should include billing methods"
);
@@ -522,6 +522,18 @@ async fn billing_get_current_plan_rejects_unknown_param() {
assert!(err.contains("unknown param 'extra'"));
}
+#[tokio::test]
+async fn billing_get_summary_rejects_unknown_param() {
+ let err = invoke_method(
+ default_state(),
+ "openhuman.billing_get_summary",
+ json!({ "extra": true }),
+ )
+ .await
+ .expect_err("unknown param should fail");
+ assert!(err.contains("unknown param 'extra'"));
+}
+
#[tokio::test]
async fn billing_purchase_plan_missing_plan_fails_validation() {
let err = invoke_method(
@@ -688,6 +700,7 @@ async fn schema_dump_includes_new_billing_and_team_methods() {
let dump = build_http_schema_dump();
let methods: Vec<&str> = dump.methods.iter().map(|m| m.method.as_str()).collect();
for expected in &[
+ "openhuman.billing_get_summary",
"openhuman.billing_get_current_plan",
"openhuman.billing_purchase_plan",
"openhuman.billing_create_portal_session",
diff --git a/src/openhuman/hosted/billing/README.md b/src/openhuman/hosted/billing/README.md
index 996eebd8f2..7753bd8f5d 100644
--- a/src/openhuman/hosted/billing/README.md
+++ b/src/openhuman/hosted/billing/README.md
@@ -5,7 +5,7 @@ Thin RPC adapter domain over the hosted backend's payment API. It exposes plan l
## Responsibilities
- Authenticate each call with the stored app-session JWT (`Authorization: Bearer …`) and reject calls with no session.
-- Fetch current plan/entitlements (`/payments/stripe/currentPlan`) and credit balance (`/payments/credits/balance`).
+- Fetch the aggregate billing summary (`/payments/summary`), current plan/entitlements, and credit balance.
- Create Stripe Checkout sessions (`purchase_plan`), the Stripe customer portal session, and Stripe SetupIntents for adding cards.
- Initiate credit top-ups via Stripe or Coinbase, and create Coinbase Commerce charges (crypto / annual billing).
- Page credit transaction history; read/update Stripe auto-recharge settings; list/update/delete saved cards.
@@ -25,15 +25,16 @@ Thin RPC adapter domain over the hosted backend's payment API. It exposes plan l
From `mod.rs`:
-- `ops::*` — async handlers: `get_current_plan`, `get_balance`, `get_transactions`, `get_auto_recharge`, `update_auto_recharge`, `get_cards`, `create_setup_intent`, `update_card`, `delete_card`, `purchase_plan`, `create_portal_session`, `top_up_credits`, `create_coinbase_charge`, `redeem_coupon`, `get_user_coupons`. Each takes `&Config` (plus typed params) and returns `Result<RpcOutcome<Value>, String>`.
+- `ops::*` — async handlers: `get_summary`, `get_current_plan`, `get_balance`, `get_transactions`, `get_auto_recharge`, `update_auto_recharge`, `get_cards`, `create_setup_intent`, `update_card`, `delete_card`, `purchase_plan`, `create_portal_session`, `top_up_credits`, `create_coinbase_charge`, `redeem_coupon`, `get_user_coupons`. Each takes `&Config` (plus typed params) and returns `Result<RpcOutcome<Value>, String>`.
- `all_billing_controller_schemas()`, `all_billing_registered_controllers()`, `billing_schemas(function: &str)` — registry wiring.
## RPC / controllers
-Namespace `billing` (15 methods, exposed as `openhuman.billing_*`):
+Namespace `billing` (16 methods, exposed as `openhuman.billing_*`):
| Method | Backend endpoint |
| --- | --- |
+| `billing_get_summary` | `GET /payments/summary` |
| `billing_get_current_plan` | `GET /payments/stripe/currentPlan` |
| `billing_get_balance` | `GET /payments/credits/balance` |
| `billing_get_transactions` | `GET /payments/credits/transactions?limit&offset` |
diff --git a/src/openhuman/hosted/billing/ops.rs b/src/openhuman/hosted/billing/ops.rs
index 844f06342d..3f01bb5b39 100644
--- a/src/openhuman/hosted/billing/ops.rs
+++ b/src/openhuman/hosted/billing/ops.rs
@@ -53,6 +53,11 @@ pub async fn get_current_plan(config: &Config) -> Result<RpcOutcome<Value>, Stri
))
}
+pub async fn get_summary(config: &Config) -> Result<RpcOutcome<Value>, String> {
+ let data = get_authed_value(config, Method::GET, "/payments/summary", None).await?;
+ Ok(RpcOutcome::single_log(data, "billing summary fetched"))
+}
+
pub async fn get_balance(config: &Config) -> Result<RpcOutcome<Value>, String> {
let data = get_authed_value(config, Method::GET, "/payments/credits/balance", None).await?;
Ok(RpcOutcome::single_log(data, "credit balance fetched"))
diff --git a/src/openhuman/hosted/billing/schemas.rs b/src/openhuman/hosted/billing/schemas.rs
index 6ba8cbd027..856b281cc7 100644
--- a/src/openhuman/hosted/billing/schemas.rs
+++ b/src/openhuman/hosted/billing/schemas.rs
@@ -65,6 +65,7 @@ struct RedeemCouponParams {
pub fn all_billing_controller_schemas() -> Vec<ControllerSchema> {
vec![
+ billing_schemas("billing_get_summary"),
billing_schemas("billing_get_current_plan"),
billing_schemas("billing_get_balance"),
billing_schemas("billing_purchase_plan"),
@@ -85,6 +86,10 @@ pub fn all_billing_controller_schemas() -> Vec<ControllerSchema> {
pub fn all_billing_registered_controllers() -> Vec<RegisteredController> {
vec![
+ RegisteredController {
+ schema: billing_schemas("billing_get_summary"),
+ handler: handle_billing_get_summary,
+ },
RegisteredController {
schema: billing_schemas("billing_get_current_plan"),
handler: handle_billing_get_current_plan,
@@ -150,6 +155,16 @@ pub fn all_billing_registered_controllers() -> Vec<RegisteredController> {
pub fn billing_schemas(function: &str) -> ControllerSchema {
match function {
+ "billing_get_summary" => ControllerSchema {
+ namespace: "billing",
+ function: "get_summary",
+ description: "Fetch credits, plan, and hosted billing dashboard links.",
+ inputs: vec![],
+ outputs: vec![json_output(
+ "summary",
+ "Billing summary payload from backend /payments/summary.",
+ )],
+ },
"billing_get_current_plan" => ControllerSchema {
namespace: "billing",
function: "get_current_plan",
@@ -378,6 +393,13 @@ pub fn billing_schemas(function: &str) -> ControllerSchema {
}
}
+fn handle_billing_get_summary(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(crate::openhuman::hosted::billing::get_summary(&config).await?)
+ })
+}
+
fn handle_billing_get_current_plan(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
diff --git a/src/openhuman/hosted/billing/schemas_tests.rs b/src/openhuman/hosted/billing/schemas_tests.rs
index 80bce2cf1d..206a703b60 100644
--- a/src/openhuman/hosted/billing/schemas_tests.rs
+++ b/src/openhuman/hosted/billing/schemas_tests.rs
@@ -2,15 +2,24 @@ use super::*;
use serde_json::json;
#[test]
-fn all_billing_controller_schemas_returns_15() {
+fn all_billing_controller_schemas_returns_16() {
let schemas = all_billing_controller_schemas();
- assert_eq!(schemas.len(), 15);
+ assert_eq!(schemas.len(), 16);
}
#[test]
-fn all_billing_registered_controllers_returns_15() {
+fn all_billing_registered_controllers_returns_16() {
let controllers = all_billing_registered_controllers();
- assert_eq!(controllers.len(), 15);
+ assert_eq!(controllers.len(), 16);
+}
+
+#[test]
+fn billing_schemas_get_summary() {
+ let s = billing_schemas("billing_get_summary");
+ assert_eq!(s.namespace, "billing");
+ assert_eq!(s.function, "get_summary");
+ assert!(s.inputs.is_empty());
+ assert!(!s.outputs.is_empty());
}
#[test]