AI Usage

What a run cost: a receipt with tokens, time and price, a live cost ticker, and usage bars against a plan limit.

Installation

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
components/ui/ai-usage-demo.tsx
"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

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-usage.json

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

  • AiRunReceipt prints 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.
  • AiCostTicker is 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.
  • AiUsageBars shows counters against a plan's limits. A bar turns amber at warnAt and red past the limit, where it also says by how much.

Props

AiRunReceipt

PropTypeDefaultDescription
lines{ id, label, tokens?, cost }[]One row per step.
totalnumbersum of linesThe amount on the total row.
tokensInnumberInput tokens for the run.
tokensOutnumberOutput tokens for the run.
durationstringRun time, already formatted.
referencestringA short id or date at the top right.
status"todo" | "run" | "ask" | "done" | "fail"done and fail stamp the receipt.
stampstringOverrides the stamp's word.
currencystring"$"Shown before every amount.
titlestring"Run receipt"The heading.

AiCostTicker

PropTypeDefaultDescription
valuenumberThe running figure.
decimalsnumber2Digits after the decimal point.
prefixstring"$"Shown small before the figure.
labelstringA caption above the figure.
statusstatusColours the pill under the figure.
statusLabelstringThe pill's text.
metastringExtra mono detail, such as a token count.

AiUsageBars

PropTypeDefaultDescription
titlestringThe plan's name.
items{ id, label, used, limit, unit? }[]One bar each.
resetLabelstringWhen the counters reset.
warnAtnumber0.8Share of a limit where a bar turns amber.
onUpgrade() => voidShows a button in the header.
upgradeLabelstring"Upgrade"The button's label.