Spend alert
Budget and spend alert settings card with an editable monthly budget, draggable alert threshold on the live spend and forecast bar, Email, Slack, and PagerDuty switches, a 100% hard stop, and a live Slack message preview.
import { SpendAlert } from '@uthereal/ui/spend-alert'Spend alert playground
Spend alerts
- Emailfinance@acme.com
- Slack#eng-spend
- PagerDutyPlatform on-call at 100%
Overview
SpendAlert provides a single billing settings card for metered products. Readers edit their Monthly budget inline, drag the alert threshold thumb directly across the live spend and forecast bar (snapping to configurable markers), toggle Email, Slack, and PagerDuty notifications, optionally enable a Hard stop at 100%, and inspect a live Slack preview of the exact message posted when spend crosses the line.
Pressing Save or Send test forwards the current SpendAlertSettings snapshot and an AbortSignal to your handlers (or simulates both locally when handlers are omitted, announcing the simulation in a polite live region). Changing any setting resets saved/tested/error banners back to Unsaved changes while keeping card height fixed.
Use SpendAlert on billing and usage settings pages for AI API spend, compute budgets, and metered overage guards. For estimating model token costs before setting a budget, use LLM cost calculator. For prompting an upgrade when a workspace hits a plan cap, use Upgrade prompt.
Usage
'use client'
import { SpendAlert } from '@uthereal/ui/spend-alert'
export function BillingAlerts({ spend }: { spend: number }) {
return (
<SpendAlert
project="Production"
scope="Model API usage"
spend={spend}
defaultValue={{ budget: 5000, threshold: 80 }}
destinations={{
email: 'finance@acme.com',
slack: '#eng-spend',
pagerduty: 'Platform on-call',
}}
onSave={async (settings, signal) => {
const res = await fetch('/api/billing/spend-alerts', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(settings),
signal,
})
if (!res.ok) throw new Error('Save failed')
}}
onSendTest={async (settings, signal) => {
const res = await fetch('/api/billing/spend-alerts/test', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(settings),
signal,
})
if (!res.ok) throw new Error('Test send failed')
}}
/>
)
}Omit onSave or onSendTest to run built-in local simulations (700ms save, 900ms test send with a preview wash) that explicitly announce "Simulated, nothing was stored." or "Simulated, nothing was sent." in the footer live region.
Examples
Hard stop with Slack disabled
Set threshold: 100, hardStop: true, and channels.slack: false to show a strict staging cap where PagerDuty pages at 100%, requests pause until the reset date, and the Slack preview crossfades to its disabled placeholder without resizing the card.
Spend alerts
- Emailops@acme.com
- Slack#staging-alerts
- PagerDutyStaging on-call at 100%
Over-budget European workspace
Configure currency="EUR", locale="de-DE", custom markers, and spend above defaultValue.budget to demonstrate the danger Over budget status, warning helper copy, danger spend bar fill, and locale-aware currency parsing and formatting.
Spend alerts
- Emailfinops@nordlicht.de
- Slack#eu-spend
- PagerDutyEU Platform at 100%
Threshold bar and delivery preview
Header and budget states
| Condition | Header status | Bar fill and helper feedback |
|---|---|---|
budget === 0 | No budget set (muted) | Slider disabled; field turns invalid (Enter a budget above $0). |
spend >= budget | Over budget (danger) | Full spend bar shifts to danger; helper shows exact overage amount. |
spend >= alertAt | Past {threshold}% (warning) | Portion of spend past the threshold thumb fills in warning tone. |
forecast >= alertAt | Hits {threshold}% {short} {d} | Projects crossing day from daily spend rate; forecast bar stays visible. |
| Below alert threshold | On track (success) | Solid spend fill and lighter forecast fill; helper shows period reset. |
Live Slack preview
- Turning Slack off crossfades the preview box to
"Turn on Slack to preview this alert"in the same container so nothing reflows. - Raising the threshold to
100%shifts the preview accent stripe and headline icon from warning to danger, appends PagerDuty when enabled, and appendsBlocked until {resetsOn}when Hard stop at 100% is enabled. - A successful Send test updates the preview timestamp to
Just nowand plays a one-shot accent wash across the preview box.
API reference
These serializable arguments and defaults come directly from the component schema.
| Argument | Type / default | Description |
|---|---|---|
title | stringDefault: "Spend alerts" | Card heading and accessible region name. |
project | stringDefault: "Production" | Project or workspace the budget applies to, shown in the subtitle and the Slack message. |
scope | stringDefault: "Model API usage" | What is being metered, shown in the subtitle. |
spend | numberDefault: 3412.8 | Spend so far this period, drawn as the solid fill on the bar. |
forecast | number— | Projected spend at period end, drawn as the lighter fill. Defaults to a linear projection from spend and period. |
period | SpendAlertPeriod— | Billing period for the forecast, the crossing date and the reset copy. |
currency | stringDefault: "USD" | ISO 4217 currency code for formatting. |
defaultValue | SpendAlertSettings— | Initial settings: budget, threshold, channels and hard stop. Missing fields fall back to the demo defaults. Edits do not reset a mounted instance. |
markers | number[]Default: [50,80,100] | Threshold markers on the bar. The thumb snaps to them within 2% while dragging, and PageUp or PageDown jumps between them. |
destinations | SpendAlertDestinations— | Where each channel delivers. PagerDuty pages only at 100%. |
appName | stringDefault: "Acme Billing" | Sender name in the Slack preview. |
lastSaved | stringDefault: "Last edited Oct 24 by Maya Chen" | Footer copy while nothing has changed. |
saveAction | string— | Registered host action requested when Save is pressed. |
testAction | string— | Registered host action requested when Send test is pressed. |
locale | string— | BCP 47 locale for currency and number formatting. Omitted inherits the application locale, else en-US. |
recipe | studio | softDefault: "studio" | Visual treatment. Both recipes preserve interaction behavior. |
theme | SpendAlertThemeDefault: {} | Color mode, accent, and typed semantic token overrides. |
motion | none | subtle | expressiveDefault: "subtle" | Animation preset. System reduced-motion preferences take precedence. |
motionOptions | SpendAlertMotionOptionsDefault: {} | Crossfade, fill, thumb and wash timing overrides in milliseconds. |
dir | ltr | rtl— | Reading direction; inherited from the page when omitted. |
SpendAlertPeriodaccepts{ label, short, day, days, resetsOn }.SpendAlertSettingsaccepts{ budget, threshold, channels: { email, slack, pagerduty }, hardStop }.SpendAlertDestinationsaccepts{ email, slack, pagerduty }.
React integration
| Prop | Purpose |
|---|---|
onChange(settings) | Called with the full SpendAlertSettings object after every edit (never on initial mount). |
onSave(settings, signal) | Persists settings asynchronously; reject to enter the inline error state. Superseded calls abort signal. |
onSendTest(settings, signal) | Sends a test alert to enabled channels; reject to show an error. Omit to simulate locally with a preview wash. |
onAction(action) | Called with saveAction when Save is pressed or testAction when Send test is pressed. |
preset | Application defaults overridden by explicit instance arguments. |
tokens | CSS variables applied after the typed theme, forwarded to the root card, switches, and footer buttons. |
ref, className, style | Applied to the root <section> element. |
| Native attributes | id, aria-*, data-*, and remaining <section> props forwarded to the root element. |
Keyboard & accessibility
| Key | Action |
|---|---|
ArrowUp / ArrowDown | In Monthly budget, nudges budget by ±100 (Shift for ±1,000). On slider, steps by 1%. |
ArrowLeft / ArrowRight | On the threshold slider, moves the alert line by 1% (Shift for 10%; respects RTL). |
PageUp / PageDown | Jumps the threshold thumb to the next or previous configured marker. |
Home / End | Sets the threshold to the minimum (10%) or maximum (100%). |
Space | Toggles the focused channel Switch or Hard stop at 100%. |
Tab | Moves across Monthly budget, threshold slider, channel switches, hard stop, Send test, and Save. |
- The root
<section>is named by its heading (aria-labelledby). The budget<input>carriesaria-invalidwhen zero and links to its dynamic helper line viaaria-describedby. - The threshold thumb exposes
role="slider"witharia-valuemin={10},aria-valuemax={100},aria-valuenow, and speakingaria-valuetext("80%, $4,000"). Clicking or dragging the rail focuses the thumb without scrolling;touch-action: pan-ypreserves vertical touch scrolling. - Every status indicator pairs a semantic icon (
circle-check,triangle-alert, orcircle-dashed) with a text label rather than relying on color alone. - The footer status slot is a pre-mounted polite
role="status"live region announcing save progress, completion, test deliveries (including simulated-mode disclaimers), and failures. - Container queries adapt the card below
440pxby tightening padding, stacking channel destinations under their labels, hiding the legend percentage pill, and expanding footer actions to equal widths. Full RTL (dir="rtl") mirrors both slider geometry andclip-pathfills.
Motion & theming
The spend and forecast fills draw in once when the card enters the viewport (720ms enter ease), then follow subsequent budget edits in 160ms. The threshold thumb tracks pointers 1:1 during drag (snapping within 2% of markers) and glides 160ms on clicks, marker jumps, and keyboard steps. Header status, budget helper, hard-stop copy, and footer status crossfade in fixed single-cell grids so card height never shifts.
Under prefers-reduced-motion: reduce, fill draw-in, glides, and transitions turn off, crossfades shorten to 120ms opacity fades, and the test-send preview wash drops to 400ms. Setting motion="none" makes every transition and animation immediate (0ms).
theme accepts mode, accent, and typed tokens across these groups:
| Token group | CSS custom properties |
|---|---|
core | --ui-surface, --ui-surface-raised, --ui-text, --ui-text-secondary, --ui-muted, --ui-border, --ui-highlight, --ui-accent, --ui-accent-foreground, --ui-danger, --ui-focus-ring, --ui-radius, --ui-border-width, --ui-shadow, --ui-disabled-opacity, --ui-font, --ui-font-size, --ui-font-weight |
extended | --ui-surface-sunken, --ui-border-strong, --ui-border-subtle, --ui-track, --ui-info, --ui-success, --ui-warning, --ui-tone-foreground, --ui-overlay, --ui-tint-strength |
shape | --ui-radius-sm, --ui-popup-radius, --ui-surface-radius |
accentTones | --ui-accent-strong, --ui-accent-subtle |
selectionControl | --ui-control-on, --ui-control-glyph, --ui-control-track-hover, --ui-control-thumb, --ui-control-thumb-on, --ui-control-fill, --ui-shadow-thumb |
include | --ui-font-mono |
An application-wide UtherealProvider supplies defaults.
Composition
In an agent composition, SpendAlert is a leaf block. Pass spend, period, and destinations from your usage API, keep markers to at most six unique percents (1–100), and wire saveAction and testAction to registered host actions. See Building with agents.
{
"type": "SpendAlert",
"props": {
"project": "Production",
"scope": "Model API usage",
"spend": 3412.8,
"defaultValue": {
"budget": 5000,
"threshold": 80,
"channels": {
"email": true,
"slack": true,
"pagerduty": false
},
"hardStop": false
},
"saveAction": "save_spend_alert",
"testAction": "send_spend_alert_test"
},
"children": []
}