Aadi

Cost Display

AI chats

About

What an agent run costs as it works: total, steps, duration and tokens update in place, with a breakdown by input, cached input, output and tool calls.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Cost Display to your project and fits it to your theme.

Code

How Cost Display is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { forwardRef, createElement, type SVGAttributes, type ForwardRefExoticComponent, type RefAttributes } from "react"
import { cn } from "@/lib/utils"
import { CostDisplay, CostLine } from "@/components/ui/cost-display"

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

interface Step {
  label: React.ReactNode
  input: number
  cached: number
  output: number
  tools: number
  ms: number
}

function Code({ children }: { children: React.ReactNode }) {
  return <code className="font-mono text-[0.92em]">{children}</code>
}

/** An agent moving webhook handling onto a job queue, one step at a time. */
const STEPS: Step[] = [
  { label: <>Read <Code>api/webhooks.ts</Code></>, input: 14_200, cached: 0, output: 640, tools: 2, ms: 1100 },
  { label: <>Searched the code for <Code>handleEvent</Code></>, input: 6_800, cached: 41_000, output: 410, tools: 3, ms: 1200 },
  { label: "Planned the queue and retry policy", input: 9_300, cached: 88_000, output: 5_200, tools: 0, ms: 1500 },
  { label: <>Wrote <Code>jobs/process-webhook.ts</Code></>, input: 11_400, cached: 132_000, output: 9_800, tools: 2, ms: 1500 },
  { label: <>Edited <Code>api/webhooks.ts</Code></>, input: 7_900, cached: 176_000, output: 3_100, tools: 1, ms: 1100 },
  { label: <>Ran <Code>pnpm test webhooks</Code></>, input: 12_600, cached: 214_000, output: 1_450, tools: 1, ms: 1600 },
]

const HOLD_MS = 3600

/** Prices per million tokens for the fictional model the run uses. */
const PRICE = { input: 3, cached: 0.3, output: 15 }

/** The breakdown for the steps done so far, plus a share of the running step. */
function breakdownAt(done: number, partial: number): CostLine[] {
  const sum = (k: "input" | "cached" | "output" | "tools") =>
    STEPS.reduce((t, s, i) => t + (i < done ? s[k] : i === done ? s[k] * partial : 0), 0)
  const input = Math.round(sum("input"))
  const cached = Math.round(sum("cached"))
  const output = Math.round(sum("output"))
  return [
    { key: "input", label: "Input", tokens: input, cost: (input * PRICE.input) / 1_000_000 },
    { key: "cached", label: "Cached input", tokens: cached, cost: (cached * PRICE.cached) / 1_000_000 },
    { key: "output", label: "Output", tokens: output, cost: (output * PRICE.output) / 1_000_000 },
    { key: "tools", label: "Tool calls", count: Math.round(sum("tools")), cost: 0 },
  ]
}

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

interface IconProps extends SVGAttributes<SVGSVGElement> {
  /** Width and height. Number means px. Default 24. */
  size?: number | string
  /** Stroke width in viewBox units (24 grid). Default 1.5. */
  strokeWidth?: number | string
  /** Keep the rendered stroke at `strokeWidth` px at any size. */
  absoluteStrokeWidth?: boolean
  /** Stroke color. Default currentColor. */
  color?: string
  /** Accessible name. Renders <title> and sets role="img"; without it the icon is aria-hidden. */
  title?: string
}

type Icon = ForwardRefExoticComponent<IconProps & RefAttributes<SVGSVGElement>>

/** Shape elements an icon may contain. */
type IconElement = "path" | "circle" | "rect" | "ellipse" | "line" | "polyline" | "polygon"

/** An icon's drawing: a flat list of [element, attributes] pairs, lucide compatible. */
type IconNode = ReadonlyArray<readonly [IconElement, Readonly<Record<string, string>>]>

const toPascal = (name: string): string =>
  name
    .split("-")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join("")

/**
 * Builds a React icon component from an icon node.
 * `name` is the kebab-case icon name, used for the class `chatcn-icon-<name>` and displayName.
 */
function createIcon(name: string, iconNode: IconNode): Icon {
  // biome-ignore lint/correctness/noComponentHookFactories: runs once per icon at module load
  const Component = forwardRef<SVGSVGElement, IconProps>(function ChatcnIcon(
    {
      size = 24,
      strokeWidth = 1.5,
      absoluteStrokeWidth = false,
      color = "currentColor",
      title,
      className,
      children,
      ...rest
    },
    ref,
  ) {
    const stroke = absoluteStrokeWidth
      ? (Number(strokeWidth) * 24) / Number.parseFloat(String(size))
      : strokeWidth
    const labelled = Boolean(title || rest["aria-label"] || rest["aria-labelledby"])
    return createElement(
      "svg",
      {
        ref,
        xmlns: "http://www.w3.org/2000/svg",
        width: size,
        height: size,
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: color,
        strokeWidth: stroke,
        strokeLinecap: "round",
        strokeLinejoin: "round",
        "data-slot": "icon",
        className: className
          ? `chatcn-icon chatcn-icon-${name} ${className}`
          : `chatcn-icon chatcn-icon-${name}`,
        ...(labelled ? { role: "img" } : { "aria-hidden": true }),
        ...rest,
      },
      title ? createElement("title", null, title) : null,
      ...iconNode.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })),
      children,
    )
  })
  Component.displayName = `${toPascal(name)}Icon`
  return Component
}

const iconNode: IconNode = [
  ["path", {"d":"m4.5 12.75 3.23 3.23a2.5 2.5 0 0 0 3.54 0l8.48-8.48"}],
]

const CheckIcon: Icon = /* @__PURE__ */ createIcon("check", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M12 3a9 9 0 1 1-9 9"}],
]

const LoaderCircleIcon: Icon = /* @__PURE__ */ createIcon("loader-circle", iconNode2)

const duration = (seconds: number) =>
  seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} m ${String(seconds % 60).padStart(2, "0")} s`

const compact = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 })

const kTokens = (n: number) => compact.format(n).toLowerCase()

const stepCost = (s: Step) =>
  (s.input * PRICE.input + s.cached * PRICE.cached + s.output * PRICE.output) / 1_000_000

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * A run card while an agent works: the cost so far, steps, duration and tokens update in place as
 * each step lands with its own cost, then the total settles. Loops. Click the total for the
 * breakdown by input, cached input, output and tool calls.
 */
export default function CostDisplayPreview() {
  // `step` is the running step; STEPS.length means the run is done. `tick` moves within a step.
  const [run, setRun] = React.useState({ step: 0, tick: 0 })
  const TICKS = 4

  React.useEffect(() => {
    if (reducedMotion()) {
      setRun({ step: STEPS.length, tick: 0 })
      return
    }
    const finished = run.step >= STEPS.length
    const ms = finished ? HOLD_MS : STEPS[run.step]!.ms / TICKS
    const id = window.setTimeout(() => {
      setRun((r) => {
        if (r.step >= STEPS.length) return { step: 0, tick: 0 }
        return r.tick + 1 >= TICKS ? { step: r.step + 1, tick: 0 } : { step: r.step, tick: r.tick + 1 }
      })
    }, ms)
    return () => window.clearTimeout(id)
  }, [run])

  const finished = run.step >= STEPS.length
  const partial = finished ? 0 : run.tick / TICKS
  const lines = breakdownAt(run.step, partial)
  const tokens = lines.reduce((t, l) => t + (l.tokens ?? 0), 0)
  const elapsedMs =
    STEPS.slice(0, run.step).reduce((t, s) => t + s.ms, 0) + (finished ? 0 : STEPS[run.step]!.ms * partial)
  // Real runs take minutes; the demo plays them about forty times faster.
  const seconds = Math.round((elapsedMs * 40) / 1000)

  return (
    <FitFrame minWidth="36rem">
      <div className="flex w-full flex-col items-center justify-center gap-5 p-6">
        <div className="rounded-(--chatcn-radius-lg) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) flex w-full max-w-xl flex-col gap-4 p-5">
          <div className="flex items-center gap-3">
            <div className="min-w-0 flex-1">
              <p className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) truncate font-medium">Move webhooks onto the job queue</p>
              <p className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) truncate font-mono">fix/webhook-queue</p>
            </div>
            <span className="bg-(color:--chatcn-fill) text-[0.75rem]/[1rem] text-(color:--chatcn-fg-muted) inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 font-medium">
              {finished ? (
                <CheckIcon className="text-(color:--chatcn-fg) size-3.5" aria-hidden="true" />
              ) : (
                <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden="true" />
              )}
              {finished ? "Done" : "Working"}
            </span>
          </div>
          <CostDisplay
            variant="run"
            live={!finished}
            breakdown={lines}
            model="atlas-pro"
            pricing="$3.00 / M input, $0.30 / M cached, $15.00 / M output."
            stats={[
              { label: "Steps", value: `${Math.min(run.step + (finished ? 0 : 1), STEPS.length)} / ${STEPS.length}` },
              { label: "Duration", value: duration(seconds) },
              { label: "Tokens", value: kTokens(tokens) },
            ]}
          />
          <ol className="border-(color:--chatcn-border) flex flex-col border-t pt-1">
            {STEPS.map((step, i) => {
              const state = i < run.step ? "done" : i === run.step ? "running" : "waiting"
              return (
                <li
                  // biome-ignore lint/suspicious/noArrayIndexKey: a fixed list.
                  key={i}
                  className={cn(
                    "flex h-8 items-center gap-2.5 transition-opacity duration-300",
                    state === "waiting" ? "opacity-0" : "opacity-100",
                  )}
                >
                  <span className="text-(color:--chatcn-fg-subtle) flex size-4 shrink-0 items-center justify-center">
                    {state === "done" ? (
                      <CheckIcon className="size-4" aria-hidden="true" />
                    ) : state === "running" ? (
                      <LoaderCircleIcon className="size-4 animate-spin" aria-hidden="true" />
                    ) : null}
                  </span>
                  <span
                    className={cn(
                      "text-[0.8125rem]/[1.25rem] min-w-0 flex-1 truncate",
                      state === "running" ? "text-(color:--chatcn-fg)" : "text-(color:--chatcn-fg-muted)",
                    )}
                  >
                    {step.label}
                  </span>
                  {state === "done" ? (
                    <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) flex items-center gap-3 tabular-nums">
                      <span>{kTokens(step.input + step.cached + step.output)} tokens</span>
                      <CostDisplay cost={stepCost(step)} className="text-(color:--chatcn-fg-muted) inline-block w-14 text-end" />
                    </span>
                  ) : null}
                </li>
              )
            })}
          </ol>
        </div>
        <MoreOn slug="cost-display">What an agent run costs as it works, step by step. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Audio Visualizer

    Audio Visualizer

    29
  • Stat Card

    Stat Card

    24
  • Dither Orb

    Dither Orb

    23
  • Voice Orb

    Voice Orb

    17
  • Waveform

    Waveform

    13
  • Message Feedback

    Message Feedback

    12
  • Agent Lanes

    Agent Lanes

    11
  • Voice Controls

    Voice Controls

    10

More in AI chats

View all
  • AI Actions

    AI Actions

    349
  • Aquarium Prompt

    Aquarium Prompt

    95
  • Generation Stats

    Generation Stats

  • Chat Bubble

    Chat Bubble

    202
  • Commit

    Commit

    36
  • Color Picker

    Color Picker

    190
  • Environment Variables

    Environment Variables

    27
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    57

Explore more

Part of chatcn — browse the full library on 21st.dev.