Skip to content

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

fix: harden billing summary integration\n\n

Steven Enamakelbd169ce44b35
diff --git a/app/src/components/settings/panels/BillingPanel.test.tsx b/app/src/components/settings/panels/BillingPanel.test.tsx
index ed861267de..80912a6cdd 100644
--- a/app/src/components/settings/panels/BillingPanel.test.tsx
+++ b/app/src/components/settings/panels/BillingPanel.test.tsx
@@ -106,10 +106,46 @@ describe('<BillingPanel />', () => {
render(<BillingPanel />);
expect(await screen.findByText('Summary unavailable')).toBeInTheDocument();
+ expect(screen.getByText('PRO')).toBeInTheDocument();
expect(screen.getByText('$39.50')).toBeInTheDocument();
expect(screen.getByText(/Spent \$6\.00 this cycle/i)).toBeInTheDocument();
});
+ it('renders malformed balances as unavailable and falls back from unusable links', async () => {
+ getSummaryMock.mockResolvedValue({
+ ...summary,
+ credits: {
+ promotionBalanceUsd: Number.NaN,
+ teamTopupUsd: -1,
+ totalUsd: Number.POSITIVE_INFINITY,
+ },
+ links: null,
+ });
+ render(<BillingPanel />);
+
+ await screen.findByText('$39.50');
+ expect(screen.getAllByText('n/a')).toHaveLength(2);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
+ expect(openUrlMock).toHaveBeenNthCalledWith(1, 'https://tinyhumans.ai/dashboard?tab=billing');
+ expect(openUrlMock).toHaveBeenNthCalledWith(2, 'https://tinyhumans.ai/dashboard');
+ });
+
+ it('falls back when the backend returns empty billing links', async () => {
+ getSummaryMock.mockResolvedValue({
+ ...summary,
+ links: { ...summary.links, topUpUrl: '', manageUrl: '' },
+ });
+ render(<BillingPanel />);
+
+ await screen.findByText('$39.50');
+ fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
+ expect(openUrlMock).toHaveBeenNthCalledWith(1, 'https://tinyhumans.ai/dashboard?tab=billing');
+ expect(openUrlMock).toHaveBeenNthCalledWith(2, 'https://tinyhumans.ai/dashboard');
+ });
+
it('keeps plan and balances visible when cycle usage fails', async () => {
getTeamUsageMock.mockRejectedValue(new Error('Usage unavailable'));
render(<BillingPanel />);
diff --git a/app/src/components/settings/panels/BillingPanel.tsx b/app/src/components/settings/panels/BillingPanel.tsx
index 91cc480e8b..1bae81e626 100644
--- a/app/src/components/settings/panels/BillingPanel.tsx
+++ b/app/src/components/settings/panels/BillingPanel.tsx
@@ -14,7 +14,10 @@ import SettingsPanel from '../layout/SettingsPanel';
import InferenceBudget from './billing/InferenceBudget';
const log = createDebug('openhuman:billing:panel');
-const formatUsd = (amount: number): string => `$${amount.toFixed(2)}`;
+const formatUsd = (amount: unknown, unavailable: string): string =>
+ typeof amount === 'number' && Number.isFinite(amount) && amount >= 0
+ ? `$${amount.toFixed(2)}`
+ : unavailable;
const BillingPanel = () => {
const { t } = useT();
@@ -70,8 +73,9 @@ const BillingPanel = () => {
// 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;
+ const unavailable = t('settings.billing.inferenceBudget.notAvailable');
+ const topUpUrl = summary?.links?.topUpUrl || `${BILLING_DASHBOARD_URL}?tab=billing`;
+ const manageUrl = summary?.links?.manageUrl || BILLING_DASHBOARD_URL;
return (
<SettingsPanel>
@@ -88,10 +92,7 @@ const BillingPanel = () => {
<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'))
- }
+ value={summary?.plan?.plan ?? teamUsage?.plan?.plan ?? (loading ? '...' : unavailable)}
/>
<SummaryTile
label={t('settings.billing.payAsYouGo.available')}
@@ -99,28 +100,28 @@ const BillingPanel = () => {
availableUsd === undefined
? loading
? '...'
- : t('settings.billing.inferenceBudget.notAvailable')
- : formatUsd(availableUsd)
+ : unavailable
+ : formatUsd(availableUsd, unavailable)
}
/>
<SummaryTile
label={t('settings.billing.payAsYouGo.promotionalCredits')}
value={
summary
- ? formatUsd(summary.credits.promotionBalanceUsd)
+ ? formatUsd(summary.credits?.promotionBalanceUsd, unavailable)
: loading
? '...'
- : t('settings.billing.inferenceBudget.notAvailable')
+ : unavailable
}
/>
<SummaryTile
label={t('settings.billing.payAsYouGo.topUpBalance')}
value={
summary
- ? formatUsd(summary.credits.teamTopupUsd)
+ ? formatUsd(summary.credits?.teamTopupUsd, unavailable)
: loading
? '...'
- : t('settings.billing.inferenceBudget.notAvailable')
+ : unavailable
}
/>
</div>
diff --git a/gitbooks/features/billing-and-usage.md b/gitbooks/features/billing-and-usage.md
index 64d5447f05..7a44adf32f 100644
--- a/gitbooks/features/billing-and-usage.md
+++ b/gitbooks/features/billing-and-usage.md
@@ -50,7 +50,7 @@ Coupon codes are redeemed against the backend (`POST /coupons/redeem`), and you
### Where billing lives in the app
-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.
+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. Other clients can reach the same hosted billing operations through the authenticated RPC controllers described below; they are not exposed as agent tools.
### RPC surface
diff --git a/src/api/rest.rs b/src/api/rest.rs
index 28c3df850c..17be87e9a4 100644
--- a/src/api/rest.rs
+++ b/src/api/rest.rs
@@ -572,7 +572,6 @@ impl BackendOAuthClient {
path: &str,
body: Option<Value>,
) -> Result<Value> {
- let url = self.url_for(path)?;
let sdk = self
.sdk
.clone()
@@ -581,6 +580,27 @@ impl BackendOAuthClient {
.raw()
.send(method.clone(), path, &[], body.as_ref(), true)
.await;
+ self.finish_authed_json(method, path, response)
+ }
+
+ /// Fetch the deployed billing summary through the SDK's typed payments API.
+ pub async fn fetch_billing_summary(&self, bearer_jwt: &str) -> Result<Value> {
+ const PATH: &str = "/payments/summary";
+ let sdk = self
+ .sdk
+ .clone()
+ .with_token(Some(bearer_jwt.trim().to_string()));
+ let response = sdk.payments().get_summary().await.map(|value| value.0);
+ self.finish_authed_json(Method::GET, PATH, response)
+ }
+
+ fn finish_authed_json(
+ &self,
+ method: Method,
+ path: &str,
+ response: Result<Value, SdkError>,
+ ) -> Result<Value> {
+ let url = self.url_for(path)?;
let value = match response {
Ok(value) => return parse_api_response_value(value),
Err(SdkError::Http(e)) => {
diff --git a/src/api/rest_tests.rs b/src/api/rest_tests.rs
index 6f6fe4ae44..e4e8326071 100644
--- a/src/api/rest_tests.rs
+++ b/src/api/rest_tests.rs
@@ -1238,6 +1238,56 @@ async fn channel_delete_404_still_means_the_message_is_gone() {
// change its Sentry or session-expiry behaviour just because it moved onto a
// typed SDK method. These pin that equivalence.
+#[tokio::test]
+async fn sdk_backed_billing_summary_unwraps_data() {
+ let app = Router::new().route(
+ "/payments/summary",
+ get(|| async {
+ Json(json!({
+ "success": true,
+ "data": {
+ "credits": { "totalUsd": 12.5 },
+ "plan": { "plan": "PRO" },
+ "links": { "manageUrl": "https://tinyhumans.ai/dashboard" }
+ }
+ }))
+ }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let client = BackendOAuthClient::new(&format!("http://{addr}")).unwrap();
+ let summary = client.fetch_billing_summary("mock-jwt").await.unwrap();
+
+ assert_eq!(summary["credits"]["totalUsd"], 12.5);
+ assert_eq!(summary["plan"]["plan"], "PRO");
+}
+
+#[tokio::test]
+async fn sdk_backed_billing_summary_surfaces_unauthorized_on_401() {
+ let app = Router::new().route(
+ "/payments/summary",
+ get(|| async { (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized") }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+
+ let client = BackendOAuthClient::new(&format!("http://{addr}")).unwrap();
+ let err = client.fetch_billing_summary("mock-jwt").await.unwrap_err();
+
+ assert!(matches!(
+ err.downcast_ref::<BackendApiError>(),
+ Some(BackendApiError::Unauthorized { method, path })
+ if method == "GET" && path == "/payments/summary"
+ ));
+}
+
#[tokio::test]
async fn sdk_backed_channel_delete_surfaces_message_not_found_on_404() {
let app = Router::new().route(
diff --git a/src/openhuman/hosted/billing/ops.rs b/src/openhuman/hosted/billing/ops.rs
index 3f01bb5b39..865cb38486 100644
--- a/src/openhuman/hosted/billing/ops.rs
+++ b/src/openhuman/hosted/billing/ops.rs
@@ -54,7 +54,13 @@ 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?;
+ let token = require_token(config)?;
+ let api_url = effective_backend_api_url(&config.api_url);
+ let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
+ let data = client
+ .fetch_billing_summary(&token)
+ .await
+ .map_err(crate::api::flatten_authed_error)?;
Ok(RpcOutcome::single_log(data, "billing summary fetched"))
}
diff --git a/vendor/tinyhumans-sdk b/vendor/tinyhumans-sdk
index d0afa1ce1e..5b44a33359 160000
--- a/vendor/tinyhumans-sdk
+++ b/vendor/tinyhumans-sdk
@@ -1 +1 @@
-Subproject commit d0afa1ce1ee8b5e15cd4a4b1a5f0ab094114de19
+Subproject commit 5b44a333593372004b31cf5da6b67443ddec9ad1