Skip to content
Browse documentation

A living WebGL2 AI context budget: a real-time plush, clay or jelly creature physically inflates as tokens mount, presses flat against the glass past 90%, and squeezes down when compacted.

Used forAI coding & chat workspacesAgent inspectorsRAG & document pickersVoice & companion apps

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/context-window

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/context-window.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • AI coding & chat workspaces

    Show live token usage beside a one-click /compact memory button.

  • Agent inspectors

    Let users drop heavy tool outputs or logs before the model loses recall.

  • RAG & document pickers

    Attach files by click or drag-and-drop with immediate capacity feedback.

  • Voice & companion apps

    Give an AI assistant a tactile physical presence that reflects real model state.

What it handles for you

A static progress bar tells you a number without making headroom tangible or giving you a way to trim bloat. This makes context fullness physical and puts file removal and compaction right underneath.

Instead of wiring upa token usage metera context breakdown listan overflow guarda /compact action buttona mascot or sprite rig
  1. Inflates and presses the walls

    The WebGL2 SDF creature scales continuously with used / limit and smoothly flattens against the alcove walls past 90%.

  2. Three real-time materials

    Switch between volumetric shell plush fur, matte stop-motion clay with healing thumbprint poke dents, and refracted jelly with lagging inner eyes.

  3. Overflow belly bounce

    Attaching an item that exceeds limit rebounds off the creature with a steam burst and “Too full — compact first”.

  4. Hover anticipation

    Hovering any file’s remove button draws its gaze downward and previews slight relief before you click.

  5. Compaction squeeze

    onCompact squeezes the creature inward while pending, then pops it free with sparkles as NumberRoll drops the count.

  6. Zero Three.js, sleeps off-screen

    Pure WebGL2 (~16 KB) that pauses via IntersectionObserver when scrolled out of view and renders a still frame under reduced motion.

Overview

AI context limits usually hide inside a tiny percentage ring until answers go sideways. Here the creature’s body is the context window itself, rendered live in raw WebGL2 with zero Three.js and no image sprites. At low usage Munch floats lightly inside the glass alcove and tracks your pointer. Feed in files or tool outputs and it gulps and swells continuously; past 90% its 3D SDF body presses flat against the alcove walls and puffs steam, bouncing excess files right off its belly. Hovering a heavy file’s remove button makes it glance down hopefully; pressing Compact squeezes it inward while your request runs, then pops it back to nimble as every token counter rolls down.

States

light
Under 75%: small and nimble inside the glass alcove, tracking your cursor and opening wide to gulp newly attached files.
heavy
75% to 90%: visibly rounder and plumper, worried brows, amber counter and “Getting heavy · recall dips”; Compact upgrades to primary.
stuffed
90% and above: swells until cheeks and ears flatten smoothly against the alcove glass walls, flushes warm red and puffs steam.
overflow
Attempting to attach an item beyond limit bounces it off with a dizzy tilt, steam burst and “Too full — compact first”.
compacting
Compact → Compacting: creature pulls off the walls and squeezes tightly inward with a tremor; on resolve it pops light with sparkles and ^ ^ eyes.

Usage

usage.tsx
import { ContextWindow } from "@/components/context-window";<ContextWindow  items={contextItems}  limit={200_000}  material="plush"  onRemove={(id) => dropItem(id)}  onCompact={() => compactThread()}/>

Works with

Wired to an AI SDK chat and /api/compact

Pass your attached files and latest thread token count as items; onCompact calls your summarisation route and swaps history for the summary.

example.tsx
"use client";import * as React from "react";import { ContextWindow, type ContextItem } from "@/components/context-window";export function ThreadContext({ threadId, initialItems }: { threadId: string; initialItems: ContextItem[] }) {  const [items, setItems] = React.useState(initialItems);  return (    <ContextWindow      items={items}      limit={200_000}      material="clay"      tone="primary"      model="200k window"      onRemove={async (id) => {        await fetch(`/api/threads/${threadId}/context/${id}`, { method: "DELETE" });        setItems((prev) => prev.filter((item) => item.id !== id));      }}      onCompact={async () => {        const res = await fetch(`/api/threads/${threadId}/compact`, { method: "POST" });        const { items: next } = await res.json();        setItems(next);      }}    />  );}

Props

items= []
ContextItem[]
{ id, label, tokens, kind?, pinned?, color? } shown in the bar and removable list.
limit
number
Maximum tokens in the model context window (e.g. 200_000).
material= "plush"
"plush" | "clay" | "jelly"
Real-time WebGL2 surface: volumetric fur, matte clay with poke dents, or refracted jelly.
tone= "coral"
"coral" | "lilac" | "peach" | "mint" | "sky" | "butter" | "primary"
Colour palette; "primary" reads shadcn --primary dynamically.
onCompact / compactLabel= — / "Compact memory"
() => Promise<unknown> / string
Runs compaction with pending/success/error states and drives the squeeze animation.
onRemove
(id: string) => void | Promise<unknown>
Drops a non-pinned item from context; hovering its button triggers relief anticipation.
suggestions / onAdd
Omit<ContextItem, "pinned">[] / (item) => boolean | void | Promise<…>
Optional quick-attach chips and drag-and-drop target on the stage. Return false to trigger overflow bounce.
model / name= — / "Munch"
string
Quiet model badge beside the title, and the creature’s name in status copy.

Accessibility and motion

  • The segmented bar carries role="meter" with aria-valuenow, aria-valuemax and a human-readable aria-valuetext; the WebGL2 canvas is aria-hidden.
  • Status updates announce through a polite sr-only live region placed outside the buttons.
  • Runs in raw WebGL2 with zero Three.js and zero external assets; pauses automatically off-screen and in background tabs.
  • Supports direct touch on the stage: hover-rub to sweep plush fur, click clay to press a healing thumbprint dent, drag and fling jelly to watch its inner eyes lag.
  • Under prefers-reduced-motion the continuous loop stops and a single crisp frame renders whenever usage or state changes.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Status button, Text morph.

Source

"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { StatusButton, type ActionStatus } from "./status-button";import { TextMorph } from "./text-morph";import {  TactileCreatureEngine,  type ContextMaterial,  type ContextTone,  type CreatureMood,} from "./tactile-creature-gl";import {  EASE_OUT,  INTERACTION_FOCUS,  INTERACTION_PRESS,  useInteractionActivity,  useInteractionReducedMotion,} from "./ui-interaction-motion";export type { ContextMaterial, ContextTone };/* ───────────────────────────────────────────────────────── * CONTEXT WINDOW: Munch, the living AI memory budget * *   light      small and nimble inside the glass alcove; eyes *              track the pointer and open wide to gulp new files *   heavy      75%+ — cheeks puff, brows knit, bar turns amber *   stuffed    90%+ — body swells until it presses flat against *              the alcove walls and puffs steam *   overflow   adding past the limit bounces off its belly *   hover ×    hovering a file's remove button makes it glance *              down hopefully and ease slightly *   compact    squeezes tight inward while pending, then pops *              free in a puff of relief as tokens roll back down * * Interactive directly on the stage too: pet to sweep plush fur, * click clay to leave healing thumbprint dents, drag and fling * jelly to watch its suspended inner eyes lag behind. * ───────────────────────────────────────────────────────── */export interface ContextItem {  id: string;  label: string;  tokens: number;  /** Optional category tag (e.g. "system", "file", "tool", "chat"). */  kind?: string;  /** Pinned items stay through compaction and cannot be removed. */  pinned?: boolean;  /** Any CSS colour; defaults to --chart-1…5. */  color?: string;}export interface ContextWindowProps {  /** Items currently held in the model's context window. */  items?: ContextItem[];  /** Model context limit in tokens (e.g. 200_000). */  limit: number;  /** Real-time WebGL2 surface for the creature. */  material?: ContextMaterial;  /** Colour tone ("primary" reads shadcn --primary). */  tone?: ContextTone;  /** Compact / summarise old context; update `items` once resolved. */  onCompact?: () => Promise<unknown>;  compactLabel?: string;  /** Drop one item from context. */  onRemove?: (id: string) => void | Promise<unknown>;  /** Quick-attach items shown below the list so users can feed context directly. */  suggestions?: Omit<ContextItem, "pinned">[];  /** Attach an item (or dropped file). Return `false` to play the belly-bounce rejection. */  onAdd?: (item: Omit<ContextItem, "pinned">) => boolean | void | Promise<boolean | void>;  /** Optional model badge in the header (e.g. "200k window" or "Claude 4.5"). */  model?: string;  /** Creature's name in status copy. */  name?: string;  className?: string;}const EMPTY_ITEMS: ContextItem[] = [];const EMPTY_SUGGESTIONS: Omit<ContextItem, "pinned">[] = [];const mix = (color: string, amount: number, into = "transparent") =>  `color-mix(in oklab, ${color} ${amount}%, ${into})`;const PF = "var(--primary-foreground)";const CARD: React.CSSProperties = {  backgroundImage: `linear-gradient(180deg, var(--card), ${mix("var(--card)", 96, "var(--foreground)")})`,  boxShadow: `0 0 0 1px var(--border), inset 0 1px 0 ${mix("var(--background)", 85)}`,};const LIT: React.CSSProperties = {  backgroundImage: `linear-gradient(180deg, ${mix(PF, 16)}, transparent 60%)`,  boxShadow: `inset 0 1px 0 ${mix(PF, 32)}, inset 0 0 0 1px ${mix("black", 10)}`,};const CHART = [  "var(--chart-1, var(--primary))",  "var(--chart-2, #10b981)",  "var(--chart-3, #f59e0b)",  "var(--chart-4, #8b5cf6)",  "var(--chart-5, #ef4444)",];function formatTokens(n: number) {  const v = Math.max(0, n);  if (v >= 1_000_000) return { value: v / 1_000_000, unit: "M", digits: 1 };  if (v >= 1_000) return { value: v / 1_000, unit: "k", digits: v < 10_000 ? 1 : 0 };  return { value: v, unit: "", digits: 0 };}function TokenFigure({ n }: { n: number }) {  const f = formatTokens(n);  return (    <span className="whitespace-nowrap tabular-nums">      <NumberRoll value={f.value} format={{ maximumFractionDigits: f.digits, minimumFractionDigits: f.digits }} />      {f.unit}    </span>  );}function formatPlainTokens(n: number) {  const f = formatTokens(n);  return `${f.value.toFixed(f.digits)}${f.unit}`;}export function ContextWindow({  items = EMPTY_ITEMS,  limit,  material = "plush",  tone = "coral",  onCompact,  compactLabel = "Compact memory",  onRemove,  suggestions = EMPTY_SUGGESTIONS,  onAdd,  model,  name = "Munch",  className = "",}: ContextWindowProps) {  const reduced = useInteractionReducedMotion();  const { ref: activityRef, active } = useInteractionActivity<HTMLElement>();  const baseId = React.useId();  const stageRef = React.useRef<HTMLDivElement>(null);  const engineRef = React.useRef<TactileCreatureEngine | null>(null);  const timerRef = React.useRef<number | null>(null);  const [compactStatus, setCompactStatus] = React.useState<ActionStatus>("idle");  const [hoverRemoveId, setHoverRemoveId] = React.useState<string | null>(null);  const [hoverCompact, setHoverCompact] = React.useState(false);  const [dragOver, setDragOver] = React.useState(false);  const [flash, setFlash] = React.useState<"none" | "rejected" | "annoyed" | "relieved" | "gulped">("none");  const used = React.useMemo(() => items.reduce((sum, it) => sum + Math.max(0, it.tokens), 0), [items]);  const ratio = limit > 0 ? used / limit : 1;  const pct = Math.min(100, Math.round(ratio * 100));  const heavy = ratio >= 0.75;  const stuffed = ratio >= 0.9;  const compactableTokens = React.useMemo(    () => items.filter((it) => !it.pinned).reduce((sum, it) => sum + Math.max(0, it.tokens), 0),    [items],  );  const mood: CreatureMood =    compactStatus === "pending"      ? "compacting"      : flash === "rejected" || flash === "annoyed"        ? "rejected"        : flash === "relieved" || compactStatus === "success"          ? "relieved"          : flash === "gulped"            ? "gulp"            : stuffed              ? "stuffed"              : heavy                ? "heavy"                : "idle";  const triggerFlash = React.useCallback((kind: "rejected" | "annoyed" | "relieved" | "gulped", ms: number) => {    setFlash(kind);    if (timerRef.current !== null) window.clearTimeout(timerRef.current);    timerRef.current = window.setTimeout(() => {      setFlash("none");      timerRef.current = null;    }, ms);  }, []);  React.useEffect(() => {    return () => {      if (timerRef.current !== null) window.clearTimeout(timerRef.current);    };  }, []);  // Mount WebGL2 creature once; update props imperatively without tearing down context  React.useEffect(() => {    const el = stageRef.current;    if (!el) return;    const engine = new TactileCreatureEngine(el, {      material,      tone,      fullness: Math.min(1.12, ratio),      mood,      reduced,      onPokeAnnoyed: () => triggerFlash("annoyed", 2400),    });    engineRef.current = engine;    return () => {      engine.dispose();      engineRef.current = null;    };    // eslint-disable-next-line react-hooks/exhaustive-deps  }, []);  React.useEffect(() => {    engineRef.current?.setProps({      material,      tone,      fullness: Math.min(1.12, ratio),      mood,      hoverRelief: Boolean(hoverRemoveId) || (hoverCompact && heavy),      reduced,    });  }, [material, tone, ratio, mood, hoverRemoveId, hoverCompact, heavy, reduced]);  React.useEffect(() => {    engineRef.current?.setActive(active);  }, [active]);  const handleAdd = async (candidate: Omit<ContextItem, "pinned">) => {    if (!onAdd) return;    if (used + candidate.tokens > limit) {      engineRef.current?.triggerReject();      triggerFlash("rejected", 2100);      return;    }    const ok = await onAdd(candidate);    if (ok === false) {      engineRef.current?.triggerReject();      triggerFlash("rejected", 2100);      return;    }    engineRef.current?.triggerGulp(candidate.tokens / Math.max(1, limit));    triggerFlash("gulped", 700);  };  const handleRemove = async (id: string) => {    if (!onRemove) return;    setHoverRemoveId(null);    await onRemove(id);    engineRef.current?.triggerRelief();    triggerFlash("relieved", 1200);  };  const handleCompact = async () => {    if (!onCompact || compactStatus === "pending") return;    setHoverCompact(false);    setCompactStatus("pending");    try {      await onCompact();      setCompactStatus("success");      triggerFlash("relieved", 1800);      window.setTimeout(() => setCompactStatus("idle"), 1700);    } catch {      setCompactStatus("error");      engineRef.current?.triggerReject();    }  };  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {    e.preventDefault();    setDragOver(false);    if (!onAdd) return;    const file = e.dataTransfer.files?.[0];    if (!file) return;    const estTokens = Math.max(4_000, Math.min(Math.round(limit * 0.45), Math.round(file.size / 4)));    void handleAdd({      id: `drop-${file.name}-${file.size}`,      label: file.name,      tokens: estTokens,      kind: "file",    });  };  const statusLine =    compactStatus === "pending"      ? "Squeezing old turns…"      : flash === "rejected"        ? "Too full — compact first"        : flash === "annoyed"          ? `Hey, ${name} is full enough`          : flash === "relieved" || compactStatus === "success"            ? "Phew. Light again"            : hoverRemoveId              ? "Drop that to free room"              : dragOver                ? "Drop to feed context"                : stuffed                  ? "Pressed against the glass"                  : heavy                    ? "Getting heavy · recall dips"                    : ratio >= 0.45                      ? "Comfortable headroom"                      : "Plenty of room";  const stageStyle: React.CSSProperties = {    backgroundColor: mix("var(--foreground)", 4, "var(--card)"),    backgroundImage: [      `radial-gradient(68% 72% at 50% 18%, ${mix("var(--background)", 88)} 0%, transparent 74%)`,      stuffed || flash === "rejected"        ? `radial-gradient(80% 45% at 50% 0%, ${mix("#ef4444", 12)} 0%, transparent 70%)`        : heavy          ? `radial-gradient(80% 45% at 50% 0%, ${mix("#f59e0b", 10)} 0%, transparent 70%)`          : "none",    ]      .filter((layer) => layer !== "none")      .join(", "),    boxShadow: dragOver      ? `inset 0 0 0 1.5px var(--primary)`      : `inset 0 0 0 1px ${mix("var(--border)", 100)}, inset 0 1px 0 ${mix("var(--background)", 70)}`,  };  const availableSuggestions = suggestions.filter((s) => !items.some((it) => it.id === s.id));  return (    <section      ref={activityRef}      aria-labelledby={`${baseId}-title`}      className={`relative w-full max-w-[416px] rounded-[28px] p-2 text-card-foreground ${className}`}      style={CARD}    >      <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 416px)" }} />      <div className="@container w-full">        {/* Lit glass alcove: the creature physically inflates and presses flat against its walls */}        <div          className="relative overflow-clip rounded-[22px] select-none transition-[box-shadow] duration-200"          style={stageStyle}          onDragOver={(e) => {            if (!onAdd) return;            e.preventDefault();            setDragOver(true);          }}          onDragLeave={() => setDragOver(false)}          onDrop={handleDrop}        >          <div            ref={stageRef}            aria-hidden="true"            className="relative w-full cursor-grab touch-none active:cursor-grabbing"            style={{ aspectRatio: "16 / 9.4" }}          />          <p className="pointer-events-none absolute left-3.5 top-3 z-10 text-[12.5px] font-medium tracking-[-0.01em] text-muted-foreground">            <TextMorph>{statusLine}</TextMorph>          </p>          <span            aria-hidden="true"            className={`pointer-events-none absolute right-3.5 top-3 z-10 font-mono text-[12px] font-medium tabular-nums ${              stuffed || flash === "rejected"                ? "text-red-600 dark:text-red-400"                : heavy                  ? "text-amber-700 dark:text-amber-400"                  : "text-muted-foreground"            }`}          >            <NumberRoll value={pct} />%          </span>        </div>        {/* Polite announcement outside buttons for screen readers */}        <p className="sr-only" aria-live="polite">          {statusLine}. {formatPlainTokens(used)} of {formatPlainTokens(limit)} tokens used.        </p>        {/* Header & rolling token count */}        <div className="px-2.5 pt-3">          <div className="flex items-baseline justify-between gap-2">            <div className="flex min-w-0 items-baseline gap-2">              <h2 id={`${baseId}-title`} className="truncate text-[15px] font-medium tracking-[-0.01em] text-foreground">                Context window              </h2>              {model && <span className="hidden truncate text-[12px] text-muted-foreground @[21rem]:inline">{model}</span>}            </div>            <p              className={`shrink-0 text-[12.5px] ${                stuffed                  ? "text-red-600 dark:text-red-400"                  : heavy                    ? "text-amber-700 dark:text-amber-400"                    : "text-muted-foreground"              }`}            >              <span className="font-medium text-foreground">                <TokenFigure n={used} />              </span>{" "}              / <TokenFigure n={limit} />            </p>          </div>          {/* Segmented hairline meter */}          <div            className="mt-2.5 flex h-2.5 w-full gap-[2px] overflow-clip rounded-full"            role="meter"            aria-label="Context window tokens"            aria-valuemin={0}            aria-valuemax={limit}            aria-valuenow={Math.min(used, limit)}            aria-valuetext={`${formatPlainTokens(used)} of ${formatPlainTokens(limit)} tokens used (${pct}%)`}            style={{ background: mix("var(--foreground)", 7) }}          >            {items.map((it, idx) => {              const segPct = (Math.max(0, it.tokens) / Math.max(1, limit)) * 100;              return (                <span                  key={it.id}                  className="h-full shrink-0 first:rounded-l-full last:rounded-r-full"                  style={{                    width: `${Math.min(100, segPct)}%`,                    background: it.color ?? CHART[idx % CHART.length],                    opacity: hoverRemoveId === it.id ? 0.45 : 1,                    transition: reduced ? "none" : `width 680ms ${EASE_OUT}, opacity 180ms ease`,                  }}                />              );            })}          </div>          {/* Attached context rows */}          {items.length > 0 && (            <ul className="mt-3 divide-y divide-border/70 border-t border-border/70">              {items.map((it, idx) => (                <li                  key={it.id}                  className="flex items-center justify-between gap-2 py-2 text-[13px] transition-colors"                >                  <div className="flex min-w-0 items-center gap-2">                    <span                      aria-hidden="true"                      className="size-2 shrink-0 rounded-full"                      style={{ background: it.color ?? CHART[idx % CHART.length] }}                    />                    <span className="truncate font-medium text-foreground">{it.label}</span>                    {it.kind && (                      <span className="hidden shrink-0 text-[11.5px] text-muted-foreground @[20rem]:inline">                        {it.kind}                      </span>                    )}                  </div>                  <div className="flex shrink-0 items-center gap-1.5">                    <span className="font-mono text-[12px] text-muted-foreground tabular-nums">                      <TokenFigure n={it.tokens} />                    </span>                    {it.pinned ? (                      <span className="px-1.5 py-0.5 text-[11px] text-muted-foreground">Pinned</span>                    ) : onRemove ? (                      <button                        type="button"                        aria-label={`Remove ${it.label} (${formatPlainTokens(it.tokens)} tokens)`}                        onMouseEnter={() => setHoverRemoveId(it.id)}                        onMouseLeave={() => setHoverRemoveId((cur) => (cur === it.id ? null : cur))}                        onFocus={() => setHoverRemoveId(it.id)}                        onBlur={() => setHoverRemoveId((cur) => (cur === it.id ? null : cur))}                        onClick={() => void handleRemove(it.id)}                        className={`flex size-6 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                      >                        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">                          <path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />                        </svg>                      </button>                    ) : null}                  </div>                </li>              ))}            </ul>          )}          {/* Quick-feed context pills (click to feed the creature!) */}          {onAdd && availableSuggestions.length > 0 && (            <div className="mt-2.5 flex flex-wrap gap-1.5 border-t border-border/70 pt-2.5">              {availableSuggestions.map((s) => {                const wouldOverflow = used + s.tokens > limit;                return (                  <button                    key={s.id}                    type="button"                    onClick={() => void handleAdd(s)}                    className={`inline-flex cursor-pointer items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-[12px] font-medium text-foreground hover:bg-muted ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}                    title={wouldOverflow ? "Exceeds context limit" : `Attach ${s.label}`}                  >                    <span aria-hidden="true" className="text-muted-foreground">+</span>                    <span className="max-w-[130px] truncate">{s.label}</span>                    <span className="font-mono text-[11px] text-muted-foreground tabular-nums">                      {formatPlainTokens(s.tokens)}                    </span>                  </button>                );              })}            </div>          )}        </div>        {/* Footer Compact action */}        {onCompact && (          <div className="px-2 pb-1 pt-3">            <div              onMouseEnter={() => setHoverCompact(true)}              onMouseLeave={() => setHoverCompact(false)}            >              <StatusButton                variant={heavy ? "primary" : "outline"}                status={compactStatus}                disabled={compactableTokens === 0 && compactStatus === "idle"}                labels={{                  idle: compactableTokens > 0 ? compactLabel : "Already compact",                  pending: "Compacting",                  success: "Compacted",                  error: "Try again",                }}                onClick={() => void handleCompact()}                className="h-10 w-full text-[13.5px]"                style={heavy && compactStatus !== "error" ? LIT : undefined}              />            </div>          </div>        )}      </div>    </section>  );}export default ContextWindow;

Registry item: /r/context-window.json