Context
SaveHow much of the model's context window is used: a compact ring and percentage that opens a card with the input, output, and cached token breakdown and the cost.
- Category
- AI elements
- Version
- 0.1.1
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Context preview
Ask a follow-up
Installation
npx @shakenui/cli add contextReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add context --dry-runUsage
context-example.tsx
import { Context } from "@/components/shaken/agent/context";
export default function ContextExample() {
return (
<div className="flex items-center gap-2 rounded-xl border border-zinc-950/10 px-2 py-1.5 dark:border-white/10">
<span className="px-1.5 text-sm text-zinc-500">Ask a follow-up</span>
<Context
max={200_000}
usage={{ input: 61_400, cacheRead: 18_200, output: 4_600 }}
pricing={{ input: 3, cacheRead: 0.3, output: 15 }}
model="Claude Sonnet 5.5"
/>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| max | number | — | Context window size in tokens. |
| used | number | sum of usage | Tokens in the window now. |
| usage | { input?, output?, cacheRead?, reasoning? } | — | The token breakdown rows. |
| pricing | { input, output, cacheRead?, reasoning? } | — | Prices per million tokens. Adds a cost column and a total. |
| currency | string | "USD" | ISO 4217 code for costs. |
| model | ReactNode | — | Model name at the foot of the card. |
| warnAt / dangerAt | number | 0.8 / 0.95 | Shares of the window where the meter turns amber and red. |
| side | "top" | "bottom" | "left" | "right" | "top" | Card side. |
| formatTokens | (value) => string | — | The compact token format on its own: 950, 84.2K, 1.2M. |
Accessibility
- The trigger is a button whose label states the share, the token counts, and nearing the limit when it applies; the ring is decorative.
- The card opens on hover, keyboard focus, or press (Base UI Popover with openOnHover), so it works without a pointer, and closes with Escape.
- Usage is a Base UI Meter (role="meter") with a value text in exact tokens. The breakdown is a description list.
- Nearing the limit is said in text as well as color.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/context.tsxcontext- Also installs popover@0.2.2registry dependency
- npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/context/0.1.1.json.
agent/context.tsxShowHide
agent/context.tsx
"use client";
import { Meter } from "@base-ui/react/meter";
import type { ReactNode } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
function cx(...classes: Array<string | false | null | undefined>) {
return classes.filter(Boolean).join(" ");
}
export interface ContextUsage {
/** Fresh prompt tokens. */
input?: number;
/** Tokens the model wrote. */
output?: number;
/** Prompt tokens read from the cache. */
cacheRead?: number;
/** Reasoning tokens, when the provider reports them apart from output. */
reasoning?: number;
}
/** Prices per million tokens, in `currency`. */
export interface ContextPricing {
input: number;
output: number;
cacheRead?: number;
/** Defaults to the output price. */
reasoning?: number;
}
export interface ContextProps {
/** Size of the model's context window, in tokens. */
max: number;
/** Tokens in the window now. Defaults to the sum of `usage`. */
used?: number;
/** The breakdown shown in the card. */
usage?: ContextUsage;
/** Adds a cost column and a total. */
pricing?: ContextPricing;
/** ISO 4217 code for the cost figures. @default "USD" */
currency?: string;
/** Model name shown at the foot of the card. */
model?: ReactNode;
/** Share of the window (0 to 1) at which the meter turns amber. @default 0.8 */
warnAt?: number;
/** Share of the window at which it turns red. @default 0.95 */
dangerAt?: number;
/** Card side relative to the trigger. @default "top" */
side?: "top" | "bottom" | "left" | "right";
/** Classes for the trigger button. */
className?: string;
}
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const exact = new Intl.NumberFormat("en");
/** 950, 84.2K, 1.2M. */
export function formatTokens(value: number): string {
return compact.format(Math.max(0, Math.round(value)));
}
function formatCost(value: number, currency: string) {
const options: Intl.NumberFormatOptions = { style: "currency", currency };
if (value > 0 && value < 0.01) {
options.maximumSignificantDigits = 2;
} else {
options.minimumFractionDigits = 2;
options.maximumFractionDigits = 2;
}
return new Intl.NumberFormat("en", options).format(value);
}
type Level = "normal" | "warn" | "danger";
const levelText: Record<Level, string> = {
normal: "text-zinc-950 dark:text-white",
warn: "text-amber-600 dark:text-amber-400",
danger: "text-red-600 dark:text-red-400",
};
const levelFill: Record<Level, string> = {
normal: "bg-zinc-950 dark:bg-white",
warn: "bg-amber-500",
danger: "bg-red-500",
};
/**
* How much of the model's context window is in use: a compact ring and percentage that opens
* a card on hover, focus, or press with the input, output, and cached token breakdown and
* what it cost. The ring turns amber near the limit and red when the window is almost full.
*/
export function Context({
max,
used: usedProp,
usage = {},
pricing,
currency = "USD",
model,
warnAt = 0.8,
dangerAt = 0.95,
side = "top",
className,
}: ContextProps) {
const used = usedProp ?? (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.reasoning ?? 0);
const ratio = max > 0 ? Math.min(1, used / max) : 0;
const percent = Math.round(ratio * 100);
const level: Level = ratio >= dangerAt ? "danger" : ratio >= warnAt ? "warn" : "normal";
const levelWord = level === "danger" ? ", nearly full" : level === "warn" ? ", nearing the limit" : "";
const rows: { label: string; tokens: number; price?: number }[] = [];
if (usage.input != null) rows.push({ label: "Input", tokens: usage.input, price: pricing?.input });
if (usage.cacheRead != null) rows.push({ label: "Cached", tokens: usage.cacheRead, price: pricing?.cacheRead ?? pricing?.input });
if (usage.output != null) rows.push({ label: "Output", tokens: usage.output, price: pricing?.output });
if (usage.reasoning != null) rows.push({ label: "Reasoning", tokens: usage.reasoning, price: pricing?.reasoning ?? pricing?.output });
const costs = rows.map((row) => (row.price != null ? (row.tokens / 1_000_000) * row.price : undefined));
const total = pricing ? costs.reduce<number>((sum, cost) => sum + (cost ?? 0), 0) : undefined;
return (
<Popover>
<PopoverTrigger
openOnHover
delay={200}
closeDelay={120}
aria-label={`Context window: ${percent}% used, ${formatTokens(used)} of ${formatTokens(max)} tokens${levelWord}`}
className={cx(
"inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2 font-mono text-xs tabular-nums select-none",
"text-zinc-600 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950",
"dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
className,
)}
>
<Ring ratio={ratio} level={level} />
<span aria-hidden="true">{percent}%</span>
</PopoverTrigger>
<PopoverContent side={side} align="end" sideOffset={8} className="w-72 p-0">
<div className="p-4">
<Meter.Root
value={used}
min={0}
max={max}
getAriaValueText={() => `${exact.format(Math.round(used))} of ${exact.format(max)} tokens${levelWord}`}
>
<div className="flex items-baseline justify-between gap-3">
<Meter.Label className="text-xs font-medium text-zinc-500">Context window</Meter.Label>
<span className={cx("font-mono text-xs tabular-nums", level === "normal" ? "text-zinc-950 dark:text-white" : levelText[level])}>
{percent}%
</span>
</div>
<p className="mt-1 font-mono text-sm text-zinc-950 tabular-nums dark:text-white">
{formatTokens(used)} <span className="text-zinc-500">/ {formatTokens(max)} tokens</span>
</p>
<Meter.Track className="mt-3 h-1 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10">
<Meter.Indicator className={cx("h-full rounded-full", levelFill[level])} />
</Meter.Track>
</Meter.Root>
{level !== "normal" ? (
<p className={cx("mt-2 text-xs", levelText[level])}>
{level === "danger" ? "Almost full. Older messages will be summarized soon." : "Getting close to the limit."}
</p>
) : null}
</div>
{rows.length ? (
<dl className="grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1.5 border-t border-zinc-950/[0.07] px-4 py-3 text-xs dark:border-white/[0.08]">
{rows.map((row, index) => (
<div key={row.label} className="col-span-3 grid grid-cols-subgrid items-baseline">
<dt className="text-zinc-600 dark:text-zinc-400">{row.label}</dt>
<dd className="text-right font-mono text-zinc-950 tabular-nums dark:text-white">{formatTokens(row.tokens)}</dd>
<dd className="min-w-12 text-right font-mono text-zinc-500 tabular-nums">
{costs[index] != null ? formatCost(costs[index], currency) : pricing ? "" : null}
</dd>
</div>
))}
</dl>
) : null}
{total != null || model != null ? (
<div className="flex items-baseline justify-between gap-3 border-t border-zinc-950/[0.07] px-4 py-3 text-xs dark:border-white/[0.08]">
<span className="min-w-0 truncate text-zinc-500">{model ?? "Total"}</span>
{total != null ? (
<span className="shrink-0 text-zinc-600 dark:text-zinc-400">
{model != null ? "Total " : ""}
<span className="font-mono font-medium text-zinc-950 tabular-nums dark:text-white">{formatCost(total, currency)}</span>
</span>
) : null}
</div>
) : null}
</PopoverContent>
</Popover>
);
}
/** A 16px ring: a faint full circle with the used share drawn over it from twelve o'clock. */
function Ring({ ratio, level }: { ratio: number; level: Level }) {
const r = 6;
const length = 2 * Math.PI * r;
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className={cx("size-4 shrink-0 -rotate-90", levelText[level])}>
<circle cx="8" cy="8" r={r} stroke="currentColor" strokeOpacity="0.18" strokeWidth="2" />
<circle
cx="8"
cy="8"
r={r}
stroke="currentColor"
strokeWidth="2"
strokeLinecap={ratio > 0 ? "round" : "butt"}
strokeDasharray={length}
strokeDashoffset={length * (1 - ratio)}
className="transition-[stroke-dashoffset,color] duration-500 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none"
/>
</svg>
);
}