AI Usage
What a run cost: a receipt with tokens, time and price, a live cost ticker, and usage bars against a plan limit.
"use client"
import * as React from "react"
import { CalendarClock } from "lucide-react"
import {
AiKitStyles,
AiStyle,
cx,
Pill,
Roll,
type AiStatus,
} from "@/lib/ai-kit"
const CSS = `
.aik-us-rcptw{position:relative;width:min(100%,320px);filter:drop-shadow(0 0 .75px var(--aik-line-3)) drop-shadow(0 12px 22px rgb(12 12 24 / 12%))}
.dark .aik-us-rcptw,.aik-us-rcptw.dark{filter:drop-shadow(0 0 .75px var(--aik-line-3)) drop-shadow(0 14px 26px rgb(0 0 0 / 55%))}
.dark .aik-light .aik-us-rcptw{filter:drop-shadow(0 0 .75px var(--aik-line-3)) drop-shadow(0 12px 22px rgb(12 12 24 / 12%))}
.aik-us-rcpt{display:grid;gap:12px;padding:18px 18px 24px;border-radius:14px 14px 0 0;background:var(--aik-card);
-webkit-mask:linear-gradient(#000,#000) top/100% calc(100% - 6px) no-repeat,radial-gradient(4.5px at 50% 100%,#0000 96%,#000) bottom left/13px 6px repeat-x;
mask:linear-gradient(#000,#000) top/100% calc(100% - 6px) no-repeat,radial-gradient(4.5px at 50% 100%,#0000 96%,#000) bottom left/13px 6px repeat-x}
.aik-us-rhead{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
.aik-us-rhead b{font:500 11px/14px var(--aik-mono);letter-spacing:.08em;text-transform:uppercase}
.aik-us-rhead span{font:11.5px/14px var(--aik-mono);color:var(--aik-text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
.aik-us-rule{height:0;border-top:1px dashed var(--aik-line-3)}
.aik-us-lines{display:grid;gap:7px}
.aik-us-lines li,.aik-us-sum div{display:flex;align-items:baseline;gap:6px;font-size:13px;line-height:18px;min-width:0}
.aik-us-lines li{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both;animation-delay:calc(min(var(--i,0),8)*var(--aik-stagger))}
.aik-us-lines li > span,.aik-us-sum span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-us-lines li > i,.aik-us-sum i{flex:1;min-width:12px;height:0;border-bottom:1px dotted var(--aik-line-3);transform:translateY(-4px)}
.aik-us-lines em{font:11.5px/18px var(--aik-mono);font-style:normal;color:var(--aik-text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
.aik-us-lines b,.aik-us-sum b{font:12.5px/18px var(--aik-mono);font-weight:400;font-variant-numeric:tabular-nums;white-space:nowrap;min-width:52px;text-align:right}
.aik-us-sum{display:grid;gap:5px;color:var(--aik-text-2)}
.aik-us-total{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
.aik-us-total span{font:500 11px/14px var(--aik-mono);letter-spacing:.08em;text-transform:uppercase;color:var(--aik-text-2)}
.aik-us-total b{font:600 24px/28px var(--aik-mono);letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.aik-us-code{height:20px;opacity:.82;background:repeating-linear-gradient(90deg,var(--aik-text) 0 2px,transparent 2px 4px,var(--aik-text) 4px 5px,transparent 5px 8px,var(--aik-text) 8px 11px,transparent 11px 13px,var(--aik-text) 13px 14px,transparent 14px 18px)}
.aik-us-stamp{position:absolute;left:50%;bottom:58px;margin-left:-34px;padding:3px 9px;border-radius:7px;border:2px solid var(--aik-c);color:var(--aik-c);font:600 12px/16px var(--aik-mono);letter-spacing:.14em;text-transform:uppercase;
transform:rotate(-9deg);opacity:.92;background:color-mix(in oklab,var(--aik-c) 8%,var(--aik-card));animation:aik-us-stamp var(--aik-d-enter) var(--aik-ease-in) both}
@keyframes aik-us-stamp{from{opacity:0;transform:rotate(-9deg) scale(1.7)}}
.aik-us-empty{color:var(--aik-text-3);font-size:13px}
.aik-us-tick{display:grid;justify-items:center;gap:12px;width:min(100%,320px);text-align:center}
.aik-us-tlabel{font:500 11px/14px var(--aik-mono);letter-spacing:.08em;text-transform:uppercase;color:var(--aik-text-3)}
.aik-us-fig{display:flex;align-items:baseline;justify-content:center;font:600 46px/1 var(--aik-mono);letter-spacing:-.04em;font-variant-numeric:tabular-nums;max-width:100%}
.aik-us-fig > small{font-size:24px;font-weight:500;color:var(--aik-text-3);margin-right:3px;letter-spacing:0}
.aik-us-col{display:inline-block;block-size:1em;overflow:hidden}
.aik-us-strip{display:grid;transform:translateY(calc(var(--d)*-1em));transition:transform var(--aik-d-state) var(--aik-ease-out)}
.aik-us-strip span{display:block;block-size:1em;line-height:1}
.aik-us-tmeta{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;font:12px/16px var(--aik-mono);color:var(--aik-text-2);font-variant-numeric:tabular-nums}
@container (max-width:300px){.aik-us-fig{font-size:38px}}
.aik-us-plan{display:grid;gap:16px;width:min(100%,380px);padding:16px;border-radius:16px;background:var(--aik-card);box-shadow:var(--aik-sh-card)}
.aik-us-phead{display:flex;align-items:center;gap:10px;min-width:0}
.aik-us-phead > div{display:grid;flex:1;min-width:0}
.aik-us-phead b{font-weight:600;font-size:14px;line-height:20px}
.aik-us-phead span{display:inline-flex;align-items:center;gap:5px;font-size:12.5px;line-height:17px;color:var(--aik-text-2)}
.aik-us-phead svg{color:var(--aik-text-3)}
.aik-us-rows{display:grid;gap:14px}
.aik-us-row{display:grid;gap:7px}
.aik-us-rtop{display:flex;align-items:baseline;justify-content:space-between;gap:10px;font-size:13px;line-height:18px}
.aik-us-rtop span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-us-rtop b{font:12px/18px var(--aik-mono);font-weight:400;color:var(--aik-text-2);font-variant-numeric:tabular-nums;white-space:nowrap}
.aik-us-rtop b strong{font-weight:500;color:var(--aik-text)}
.aik-us-bar{position:relative;height:6px;border-radius:3px;background:var(--aik-line-2);overflow:hidden}
.aik-us-bar i{position:absolute;inset:0;border-radius:3px;background:var(--aik-text);transform:scaleX(var(--p,0));transform-origin:0 50%;transition:transform var(--aik-d-move) var(--aik-ease-out),background var(--aik-d-state)}
.aik-us-row[data-lvl="warn"] .aik-us-bar i{background:var(--aik-amber-fill)}
.aik-us-row[data-lvl="over"] .aik-us-bar i{background:var(--aik-red)}
.aik-us-row[data-lvl="warn"] .aik-us-rtop b strong{color:var(--aik-amber)}
.aik-us-row[data-lvl="over"] .aik-us-rtop b strong{color:var(--aik-red)}
.aik-us-over{font-size:12px;line-height:16px;color:var(--aik-red);font-weight:500;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
@media (prefers-reduced-motion: reduce){.aik-us-stamp,.aik-us-lines li,.aik-us-over{animation:none}.aik-us-strip{transition:none}}
`
/** 1234 becomes "1.2k", 124000 becomes "124k". */
function compact(value: number) {
const abs = Math.abs(value)
if (abs >= 1_000_000) return `${+(value / 1_000_000).toFixed(1)}M`
if (abs >= 10_000) return `${Math.round(value / 1000)}k`
if (abs >= 1000) return `${+(value / 1000).toFixed(1)}k`
return String(Math.round(value))
}
const money = (value: number, currency: string) =>
`${currency}${value.toFixed(Math.abs(value) < 0.1 ? 3 : 2)}`
export interface AiReceiptLine {
id: string
/** The step, such as "Write the pricing section". */
label: string
/** Tokens the step used. */
tokens?: number
/** What the step cost. */
cost: number
}
export interface AiRunReceiptProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"title"
> {
title?: string
/** A short id or timestamp at the top right. */
reference?: string
/** One row per step, in order. */
lines: AiReceiptLine[]
tokensIn?: number
tokensOut?: number
/** Total run time, already formatted. */
duration?: string
/** Defaults to the sum of the lines. */
total?: number
currency?: string
/** `done` and `fail` stamp the receipt. Other values leave it unstamped. */
status?: AiStatus
/** Overrides the stamp's word. */
stamp?: string
}
/** What a run cost, as a receipt: a line per step, tokens, time and a stamped total. */
export function AiRunReceipt({
title = "Run receipt",
reference,
lines,
tokensIn,
tokensOut,
duration,
total,
currency = "$",
status,
stamp,
className,
...rest
}: AiRunReceiptProps) {
const sum = total ?? lines.reduce((value, line) => value + line.cost, 0)
const stamped = status === "done" || status === "fail"
return (
<div {...rest} className={cx("aik aik-us-rcptw", className)}>
<AiKitStyles />
<AiStyle id="ai-usage" css={CSS} />
<div className="aik-us-rcpt">
<div className="aik-us-rhead">
<b>{title}</b>
{reference ? <span>{reference}</span> : null}
</div>
<div className="aik-us-rule" />
{lines.length === 0 ? (
<p className="aik-us-empty">No steps have run yet.</p>
) : (
<ul className="aik-us-lines">
{lines.map((line, index) => (
<li key={line.id} style={{ "--i": index } as React.CSSProperties}>
<span>{line.label}</span>
<i />
{line.tokens === undefined ? null : (
<em>{compact(line.tokens)}</em>
)}
<b>{money(line.cost, currency)}</b>
</li>
))}
</ul>
)}
<div className="aik-us-rule" />
<div className="aik-us-sum">
{tokensIn === undefined ? null : (
<div>
<span>Tokens in</span>
<i />
<b>{compact(tokensIn)}</b>
</div>
)}
{tokensOut === undefined ? null : (
<div>
<span>Tokens out</span>
<i />
<b>{compact(tokensOut)}</b>
</div>
)}
{duration ? (
<div>
<span>Time</span>
<i />
<b>{duration}</b>
</div>
) : null}
</div>
<div className="aik-us-total">
<span>Total</span>
<b>{money(sum, currency)}</b>
</div>
<div className="aik-us-code" aria-hidden="true" />
</div>
{stamped ? (
<span className="aik-us-stamp" data-s={status} role="status">
{stamp ?? (status === "done" ? "Done" : "Failed")}
</span>
) : null}
</div>
)
}
export interface AiCostTickerProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The running figure. */
value: number
/** Digits after the decimal point. */
decimals?: number
/** Shown small before the figure. */
prefix?: string
/** A small caption above the figure. */
label?: string
/** A pill under the figure, in the kit's status language. */
status?: AiStatus
/** The pill's text. Rolls over when it changes. */
statusLabel?: string
/** Extra mono details beside the pill, such as a rate or a token count. */
meta?: string
}
const DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
/** A live figure whose digits roll, column by column, as the cost climbs. */
export function AiCostTicker({
value,
decimals = 2,
prefix = "$",
label,
status,
statusLabel,
meta,
className,
...rest
}: AiCostTickerProps) {
const text = Math.max(value, 0).toFixed(Math.max(0, decimals))
const chars = text.split("")
return (
<div {...rest} className={cx("aik aik-us-tick", className)}>
<AiKitStyles />
<AiStyle id="ai-usage" css={CSS} />
{label ? <span className="aik-us-tlabel">{label}</span> : null}
<div className="aik-us-fig" role="img" aria-label={`${prefix}${text}`}>
{prefix ? <small aria-hidden="true">{prefix}</small> : null}
{chars.map((char, index) => {
// Key from the right so a digit keeps its column when the figure grows.
const key = chars.length - index
return /\d/.test(char) ? (
<span key={key} className="aik-us-col" aria-hidden="true">
<span
className="aik-us-strip"
style={{ "--d": Number(char) } as React.CSSProperties}
>
{DIGITS.map((digit) => (
<span key={digit}>{digit}</span>
))}
</span>
</span>
) : (
<span key={key} aria-hidden="true">
{char}
</span>
)
})}
</div>
{statusLabel || meta ? (
<div className="aik-us-tmeta">
{statusLabel ? (
<Pill status={status}>
<Roll>{statusLabel}</Roll>
</Pill>
) : null}
{meta ? <span>{meta}</span> : null}
</div>
) : null}
</div>
)
}
export interface AiUsageItem {
id: string
/** What is being counted, such as "Agent runs". */
label: string
used: number
limit: number
/** A word after the figures, such as "runs". */
unit?: string
}
export interface AiUsageBarsProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"title"
> {
/** The plan's name. */
title: string
/** When the counters reset, already worded: "Resets 1 Dec". */
resetLabel?: string
items: AiUsageItem[]
/** Share of a limit (0 to 1) where a bar turns amber. */
warnAt?: number
/** Shows a button in the header. */
onUpgrade?: () => void
upgradeLabel?: string
}
/** Usage against a plan's limits, with a reset date. Bars go amber near a limit and red past it. */
export function AiUsageBars({
title,
resetLabel,
items,
warnAt = 0.8,
onUpgrade,
upgradeLabel = "Upgrade",
className,
...rest
}: AiUsageBarsProps) {
return (
<div {...rest} className={cx("aik aik-us-plan", className)}>
<AiKitStyles />
<AiStyle id="ai-usage" css={CSS} />
<div className="aik-us-phead">
<div>
<b>{title}</b>
{resetLabel ? (
<span>
<CalendarClock size={13} />
{resetLabel}
</span>
) : null}
</div>
{onUpgrade ? (
<button type="button" className="aik-btn sm pri" onClick={onUpgrade}>
{upgradeLabel}
</button>
) : null}
</div>
{items.length === 0 ? (
<p className="aik-us-empty">No usage recorded this period.</p>
) : (
<div className="aik-us-rows">
{items.map((item) => {
const ratio =
item.limit > 0 ? Math.max(item.used, 0) / item.limit : 0
const level = ratio > 1 ? "over" : ratio >= warnAt ? "warn" : "ok"
return (
<div key={item.id} className="aik-us-row" data-lvl={level}>
<div className="aik-us-rtop">
<span>{item.label}</span>
<b>
<strong>{compact(item.used)}</strong> /{" "}
{compact(item.limit)}
{item.unit ? ` ${item.unit}` : ""}
</b>
</div>
<div
className="aik-us-bar"
role="meter"
aria-label={item.label}
aria-valuemin={0}
aria-valuemax={item.limit}
aria-valuenow={Math.min(Math.max(item.used, 0), item.limit)}
aria-valuetext={`${compact(item.used)} of ${compact(item.limit)}${item.unit ? ` ${item.unit}` : ""}`}
>
<i
style={{ "--p": Math.min(1, ratio) } as React.CSSProperties}
/>
</div>
{level === "over" ? (
<span className="aik-us-over">
Over by {compact(item.used - item.limit)}
{item.unit ? ` ${item.unit}` : ""}
</span>
) : null}
</div>
)
})}
</div>
)}
</div>
)
}
Installation
One command adds ai-usage and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.
$npx shadcn@latest add https://tweenui.dev/r/ai-usage.json
ai-usage-demo
"use client"
import * as React from "react"
import { AiDemo } from "@/lib/ai-demo"
import { useAiLoop, type AiStatus } from "@/lib/ai-kit"
import {
AiCostTicker,
AiRunReceipt,
AiUsageBars,
type AiReceiptLine,
type AiUsageItem,
} from "@/registry/tween/ai-usage"
const LINES: AiReceiptLine[] = [
{ id: "read", label: "Read the hero section", tokens: 4200, cost: 0.013 },
{ id: "find", label: "Find text-skew-reveal", tokens: 1800, cost: 0.006 },
{
id: "write",
label: "Write the pricing section",
tokens: 21400,
cost: 0.094,
},
{ id: "check", label: "Run the type check", tokens: 2600, cost: 0.008 },
{ id: "build", label: "Rebuild the registry", tokens: 3100, cost: 0.011 },
]
function Receipt() {
const root = React.useRef<HTMLDivElement>(null)
const [count, setCount] = React.useState(LINES.length)
const [status, setStatus] = React.useState<AiStatus>("done")
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setStatus("run")
setCount(0)
await sleep(600)
for (let shown = 1; shown <= LINES.length; shown++) {
setCount(shown)
await sleep(650)
}
await sleep(500)
setStatus("done")
await sleep(2600)
},
{
gap: 400,
enabled: !hands,
still: () => {
setCount(LINES.length)
setStatus("done")
},
}
)
const lines = LINES.slice(0, count)
const tokens = lines.reduce((sum, line) => sum + (line.tokens ?? 0), 0)
return (
<div
ref={root}
style={{ display: "grid", justifyItems: "center", width: "100%" }}
onPointerDown={() => {
setHands(true)
setCount(LINES.length)
setStatus((current) => (current === "done" ? "fail" : "done"))
}}
>
<AiRunReceipt
reference="#482 · 20 Nov"
lines={lines}
tokensIn={Math.round(tokens * 0.86)}
tokensOut={Math.round(tokens * 0.14)}
duration={`0:${String(count * 9).padStart(2, "0")}`}
status={status}
/>
</div>
)
}
const PHASES: Array<[string, AiStatus, number]> = [
["Reading files", "run", 6],
["Writing the section", "run", 14],
["Waiting for you", "ask", 5],
["Running the checks", "run", 8],
]
function Ticker() {
const root = React.useRef<HTMLDivElement>(null)
const [cents, setCents] = React.useState(1320)
const [label, setLabel] = React.useState("Writing the section")
const [status, setStatus] = React.useState<AiStatus>("run")
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
let total = 0
setCents(0)
for (const [name, phase, ticks] of PHASES) {
setLabel(name)
setStatus(phase)
for (let tick = 0; tick < ticks; tick++) {
if (phase === "run") {
total += 37 + ((tick * 23) % 41)
setCents(total)
}
await sleep(260)
}
}
setLabel("Run finished")
setStatus("done")
await sleep(2000)
},
{ gap: 500, enabled: !hands }
)
return (
<div
ref={root}
style={{ display: "grid", justifyItems: "center", width: "100%" }}
onPointerDown={() => {
setHands(true)
setStatus("run")
setLabel("Added by hand")
setCents((current) => current + 137)
}}
>
<AiCostTicker
label="This run"
value={cents / 10000}
decimals={3}
status={status}
statusLabel={label}
meta={`${(cents * 0.021).toFixed(1)}k tokens`}
/>
</div>
)
}
const PLAN_STEPS: Array<[number, number, number]> = [
[212, 1.4, 3],
[318, 2.6, 5],
[431, 3.9, 7],
[486, 4.7, 9],
[512, 5.2, 10],
]
function Plan() {
const root = React.useRef<HTMLDivElement>(null)
const [at, setAt] = React.useState(3)
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
for (let index = 0; index < PLAN_STEPS.length; index++) {
setAt(index)
await sleep(index === PLAN_STEPS.length - 1 ? 2400 : 1500)
}
},
{ gap: 500, enabled: !hands, still: () => setAt(3) }
)
const [runs, tokens, seats] = PLAN_STEPS[at] ?? PLAN_STEPS[0]!
const items: AiUsageItem[] = [
{ id: "runs", label: "Agent runs", used: runs, limit: 500, unit: "runs" },
{
id: "tokens",
label: "Tokens",
used: tokens * 1_000_000,
limit: 6_000_000,
},
{ id: "seats", label: "Seats", used: seats, limit: 10 },
]
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 380px)" }}
onPointerDown={() => setHands(true)}
>
<AiUsageBars
title="Pro plan"
resetLabel="Resets 1 Dec"
items={items}
onUpgrade={() => setAt(0)}
/>
</div>
)
}
export function AiUsageDemo({ only }: { only?: string }) {
return (
<AiDemo
only={only}
tabs={[
{ name: "Receipt", node: <Receipt /> },
{ name: "Ticker", node: <Ticker /> },
{ name: "Plan", node: <Plan /> },
]}
/>
)
}
Installation
Usage
import {
AiCostTicker,
AiRunReceipt,
AiUsageBars,
} from "@/components/ui/ai-usage"<AiRunReceipt
reference="#482"
status="done"
duration="0:45"
tokensIn={28_400}
tokensOut={4_700}
lines={[
{ id: "read", label: "Read the hero section", tokens: 4200, cost: 0.013 },
{ id: "write", label: "Write the pricing section", tokens: 21400, cost: 0.094 },
]}
/>
<AiCostTicker label="This run" value={cost} decimals={3} status="run" statusLabel="Writing" />
<AiUsageBars
title="Pro plan"
resetLabel="Resets 1 Dec"
items={[{ id: "runs", label: "Agent runs", used: 431, limit: 500, unit: "runs" }]}
/>Versions
AiRunReceiptprints a run as a receipt: a line per step with dotted leaders, tokens, time, a total, and a perforated edge.status="done"or"fail"stamps it.AiCostTickeris a live figure. Each digit sits in its own column and rolls to the next value, so a climbing cost reads as motion and not as flicker.AiUsageBarsshows counters against a plan's limits. A bar turns amber atwarnAtand red past the limit, where it also says by how much.
Props
AiRunReceipt
| Prop | Type | Default | Description |
|---|---|---|---|
lines | { id, label, tokens?, cost }[] | One row per step. | |
total | number | sum of lines | The amount on the total row. |
tokensIn | number | Input tokens for the run. | |
tokensOut | number | Output tokens for the run. | |
duration | string | Run time, already formatted. | |
reference | string | A short id or date at the top right. | |
status | "todo" | "run" | "ask" | "done" | "fail" | done and fail stamp the receipt. | |
stamp | string | Overrides the stamp's word. | |
currency | string | "$" | Shown before every amount. |
title | string | "Run receipt" | The heading. |
AiCostTicker
| Prop | Type | Default | Description |
|---|---|---|---|
value | number | The running figure. | |
decimals | number | 2 | Digits after the decimal point. |
prefix | string | "$" | Shown small before the figure. |
label | string | A caption above the figure. | |
status | status | Colours the pill under the figure. | |
statusLabel | string | The pill's text. | |
meta | string | Extra mono detail, such as a token count. |
AiUsageBars
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | The plan's name. | |
items | { id, label, used, limit, unit? }[] | One bar each. | |
resetLabel | string | When the counters reset. | |
warnAt | number | 0.8 | Share of a limit where a bar turns amber. |
onUpgrade | () => void | Shows a button in the header. | |
upgradeLabel | string | "Upgrade" | The button's label. |