AI context meter
Floating context breakdown popover above a model pill with stacked token bar, 80% compaction mark, SVG ring and Compact now action.
pnpm dlx shadcn@latest add @haze/ai-context-meter---
import { cn } from "../../../lib/haze/utils";
interface ContextSource {
id: string;
label: string;
tokens: number;
}
interface Props {
id?: string;
heading?: string;
modelLabel?: string;
maxTokens?: number;
sources?: ContextSource[];
class?: string;
}
const {
id = "haze-ai-context-meter",
heading = "AI context meter",
modelLabel = "Opus 5.5",
maxTokens = 200000,
sources = [
{ id: "system", label: "System prompt", tokens: 3100 },
{ id: "tools", label: "Tools", tokens: 14200 },
{ id: "files", label: "Files", tokens: 38600 },
{ id: "messages", label: "Messages", tokens: 61000 },
],
class: className,
} = Astro.props;
const totalInitial = sources.reduce((sum, s) => sum + s.tokens, 0);
const freeInitial = Math.max(0, maxTokens - totalInitial);
const initialPct = Math.min(100, Math.round((totalInitial / maxTokens) * 100));
const radius = 7;
const circumference = 2 * Math.PI * radius;
const initialOffset = circumference * (1 - initialPct / 100);
const formatK = (n: number) => (n >= 10000 ? `${Math.round(n / 1000)}k` : `${(n / 1000).toFixed(1)}k`);
const formatPct = (n: number) => `${((n / maxTokens) * 100).toFixed(1)}%`;
const segmentTone = (idx: number) => {
if (idx === 0) return "bg-muted-foreground";
if (idx === 1) return "bg-foreground/70";
if (idx === 2) return "bg-border-strong";
return "bg-foreground/40";
};
const dotSlots = Array.from({ length: 36 });
---
<section
aria-labelledby={`${id}-title`}
data-haze-ai-context-meter
data-max-tokens={String(maxTokens)}
data-sources={JSON.stringify(sources)}
class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
<h2 id={`${id}-title`} class="sr-only">{heading}</h2>
<div class="mx-auto flex w-full max-w-sm flex-col items-end gap-3">
<div
id={`${id}-popover`}
data-acm-popover
class="w-full max-w-xs rounded-2xl border border-border bg-card p-4"
>
<div class="flex items-baseline justify-between gap-2">
<h3 class="text-sm/5 font-semibold text-foreground">Context</h3>
<span
data-acm-total-label
class="font-mono text-sm/5 text-muted-foreground tabular-nums"
>
{formatK(totalInitial)} of {Math.round(maxTokens / 1000)}k
</span>
</div>
<div class="mt-3.5">
<div class="relative flex h-2.5 w-full items-center">
<div
aria-hidden="true"
class="flex h-full w-full items-center justify-between px-0.5"
>
{
dotSlots.map((_, idx) => (
<span
class={cn(
"size-1 rounded-full",
idx >= 29 ? "bg-destructive/60" : "bg-muted-foreground/35"
)}
/>
))
}
</div>
<div class="pointer-events-none absolute inset-0 flex items-center gap-0.5 overflow-hidden rounded-full">
{
sources.map((src, idx) => {
const widthPct = Math.max(1.2, (src.tokens / maxTokens) * 100);
return (
<div
data-acm-seg={src.id}
style={`width: ${widthPct.toFixed(2)}%`}
class={cn(
"h-full transition-[width] duration-300 ease-snappy",
idx === 0 && "rounded-l-full",
segmentTone(idx)
)}
/>
);
})
}
</div>
<span
aria-hidden="true"
style="left: 80%"
class="pointer-events-none absolute -top-1 -bottom-1 w-px bg-muted-foreground/70"
></span>
</div>
<p class="mt-2 text-right text-xs/4 text-muted-foreground">
Compacts at 80%
</p>
</div>
<ul role="list" class="mt-4 space-y-2.5">
{
sources.map((src, idx) => (
<li data-acm-row={src.id} class="flex items-center justify-between gap-2 text-sm/5">
<span class="flex min-w-0 items-center gap-2.5">
<span
aria-hidden="true"
class={cn("size-2.5 shrink-0 rounded-full", segmentTone(idx))}
/>
<span class="truncate text-foreground">{src.label}</span>
</span>
<span class="flex shrink-0 items-center gap-3 font-mono text-xs tabular-nums">
<span data-acm-row-count class="text-foreground">{formatK(src.tokens)}</span>
<span data-acm-row-pct class="w-11 text-right text-muted-foreground">{formatPct(src.tokens)}</span>
</span>
</li>
))
}
<li data-acm-row-free class="flex items-center justify-between gap-2 text-sm/5">
<span class="flex min-w-0 items-center gap-2.5">
<span
aria-hidden="true"
class="size-2.5 shrink-0 rounded-full border border-dashed border-muted-foreground/70 bg-muted/40"
/>
<span class="truncate text-muted-foreground">Free</span>
</span>
<span class="flex shrink-0 items-center gap-3 font-mono text-xs tabular-nums">
<span data-acm-free-count class="text-muted-foreground">{formatK(freeInitial)}</span>
<span data-acm-free-pct class="w-11 text-right text-muted-foreground">{formatPct(freeInitial)}</span>
</span>
</li>
</ul>
<div class="mt-4 flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3.5">
<span data-acm-footer-hint class="text-xs/4 text-muted-foreground">
Summarize older turns
</span>
<button
type="button"
data-acm-action
class="inline-flex h-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-primary px-3.5 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
>
Compact now
</button>
</div>
</div>
<div class="flex w-full items-center justify-between gap-3 rounded-full border border-frame bg-card px-4 py-2 shadow-key">
<span class="truncate text-sm font-medium text-foreground">
{modelLabel}
</span>
<button
type="button"
data-acm-toggle
aria-expanded="true"
aria-controls={`${id}-popover`}
class="inline-flex min-h-8 shrink-0 cursor-pointer items-center gap-2 rounded-full border border-frame bg-muted/60 px-3 py-1 text-xs font-semibold text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<span class="sr-only">Context usage </span>
<svg viewBox="0 0 20 20" class="size-4 -rotate-90" aria-hidden="true">
<circle
cx="10"
cy="10"
r={radius}
fill="none"
stroke-width="2.2"
class="stroke-border-strong"
/>
<circle
data-acm-ring
cx="10"
cy="10"
r={radius}
fill="none"
stroke-width="2.2"
stroke-linecap="round"
stroke-dasharray={circumference.toFixed(2)}
stroke-dashoffset={initialOffset.toFixed(2)}
class="stroke-foreground transition-[stroke-dashoffset,stroke] duration-300 ease-snappy"
/>
</svg>
<span data-acm-pct class="font-mono tabular-nums">{initialPct}%</span>
</button>
</div>
<p data-acm-status role="status" class="sr-only"></p>
</div>
</section>
<script>
interface TokenBucket {
id: string;
label: string;
tokens: number;
}
function initAiContextMeters() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-context-meter]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const popover = root.querySelector<HTMLElement>("[data-acm-popover]");
const toggleBtn = root.querySelector<HTMLButtonElement>("[data-acm-toggle]");
const ring = root.querySelector<SVGCircleElement>("[data-acm-ring]");
const pctEl = root.querySelector<HTMLElement>("[data-acm-pct]");
const totalLabel = root.querySelector<HTMLElement>("[data-acm-total-label]");
const freeCountEl = root.querySelector<HTMLElement>("[data-acm-free-count]");
const freePctEl = root.querySelector<HTMLElement>("[data-acm-free-pct]");
const footerHint = root.querySelector<HTMLElement>("[data-acm-footer-hint]");
const actionBtn = root.querySelector<HTMLButtonElement>("[data-acm-action]");
const status = root.querySelector<HTMLElement>("[data-acm-status]");
const maxTokens = Math.max(1000, Number(root.dataset.maxTokens ?? "200000") || 200000);
const radius = 7;
const circumference = 2 * Math.PI * radius;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let initialBuckets: TokenBucket[] = [];
try {
initialBuckets = JSON.parse(root.dataset.sources ?? "[]") as TokenBucket[];
} catch {
initialBuckets = [];
}
let buckets: TokenBucket[] = initialBuckets.map((b) => ({ ...b }));
let compacted = false;
let animFrame: number | undefined;
const formatK = (n: number) => (n >= 10000 ? `${Math.round(n / 1000)}k` : `${(n / 1000).toFixed(1)}k`);
const formatPct = (n: number) => `${((n / maxTokens) * 100).toFixed(1)}%`;
const announce = (msg: string) => {
if (status) status.textContent = msg;
};
const render = (current: TokenBucket[]) => {
const total = current.reduce((sum, item) => sum + item.tokens, 0);
const free = Math.max(0, maxTokens - total);
const pct = Math.min(100, Math.round((total / maxTokens) * 100));
const offset = circumference * (1 - pct / 100);
const level = pct >= 85 ? "critical" : pct >= 72 ? "warn" : "ok";
if (ring) {
ring.style.strokeDasharray = circumference.toFixed(2);
ring.style.strokeDashoffset = offset.toFixed(2);
ring.classList.toggle("stroke-foreground", level === "ok");
ring.classList.toggle("stroke-warning", level === "warn");
ring.classList.toggle("stroke-destructive", level === "critical");
}
if (pctEl) pctEl.textContent = `${pct}%`;
if (totalLabel) totalLabel.textContent = `${formatK(total)} of ${Math.round(maxTokens / 1000)}k`;
if (freeCountEl) freeCountEl.textContent = formatK(free);
if (freePctEl) freePctEl.textContent = formatPct(free);
current.forEach((item) => {
const widthPct = Math.max(1.2, (item.tokens / maxTokens) * 100);
const seg = root.querySelector<HTMLElement>(`[data-acm-seg="${item.id}"]`);
if (seg) seg.style.width = `${widthPct.toFixed(2)}%`;
const row = root.querySelector<HTMLElement>(`[data-acm-row="${item.id}"]`);
if (!row) return;
const countEl = row.querySelector<HTMLElement>("[data-acm-row-count]");
const rowPctEl = row.querySelector<HTMLElement>("[data-acm-row-pct]");
if (countEl) countEl.textContent = formatK(item.tokens);
if (rowPctEl) rowPctEl.textContent = formatPct(item.tokens);
});
};
const animateTo = (targets: TokenBucket[], onDone: () => void) => {
if (animFrame !== undefined) {
window.cancelAnimationFrame(animFrame);
animFrame = undefined;
}
if (reducedMotion) {
buckets = targets.map((t) => ({ ...t }));
render(buckets);
onDone();
return;
}
const start = buckets.map((b) => ({ ...b }));
const startedAt = performance.now();
const duration = 340;
const tick = (now: number) => {
const t = Math.min(1, (now - startedAt) / duration);
const eased = 1 - Math.pow(1 - t, 3);
buckets = start.map((item, idx) => {
const target = targets[idx]?.tokens ?? item.tokens;
return { ...item, tokens: Math.round(item.tokens + (target - item.tokens) * eased) };
});
render(buckets);
if (t < 1) {
animFrame = window.requestAnimationFrame(tick);
} else {
animFrame = undefined;
onDone();
}
};
animFrame = window.requestAnimationFrame(tick);
};
toggleBtn?.addEventListener("click", () => {
if (!popover) return;
const willOpen = Boolean(popover.hidden);
popover.hidden = !willOpen;
toggleBtn.setAttribute("aria-expanded", String(willOpen));
});
actionBtn?.addEventListener("click", () => {
if (!compacted) {
const beforeTotal = buckets.reduce((sum, b) => sum + b.tokens, 0);
const next = buckets.map((b, idx) => {
if (idx === 0) return { ...b };
if (idx === 1) return { ...b, tokens: Math.max(4000, Math.round(b.tokens * 0.45)) };
if (idx === 2) return { ...b, tokens: Math.max(12000, Math.round(b.tokens * 0.55)) };
return { ...b, tokens: Math.max(14000, Math.round(b.tokens * 0.3)) };
});
const afterTotal = next.reduce((sum, b) => sum + b.tokens, 0);
const reclaimed = Math.max(0, beforeTotal - afterTotal);
compacted = true;
if (actionBtn) actionBtn.textContent = "Simulate fill";
if (footerHint) footerHint.textContent = "Context compacted";
animateTo(next, () => {
const pct = Math.min(100, Math.round((afterTotal / maxTokens) * 100));
announce(`Compacted context: reclaimed ${formatK(reclaimed)} tokens, now at ${pct}%.`);
});
} else {
const filled = initialBuckets.map((b, idx) => {
if (idx === 2) return { ...b, tokens: Math.round(b.tokens * 1.25) };
if (idx === 3) return { ...b, tokens: Math.round(b.tokens * 1.55) };
return { ...b };
});
const nextTotal = filled.reduce((sum, b) => sum + b.tokens, 0);
compacted = false;
if (actionBtn) actionBtn.textContent = "Compact now";
if (footerHint) footerHint.textContent = "Summarize older turns";
animateTo(filled, () => {
const pct = Math.min(100, Math.round((nextTotal / maxTokens) * 100));
announce(`Simulated fill: context usage is now ${pct}%.`);
});
}
});
render(buckets);
});
}
initAiContextMeters();
document.addEventListener("astro:page-load", initAiContextMeters);
</script>When to use
- Surfacing remaining LLM context window capacity inside a chat composer footer
- Showing how system instructions, turns, attached files and tool outputs consume tokens
- Offering one-click context compaction when a long conversation approaches model limits
When not to use
- Displaying monthly billing quotas or account seat counts; use usage-meter instead
Installation
Add the Haze registry to components.json once, then install AI context meter with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-context-meternpx shadcn@latest add @haze/ai-context-meteryarn dlx shadcn@latest add @haze/ai-context-meterbunx --bun shadcn@latest add @haze/ai-context-meterFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | "haze-ai-context-meter" | Unique prefix for labels and popover aria-controls. |
| heading | string | "AI context meter" | Screen-reader section heading for the context meter. |
| modelLabel | string | "Opus 5.5" | Active model name shown on the left of the status pill. |
| maxTokens | number | 200000 | Total context window token budget used for percentage calculations. |
| sources | { id: string; label: string; tokens: number }[] | 4 token buckets | Initial token allocations shown inside the breakdown panel. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move between breakdown actions, draft textarea, context ring toggle and send button
- EnterSpace
- Toggle the breakdown popover, simulate +28% usage or compact active context
Accessibility
- The circular SVG meter button exposes aria-expanded and aria-controls while pairing the ring color with numeric percentage and status text.
- Simulated token spikes and context compaction announce exact reclaimed token counts through a polite role="status" message.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI block "AI context meter" with `npx shadcn@latest add @haze/ai-context-meter`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiContextMeter from "@/components/haze/blocks/ai-context-meter.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/blocks/ai-context-meter.md
Customize with real content
Adapt the Haze ai-context-meter block for our product. Replace the demo values of these props with our real content: id, heading, modelLabel, maxTokens, sources, class. Keep the layout, the heading level rules and these accessibility details: The circular SVG meter button exposes aria-expanded and aria-controls while pairing the ring color with numeric percentage and status text. Simulated token spikes and context compaction announce exact reclaimed token counts through a polite role="status" message. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-context-meter, check it fits: use it when surfacing remaining llm context window capacity inside a chat composer footer; showing how system instructions, turns, attached files and tool outputs consume tokens; offering one-click context compaction when a long conversation approaches model limits. Avoid it when displaying monthly billing quotas or account seat counts; use usage-meter instead. Alternatives: @haze/usage-meter, @haze/progress-ring, @haze/ai-prompt.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.