"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;