# Context window

> 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.

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.

## Install

```bash
npx shadcn@latest add @hairline/context-window
```

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

- npm: none
- Hairline UI components it needs (the CLI installs them too): `number-roll`, `status-button`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/context-window
- Registry item (source): https://hairlineui.com/r/context-window.json

## Usage

```tsx
import { ContextWindow } from "@/components/context-window";

<ContextWindow
  items={contextItems}
  limit={200_000}
  material="plush"
  onRemove={(id) => dropItem(id)}
  onCompact={() => compactThread()}
/>
```

## 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.

```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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `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" \| "clay" \| "jelly"` | `"plush"` | Real-time WebGL2 surface: volumetric fur, matte clay with poke dents, or refracted jelly. |
| `tone` | `"coral" \| "lilac" \| "peach" \| "mint" \| "sky" \| "butter" \| "primary"` | `"coral"` | Colour palette; "primary" reads shadcn --primary dynamically. |
| `onCompact / compactLabel` | `() => Promise<unknown> / string` | `— / "Compact memory"` | 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` | `string` | `— / "Munch"` | Quiet model badge beside the title, and the creature’s name in status copy. |

## 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.

## What it handles

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.

- **Inflates and presses the walls**: The WebGL2 SDF creature scales continuously with used / limit and smoothly flattens against the alcove walls past 90%.
- **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.
- **Overflow belly bounce**: Attaching an item that exceeds limit rebounds off the creature with a steam burst and “Too full — compact first”.
- **Hover anticipation**: Hovering any file’s remove button draws its gaze downward and previews slight relief before you click.
- **Compaction squeeze**: onCompact squeezes the creature inward while pending, then pops it free with sparkles as NumberRoll drops the count.
- **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.

## Replaces

a token usage meter, a context breakdown list, an overflow guard, a /compact action button, a mascot or sprite rig

## Where it fits

- **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.

## Notes

- 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.

License: MIT (https://hairlineui.com/license#components)
