# Message Usage

> Show the tokens, cost, and latency of one reply or a whole thread, and open the breakdown on demand.

Source: https://www.honestui.com/docs/ai/message-usage

```tsx
"use client"

import { MessageUsage } from "@/components/ai/message-usage"

/** A reply with its usage underneath. The figures are a sample of what a provider reports. */
export function MessageUsageDemo() {
  return (
    <div className="flex w-full max-w-lg min-w-0 flex-col gap-[var(--hui-space-2)] text-[var(--hui-color-foreground-base-primary)]">
      <p className="m-0 [font-size:var(--hui-font-size-regular)] [line-height:20px]">
        Three invoices are past due: INV-2041 ($1,240, 18 days), INV-2052 ($860, 9 days), and INV-2060 ($2,115, 3 days).
        I drafted a reminder for each, oldest first.
      </p>
      <MessageUsage
        className="-ms-[var(--hui-space-2)] self-start"
        model="gpt-5-mini"
        usage={{ input: 18_420, cachedInput: 12_288, output: 1_184, reasoning: 640 }}
        pricing={{ input: 0.25, cachedInput: 0.025, output: 2 }}
        latency={2_380}
        show={["tokens", "cost", "latency", "model"]}
      />
    </div>
  )
}

```

## Overview [#overview]

Message Usage puts what a reply cost under the reply: how many tokens it used, what they cost, how long it took, and which model answered. It is a quiet row of figures that opens the full breakdown: input, the part of it read from the cache, output, the part of it spent reasoning, and the total.

Take a support assistant that answers from a long policy document. Most of each prompt is the cached document, so a reply that reads "19,604 tokens" costs a fraction of a cent. The breakdown shows why: 12,288 of its 18,420 input tokens were cached.

It is the per-message companion to [Context Meter](/docs/ai/context-meter). Context Meter answers "how full is the window now"; Message Usage answers "what did this reply use". They share the same token formatting.

Message Usage counts nothing. Pass the figures your provider reported. It prices nothing either, unless you pass `pricing`, and then it marks the cost as an estimate.

## Anatomy [#anatomy]

<Anatomy title="MessageUsage">
  <AnatomyItem name="Summary" description="The figures chosen with show: tokens, cost, latency, and model" />

  <AnatomyItem name="Breakdown" description="A popover with input, cached, output, reasoning, and total tokens" />

  <AnatomyItem name="Cost and latency" description="Rows under the counts, when you pass them" />

  <AnatomyItem name="Rates" description="The list prices an estimated cost was worked out from" />
</Anatomy>

`MessageUsage` is one component that takes data. Installing `message-usage` brings [Popover](/docs/components/popover) and [Context Meter](/docs/ai/context-meter) along as registry dependencies.

## Behavior [#behavior]

### Counts [#counts]

`usage.cachedInput` is part of `usage.input`, and `usage.reasoning` is part of `usage.output`, as most providers report them. The breakdown indents them under their parent rows, and the total is input plus output. Rows for cached and reasoning tokens appear only when they are above zero.

### Cost [#cost]

Pass `cost` when your provider bills you a figure; it is shown as it is. Pass `pricing` instead to estimate it from list prices with `estimateCost`. An estimate is marked with a tilde, such as "\~$0.0042", and the breakdown names the rates it used and says the bill may differ. When you pass both, `cost` wins.

Costs under a cent keep two significant digits, so a cheap reply reads "$0.0042" instead of "$0.00".

### Thread totals [#thread-totals]

`variant="thread"` totals a conversation. Add the counts with `sumUsage` and the costs yourself, and pass `messageCount`. The thread variant leaves out latency, because the latencies of separate replies do not add up to anything meaningful.

### What the row shows [#what-the-row-shows]

`show` picks the figures in the collapsed row and their order. The default is tokens, cost, and latency. The breakdown always shows everything you passed.

## Accessibility [#accessibility]

The row is a button. Its name starts with "Usage details" and then reads the visible figures with a pause between each, such as "Usage details: 19,604 tokens, \~$0.0042, 2.4 s". The dots between the figures are hidden from assistive technology. The details open in a popover named by its title, which takes focus and closes on <kbd>Escape</kbd>, returning focus to the row.

The counts are a description list, so each figure is read with its name. Every digit uses tabular figures, so columns of numbers line up.

Every string comes from `labels`, including the number, currency, and duration formats.

| Key                                  | Action                      |
| ------------------------------------ | --------------------------- |
| <kbd>Enter</kbd> or <kbd>Space</kbd> | Open or close the breakdown |
| <kbd>Escape</kbd>                    | Close the breakdown         |

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;@honestai/message-usage&#x22;]" />
  

  
    
      
        Add the items it is built from.
      

      <CliBlock commands="[&#x22;popover&#x22;, &#x22;@honestai/context-meter&#x22;]" />

      
        Copy and paste this file into your project.
      

      ### components/ai/message-usage.tsx

```tsx
"use client"

import * as React from "react"
import { ChevronDown as ChevronDownIcon } from "honestui/icons"

import { cn } from "@/lib/utils"
import { formatTokenCount, TabularDigits } from "@/components/ai/context-meter"
import { Popover, PopoverPopup, PopoverTrigger } from "@/components/honest-ui/ui/popover"

/**
 * The token counts a provider reports for one model call. `cachedInput` is the
 * part of `input` read from the prompt cache, and `reasoning` is the part of
 * `output` the model spent thinking, as most providers report them.
 */
export type MessageUsageTokens = {
  input: number
  output: number
  cachedInput?: number
  reasoning?: number
}

/** List prices, in `currency` per `per` tokens. Defaults to US dollars per million tokens. */
export type ModelPricing = {
  input: number
  output: number
  /** The price of cached input tokens. Without it, cached tokens cost the same as input. */
  cachedInput?: number
  /** How many tokens each price covers. Defaults to 1,000,000. */
  per?: number
  /** An ISO 4217 code, such as "USD" or "EUR". Defaults to "USD". */
  currency?: string
}

export type MessageUsageItem = "tokens" | "cost" | "latency" | "model"

export type MessageUsageLabels = {
  title: string
  threadTitle: string
  /** The trigger's prefix for assistive technology, before the visible summary. */
  details: string
  tokens: (count: string) => string
  messages: (count: number) => string
  model: string
  input: string
  cached: string
  output: string
  reasoning: string
  total: string
  cost: string
  latency: string
  /** Marks a cost worked out from list prices, not billed by the provider. */
  estimatedCost: (cost: string) => string
  estimatedNote: string
  rates: (input: string, output: string, per: string) => string
  /** Formats every token count. */
  number: (value: number) => string
  /** Formats every cost. */
  currency: (value: number, currency: string) => string
  /** Formats a latency in milliseconds. */
  duration: (ms: number) => string
}

const costFormats = new Map<string, Intl.NumberFormat>()

/**
 * Formats a cost so that a small one is still visible: "$0.0042" rather than
 * "$0.00". Costs of a cent or more use two decimals.
 */
export function formatUsageCost(value: number, currency = "USD", locale = "en-US") {
  const small = value !== 0 && Math.abs(value) < 0.01
  const key = `${locale}|${currency}|${small}`
  let format = costFormats.get(key)
  if (!format) {
    format = new Intl.NumberFormat(locale, {
      style: "currency",
      currency,
      ...(small
        ? { minimumSignificantDigits: 2, maximumSignificantDigits: 2 }
        : { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
    })
    costFormats.set(key, format)
  }
  return format.format(value)
}

/** "820 ms" under a second, "2.4 s" under a minute, "1 min 12 s" beyond. */
export function formatUsageDuration(ms: number) {
  if (ms < 1000) return `${Math.round(ms)} ms`
  const seconds = ms / 1000
  if (seconds < 60) return `${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)} s`
  const minutes = Math.floor(seconds / 60)
  return `${minutes} min ${Math.round(seconds - minutes * 60)} s`
}

export const defaultMessageUsageLabels: MessageUsageLabels = {
  title: "Usage",
  threadTitle: "Thread total",
  details: "Usage details",
  tokens: (count) => `${count} tokens`,
  messages: (count) => (count === 1 ? "1 message" : `${count} messages`),
  model: "Model",
  input: "Input",
  cached: "Cached",
  output: "Output",
  reasoning: "Reasoning",
  total: "Total",
  cost: "Cost",
  latency: "Latency",
  estimatedCost: (cost) => `~${cost}`,
  estimatedNote: "Estimated from list prices. Your bill may differ.",
  rates: (input, output, per) => `${input} in · ${output} out per ${per} tokens`,
  number: formatTokenCount,
  currency: (value, currency) => formatUsageCost(value, currency),
  duration: formatUsageDuration,
}

/**
 * The cost of one call at list prices. Cached input is billed at its own price
 * when you give one; reasoning is part of output and is billed with it.
 */
export function estimateCost(usage: MessageUsageTokens, pricing: ModelPricing) {
  const per = pricing.per ?? 1_000_000
  const cached = Math.min(Math.max(usage.cachedInput ?? 0, 0), Math.max(usage.input, 0))
  const freshInput = Math.max(usage.input, 0) - cached
  const cachedPrice = pricing.cachedInput ?? pricing.input
  return (
    (freshInput * pricing.input + cached * cachedPrice + Math.max(usage.output, 0) * pricing.output) / per
  )
}

/** Adds several calls' counts, such as every message in a thread. */
export function sumUsage(usages: MessageUsageTokens[]): MessageUsageTokens {
  return usages.reduce<MessageUsageTokens>(
    (total, usage) => ({
      input: total.input + usage.input,
      output: total.output + usage.output,
      cachedInput: (total.cachedInput ?? 0) + (usage.cachedInput ?? 0),
      reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0),
    }),
    { input: 0, output: 0, cachedInput: 0, reasoning: 0 }
  )
}

const metaText =
  "[font-size:var(--hui-font-size-small)] [letter-spacing:var(--hui-letter-spacing-small)] [line-height:var(--hui-line-height-small)]"

export type MessageUsageProps = Omit<React.ComponentProps<"button">, "children"> & {
  usage: MessageUsageTokens
  /** The billed cost, if your provider reports one. Takes precedence over `pricing`. */
  cost?: number
  /** List prices to estimate the cost from. The estimate is marked as one. */
  pricing?: ModelPricing
  /** The currency of `cost`. Defaults to `pricing.currency`, then "USD". */
  currency?: string
  /** Time to the last token, in milliseconds. */
  latency?: number
  /** The model that answered, such as "gpt-5-mini". */
  model?: string
  /** "message" sits under one reply. "thread" totals a conversation. */
  variant?: "message" | "thread"
  /** With `variant="thread"`, how many messages the total covers. */
  messageCount?: number
  /** What the collapsed row shows, in order. */
  show?: MessageUsageItem[]
  labels?: Partial<MessageUsageLabels>
}

/**
 * Tokens, cost, and latency for one message or a whole thread, as a quiet row
 * that opens the breakdown. It shows the figures your provider reported and
 * prices nothing unless you pass `pricing`.
 */
function MessageUsage({
  usage,
  cost: costProp,
  pricing,
  currency: currencyProp,
  latency,
  model,
  variant = "message",
  messageCount,
  show = ["tokens", "cost", "latency"],
  labels: labelsProp,
  className,
  ...props
}: MessageUsageProps) {
  const labels = { ...defaultMessageUsageLabels, ...labelsProp }
  const titleId = React.useId()

  const currency = currencyProp ?? pricing?.currency ?? "USD"
  const estimated = costProp === undefined && pricing !== undefined
  const costValue = costProp ?? (pricing ? estimateCost(usage, pricing) : undefined)
  const costText =
    costValue === undefined
      ? undefined
      : estimated
        ? labels.estimatedCost(labels.currency(costValue, currency))
        : labels.currency(costValue, currency)
  const total = Math.max(usage.input, 0) + Math.max(usage.output, 0)
  const isThread = variant === "thread"

  const items: string[] = []
  if (isThread && messageCount !== undefined) items.push(labels.messages(messageCount))
  for (const item of show) {
    if (item === "tokens") items.push(labels.tokens(labels.number(total)))
    if (item === "cost" && costText) items.push(costText)
    if (item === "latency" && latency !== undefined && !isThread) items.push(labels.duration(latency))
    if (item === "model" && model) items.push(model)
  }

  const rows: { label: string; value: string; indent?: boolean; strong?: boolean }[] = [
    { label: labels.input, value: labels.number(usage.input) },
    ...(usage.cachedInput
      ? [{ label: labels.cached, value: labels.number(usage.cachedInput), indent: true }]
      : []),
    { label: labels.output, value: labels.number(usage.output) },
    ...(usage.reasoning
      ? [{ label: labels.reasoning, value: labels.number(usage.reasoning), indent: true }]
      : []),
    { label: labels.total, value: labels.number(total), strong: true },
  ]

  const per = pricing?.per ?? 1_000_000
  const perText = per === 1_000_000 ? "1M" : labels.number(per)

  return (
    <Popover>
      <PopoverTrigger
        data-slot="message-usage"
        data-variant={variant}
        className={cn(
          "group/usage inline-flex min-h-[var(--hui-control-height-sm,28px)] max-w-full cursor-pointer items-center gap-[var(--hui-space-2)] rounded-[var(--hui-radius-2)] border-0 bg-transparent px-[var(--hui-space-2)] py-[var(--hui-space-1)] text-[var(--hui-color-foreground-base-secondary)] outline-none motion-safe:[transition:var(--hui-transition-interactive)] hover:bg-[var(--hui-color-background-base-primary-hover)] hover:text-[var(--hui-color-foreground-base-primary)] focus-visible:[outline:var(--hui-focus-ring)] data-popup-open:bg-[var(--hui-color-background-base-primary-hover)] data-popup-open:text-[var(--hui-color-foreground-base-primary)]",
          metaText,
          className
        )}
        // One name built from the same strings, so it reads "Usage details: 19,604 tokens, ~$0.0042, 2.4 s".
        aria-label={`${labels.details}: ${isThread ? `${labels.threadTitle}, ` : ""}${items.join(", ")}`}
        {...props}
      >
        {isThread && (
          <span className="shrink-0 [font-weight:var(--hui-font-weight-medium)] text-[var(--hui-color-foreground-base-primary)]">
            {labels.threadTitle}
          </span>
        )}
        <span data-slot="message-usage-summary" className="flex min-w-0 flex-wrap items-center gap-x-[var(--hui-space-2)]">
          {items.map((item, index) => (
            <React.Fragment key={`${item}-${index}`}>
              {index > 0 && (
                <span aria-hidden="true" className="select-none">
                  ·
                </span>
              )}
              <span className="whitespace-nowrap">
                <TabularDigits text={item} />
              </span>
            </React.Fragment>
          ))}
        </span>
        <ChevronDownIcon
          aria-hidden="true"
          className="size-3 shrink-0 opacity-70 motion-safe:transition-transform group-data-popup-open/usage:rotate-180"
        />
      </PopoverTrigger>
      <PopoverPopup align="start" aria-labelledby={titleId} className="w-72 max-w-[calc(100vw-2rem)]">
        <div data-slot="message-usage-details" className="flex flex-col gap-[var(--hui-space-3)]">
          <div className="flex items-baseline justify-between gap-[var(--hui-space-3)]">
            <p id={titleId} className="m-0 [font-weight:var(--hui-font-weight-medium)]">
              {isThread ? labels.threadTitle : labels.title}
            </p>
            {isThread && messageCount !== undefined ? (
              <span className="text-[var(--hui-color-foreground-base-secondary)] tabular-nums">
                {labels.messages(messageCount)}
              </span>
            ) : model ? (
              <span className="min-w-0 truncate text-[var(--hui-color-foreground-base-secondary)]" title={model}>
                <span className="sr-only">{`${labels.model}: `}</span>
                {model}
              </span>
            ) : null}
          </div>

          <dl className="m-0 grid grid-cols-[minmax(0,1fr)_auto] gap-y-[var(--hui-space-1)]">
            {rows.map((row) => (
              <React.Fragment key={row.label}>
                <dt
                  className={cn(
                    "min-w-0 break-words pe-[var(--hui-space-4)]",
                    row.strong
                      ? "mt-[var(--hui-space-1)] border-t-[0.5px] border-[var(--hui-color-border-base-primary)] pt-[var(--hui-space-2)] [font-weight:var(--hui-font-weight-medium)]"
                      : "text-[var(--hui-color-foreground-base-secondary)]",
                    row.indent && "ps-[var(--hui-space-4)]"
                  )}
                >
                  {row.label}
                </dt>
                <dd
                  className={cn(
                    "m-0 text-end",
                    row.strong &&
                      "mt-[var(--hui-space-1)] border-t-[0.5px] border-[var(--hui-color-border-base-primary)] pt-[var(--hui-space-2)] [font-weight:var(--hui-font-weight-medium)]",
                    row.indent && "text-[var(--hui-color-foreground-base-secondary)]"
                  )}
                >
                  <TabularDigits text={row.value} />
                </dd>
              </React.Fragment>
            ))}
            {costText !== undefined && (
              <>
                <dt className="pe-[var(--hui-space-4)] text-[var(--hui-color-foreground-base-secondary)]">{labels.cost}</dt>
                <dd className="m-0 text-end">
                  <TabularDigits text={costText} />
                </dd>
              </>
            )}
            {latency !== undefined && !isThread && (
              <>
                <dt className="pe-[var(--hui-space-4)] text-[var(--hui-color-foreground-base-secondary)]">{labels.latency}</dt>
                <dd className="m-0 text-end">
                  <TabularDigits text={labels.duration(latency)} />
                </dd>
              </>
            )}
          </dl>

          {estimated && pricing && (
            <p className={cn("m-0 break-words text-[var(--hui-color-foreground-base-secondary)]", metaText)}>
              <TabularDigits
                text={labels.rates(
                  labels.currency(pricing.input, currency),
                  labels.currency(pricing.output, currency),
                  perText
                )}
              />
              <br />
              {labels.estimatedNote}
            </p>
          )}
        </div>
      </PopoverPopup>
    </Popover>
  )
}

export { MessageUsage }

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

```tsx
import { MessageUsage } from "@/components/ai/message-usage"

<MessageUsage
  model={message.model}
  usage={{
    input: message.usage.inputTokens,
    cachedInput: message.usage.cachedInputTokens,
    output: message.usage.outputTokens,
    reasoning: message.usage.reasoningTokens,
  }}
  pricing={{ input: 0.25, cachedInput: 0.025, output: 2 }}
  latency={message.latencyMs}
/>
```

## Examples [#examples]

### Per turn and thread total [#per-turn-and-thread-total]

Billed costs on each turn, with a thread total at the foot.

```tsx
"use client"

import { MessageUsage, sumUsage, type MessageUsageTokens } from "@/components/ai/message-usage"

const turns: { prompt: string; usage: MessageUsageTokens; cost: number; latency: number }[] = [
  { prompt: "Summarize last week's churn", usage: { input: 6_210, output: 742 }, cost: 0.0298, latency: 3_120 },
  { prompt: "Break it down by plan", usage: { input: 7_480, cachedInput: 6_144, output: 1_036 }, cost: 0.0211, latency: 2_460 },
  { prompt: "Draft a note for the team", usage: { input: 8_905, cachedInput: 7_168, output: 1_412, reasoning: 384 }, cost: 0.0262, latency: 4_870 },
]

/** Each turn shows its billed cost; the footer totals the thread. */
export function MessageUsageThread() {
  const total = sumUsage(turns.map((turn) => turn.usage))
  const totalCost = turns.reduce((sum, turn) => sum + turn.cost, 0)

  return (
    <div className="flex w-full max-w-lg min-w-0 flex-col overflow-hidden rounded-[var(--hui-radius-4)] border-[0.5px] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] text-[var(--hui-color-foreground-base-primary)] shadow-[var(--hui-shadow-feather)]">
      <ul className="m-0 list-none p-0">
        {turns.map((turn) => (
          <li
            key={turn.prompt}
            className="flex min-h-11 flex-wrap items-center justify-between gap-x-[var(--hui-space-4)] border-b-[0.5px] border-[var(--hui-color-border-base-primary)] px-[var(--hui-space-5)] py-[var(--hui-space-2)] [font-size:var(--hui-font-size-regular)]"
          >
            <span className="min-w-0 truncate">{turn.prompt}</span>
            <MessageUsage
              className="-me-[var(--hui-space-2)]"
              usage={turn.usage}
              cost={turn.cost}
              latency={turn.latency}
              show={["tokens", "cost"]}
              model="claude-sonnet-5-5"
            />
          </li>
        ))}
      </ul>
      <div className="flex items-center justify-end bg-[var(--hui-color-background-base-secondary)] px-[var(--hui-space-3)] py-[var(--hui-space-2)]">
        <MessageUsage variant="thread" messageCount={turns.length} usage={total} cost={totalCost} />
      </div>
    </div>
  )
}

```

## API reference [#api-reference]

### MessageUsage [#messageusage]

Accepts native button props beyond those listed.

| Prop           | Type                          | Default                          | Description                                                  |
| -------------- | ----------------------------- | -------------------------------- | ------------------------------------------------------------ |
| `usage`        | `MessageUsageTokens`          | Required                         | The token counts your provider reported.                     |
| `cost`         | number                        | None                             | The billed cost. Takes precedence over `pricing`.            |
| `pricing`      | `ModelPricing`                | None                             | List prices to estimate the cost from.                       |
| `currency`     | string                        | `pricing.currency`, then `"USD"` | The currency of `cost`.                                      |
| `latency`      | number                        | None                             | Time to the last token, in milliseconds.                     |
| `model`        | string                        | None                             | The model that answered.                                     |
| `variant`      | `"message"` or `"thread"`     | `"message"`                      | One reply, or a conversation's total.                        |
| `messageCount` | number                        | None                             | How many messages a thread total covers.                     |
| `show`         | `MessageUsageItem[]`          | `["tokens", "cost", "latency"]`  | The figures in the collapsed row, in order.                  |
| `labels`       | `Partial<MessageUsageLabels>` | English                          | Every string and the number, currency, and duration formats. |

### Helpers [#helpers]

| Export                                       | Description                                                                  |
| -------------------------------------------- | ---------------------------------------------------------------------------- |
| `estimateCost(usage, pricing)`               | The cost at list prices. Cached input uses `pricing.cachedInput` when given. |
| `sumUsage(usages)`                           | Adds several calls' counts.                                                  |
| `formatUsageCost(value, currency?, locale?)` | Formats a cost, keeping small ones visible.                                  |
| `formatUsageDuration(ms)`                    | "820 ms", "2.4 s", or "1 min 12 s".                                          |

### Types [#types]

| Export               | Shape                                                                                          |
| -------------------- | ---------------------------------------------------------------------------------------------- |
| `MessageUsageTokens` | `input`, `output`, and optional `cachedInput` and `reasoning`                                  |
| `ModelPricing`       | `input`, `output`, and optional `cachedInput`, `per` (default 1,000,000), and `currency`       |
| `MessageUsageItem`   | `"tokens"`, `"cost"`, `"latency"`, or `"model"`                                                |
| `MessageUsageLabels` | Titles, row names, `estimatedCost`, `estimatedNote`, `rates`, `number`, `currency`, `duration` |
