AI Context Meter

How full the context window is: a tank of liquid that rises toward the limit, a hundred blocks filled by category, and a rim meter that squeezes back when you compact.

Installation

Installation

One command adds ai-meter and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.

$npx shadcn@latest add https://tweenui.dev/r/ai-meter.json
ai-meter-demo
components/ui/ai-meter-demo.tsx
"use client"

import * as React from "react"

import { AiDemo } from "@/lib/ai-demo"
import { AiStyle, Face, useAiLoop, useIdleHands } from "@/lib/ai-kit"
import {
  AiCompactMarker,
  AiContextBlocks,
  AiContextRim,
  AiContextTank,
  type AiContextSegment,
} from "@/registry/tween/ai-meter"

const CSS = `
.aik-mtd-turn{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;font-size:15px;line-height:24px}
.aik-mtd-turn p{padding-top:2px;color:var(--aik-text)}
.aik-mtd-user{justify-self:end;max-width:78%;padding:10px 16px;border-radius:18px;background:var(--aik-raised);font-size:15px;line-height:22px}
`

const LIMIT = 200_000

const TANK_STEPS: Array<[number, string]> = [
  [68_000, "Loaded 6 files"],
  [104_000, "Three tool results"],
  [142_000, "Long conversation"],
  [166_000, "Past the tidy point"],
  [188_000, "Time to compact"],
]

const WRAP: React.CSSProperties = { display: "grid", width: "min(100%, 560px)" }

function Tank() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [used, setUsed] = React.useState(104_000)
  const [note, setNote] = React.useState("Tools returned 3 results")

  useAiLoop(
    root,
    async ({ sleep }) => {
      setUsed(36_000)
      setNote("System and rules")
      await sleep(1100)
      for (const [value, line] of TANK_STEPS) {
        setUsed(value)
        setNote(line)
        await sleep(1500)
      }
      await sleep(500)
      setUsed(72_000)
      setNote("Compacted 116k tokens")
      await sleep(2400)
    },
    { gap: 500, enabled: !hands, still: () => setUsed(166_000) }
  )

  return (
    <div ref={root} style={WRAP} onPointerDown={touch} onKeyDown={touch}>
      <AiContextTank
        used={used}
        limit={LIMIT}
        note={note}
        onAdd={() => {
          setUsed((value) => Math.min(LIMIT, value + 24_000))
          setNote("Added 24k of files")
        }}
        onCompact={() => {
          setUsed((value) => Math.max(30_000, Math.round(value * 0.4)))
          setNote("Compacted older messages")
        }}
      />
    </div>
  )
}

const seg = (
  system: number,
  files: number,
  chat: number,
  tools: number
): AiContextSegment[] => [
  { id: "system", label: "System and rules", tokens: system, tone: "ink" },
  { id: "files", label: "Files", tokens: files, tone: "blue" },
  { id: "chat", label: "Conversation", tokens: chat, tone: "violet" },
  { id: "tools", label: "Tool results", tokens: tools, tone: "teal" },
]

const BLOCK_STEPS: Array<[AiContextSegment[], string]> = [
  [seg(12_000, 0, 4_000, 0), "A fresh session"],
  [seg(12_000, 38_000, 10_000, 0), "Loaded 6 files"],
  [seg(12_000, 52_000, 22_000, 18_000), "Tools returned 18k"],
  [seg(12_000, 60_000, 46_000, 44_000), "Getting full"],
]

function Blocks() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [segments, setSegments] = React.useState(BLOCK_STEPS[2]![0])
  const [note, setNote] = React.useState("Tools returned 18k")

  useAiLoop(
    root,
    async ({ sleep }) => {
      for (const [value, line] of BLOCK_STEPS) {
        setSegments(value)
        setNote(line)
        await sleep(1900)
      }
      setSegments(seg(12_000, 60_000, 14_000, 6_000))
      setNote("Compacted 70k tokens")
      await sleep(2600)
    },
    { gap: 400, enabled: !hands, still: () => setSegments(BLOCK_STEPS[3]![0]) }
  )

  return (
    <div ref={root} style={WRAP} onPointerDown={touch} onKeyDown={touch}>
      <AiContextBlocks
        segments={segments}
        limit={LIMIT}
        note={note}
        onCompact={() => {
          setSegments((list) =>
            list.map((item) =>
              item.id === "chat" || item.id === "tools"
                ? { ...item, tokens: Math.round(item.tokens * 0.25) }
                : item
            )
          )
          setNote("Folded older messages and results")
        }}
      />
    </div>
  )
}

function Rim() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [used, setUsed] = React.useState(96_000)
  const [freed, setFreed] = React.useState(0)

  const compact = () => {
    const next = Math.round(used * 0.36)
    setFreed(used - next)
    setUsed(next)
  }

  useAiLoop(
    root,
    async ({ sleep }) => {
      setFreed(0)
      setUsed(96_000)
      await sleep(1300)
      setUsed(138_000)
      await sleep(1300)
      setUsed(172_000)
      await sleep(2200)
      setFreed(110_000)
      setUsed(62_000)
      await sleep(3000)
    },
    { gap: 500, enabled: !hands, still: () => setUsed(172_000) }
  )

  return (
    <div ref={root} style={WRAP} onPointerDown={touch} onKeyDown={touch}>
      <AiContextRim
        used={used}
        limit={LIMIT}
        placeholder="Ask Mira to keep going"
        onCompact={compact}
      >
        <div className="aik-mtd-user">Now add the yearly toggle.</div>
        {freed > 0 ? <AiCompactMarker tokens={freed} /> : null}
        <div className="aik-mtd-turn">
          <Face size={28} shape="orb" mood={freed > 0 ? "happy" : "talk"} />
          <p>
            The toggle is in. Prices switch with a 180ms state change and the
            saving badge rolls over.
          </p>
        </div>
      </AiContextRim>
    </div>
  )
}

export function AiMeterDemo({ only }: { only?: string }) {
  return (
    <>
      <AiStyle id="ai-meter-demo" css={CSS} />
      <AiDemo
        only={only}
        tabs={[
          { name: "Tank", node: <Tank /> },
          { name: "Blocks", node: <Blocks /> },
          { name: "Rim meter", node: <Rim /> },
        ]}
      />
    </>
  )
}

Installation

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-meter.json

Usage

import {
  AiCompactMarker,
  AiContextBlocks,
  AiContextRim,
  AiContextTank,
} from "@/components/ui/ai-meter"
<AiContextTank
  used={142_000}
  limit={200_000}
  note="Long conversation"
  onCompact={compact}
/>
 
<AiContextBlocks
  limit={200_000}
  segments={[
    { id: "system", label: "System and rules", tokens: 12_000, tone: "ink" },
    { id: "files", label: "Files", tokens: 52_000, tone: "blue" },
    { id: "chat", label: "Conversation", tokens: 22_000, tone: "violet" },
  ]}
  onCompact={compact}
/>
 
<AiContextRim used={172_000} limit={200_000} onCompact={compact}>
  <AiCompactMarker tokens={110_000} />
</AiContextRim>

Versions

  • AiContextTank is the window as a vessel. Liquid rises to the share in use behind a drifting wave, turns amber past the tidy point and red near the top, and dips when a compaction drains it.
  • AiContextBlocks is a hundred cells, one per percent. Cells fill in each part's colour with a stagger, so you can see which part is growing. Compacting dissolves cells and the rest repack.
  • AiContextRim is the meter where it lives, in the rim under a composer. A thin bar carries a tick at the tidy point; past it the rim turns amber and offers Compact. Put AiCompactMarker in the thread to show where older messages were folded.

All three take plain numbers and work at any value, including zero and over the limit. formatTokens is exported for your own labels.

Props

AiContextTank

PropTypeDefaultDescription
usednumberTokens in the window now.
limitnumberThe window's size in tokens.
tidyAtnumber0.75Share of the window past which it warns.
notestringA line under the figure. Rolls when it changes.
onCompact() => voidCalled by the Compact action.
onAdd() => voidCalled by Add context. The button hides when omitted.

AiContextBlocks

PropTypeDefaultDescription
segments{ id, label, tokens, tone }[]What fills the window, in fill order.
limitnumberThe window's size in tokens.
notestringA line beside the Compact action.
onCompact() => voidCalled by the Compact action.

AiContextRim

PropTypeDefaultDescription
usednumberTokens in the window now.
limitnumberThe window's size in tokens.
tidyAtnumber0.8Where the tick sits and the warning starts.
placeholderstring"Ask a follow-up"The mock field's text.
onCompact() => voidCalled by the Compact button in the rim.
childrenReactNodeThe thread above, including AiCompactMarker.