wordle-five: the engine, the reward, the solver and the probe that checks them
The Python is the source of truth; src/demos/wordle/engine.ts will be a port of it, and CI gates the two against a SHA-256 over all 21.2M (guess, answer) pattern pairs rather than a hand-picked vector file — a vector file only ever catches the cases somebody thought of. The reward is three weighted components, and the third one is the reason this demo is worth building. `solved` and `economy` pull toward winning. `consistency` pulls against them, because a player maximising information deliberately guesses words that cannot win — a word that splits the remaining candidates evenly teaches more than a word that might happen to be right. That is good play, and it costs consistency. The probe ladder proves the tension is real rather than asserted: inaction 0.0000 crude 0.0111 plausible 0.1224 candidate_only 0.8925 exhaustive 0.9031 oracle 0.9458 The two good policies are 0.05 apart and neither dominates — the entropy oracle takes 1.00 economy and 0.73 consistency, the candidate-only player takes 0.75 and 1.00. Which one wins is a decision about what you want, which is the whole argument the site exists to make. probe.py fails CI if either starts dominating. Two traps found by building it. `consistency` is scored over turns SPENT, not guesses accepted: counting only legal guesses hands a free 1.0 to a policy that plays one word and then jams the parser five times — one guess, no contradictions, perfect score. And `economy`'s denominator is the depth the SHIPPED solver reaches, not a depth-optimal search: entropy-greedy is not depth-optimal, so grading it against an exact optimum would make the oracle rung fail its own assertion on some seeds. The word lists are built from Wordnik (MIT) intersected with SCOWL, never from the original game's 2,315 answers. 4,603 answers makes this materially harder than the original, so the published SALET/3.4212 results are cited as belonging to that list and our own reference player's TARES/3.72 is measured here. verifiers is an optional extra. The engine, reward, solver and probe all run — and gate — without an RL stack resolvable. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019mt6sHQHEnEYrJZvoMCJSB
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { StoryBeat } from '@/lib/demo-kit/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface BeatSectionProps {
|
||||
beat: StoryBeat;
|
||||
/** 1-based. The narrative is numbered so a reader can be told "see beat 3". */
|
||||
number: number;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One beat of the exec narrative: a number, a title, a claim, and the surface
|
||||
* that makes the claim true.
|
||||
*
|
||||
* The claim is typeset as an assertion — large, high contrast, above the
|
||||
* evidence — because the failure mode of a demo site is a visitor watching a
|
||||
* pretty animation and never learning what it was supposed to prove.
|
||||
*/
|
||||
export function BeatSection({ beat, number, children, className }: BeatSectionProps) {
|
||||
const headingId = `beat-${beat.id}-title`;
|
||||
return (
|
||||
<section
|
||||
id={beat.id}
|
||||
aria-labelledby={headingId}
|
||||
data-surface={beat.surface}
|
||||
className={cn('scroll-mt-[var(--app-header-h)] py-10 lg:py-14', className)}
|
||||
>
|
||||
<header className="mb-6 lg:mb-8">
|
||||
<div className="flex items-baseline gap-3">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="nums select-none text-sm font-semibold tabular-nums text-accent-fg"
|
||||
>
|
||||
{String(number).padStart(2, '0')}
|
||||
</span>
|
||||
<h2 id={headingId} className="text-xl font-semibold tracking-tight lg:text-2xl">
|
||||
{beat.title}
|
||||
</h2>
|
||||
</div>
|
||||
<p className="mt-3 max-w-2xl text-pretty text-lg leading-snug text-fg lg:text-xl">
|
||||
{beat.claim}
|
||||
</p>
|
||||
</header>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Component } from 'react';
|
||||
import type { ErrorInfo, ReactNode } from 'react';
|
||||
import { AlertTriangle, ExternalLink, RotateCcw } from 'lucide-react';
|
||||
|
||||
const REPO_URL = 'https://github.com/karti-ai/PIG-Demo';
|
||||
|
||||
export interface DemoErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
/** Named in the fallback copy, so the visitor knows what broke. */
|
||||
demoTitle?: string;
|
||||
/** Link to the exact source, if the caller knows it. Falls back to the repo. */
|
||||
sourceHref?: string;
|
||||
/** Called when the visitor asks to try again; use it to reset shell state. */
|
||||
onReset?: () => void;
|
||||
}
|
||||
|
||||
interface DemoErrorBoundaryState {
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One broken demo must never take the site down.
|
||||
*
|
||||
* This is a class because there is still no hook for `componentDidCatch`; that
|
||||
* is the entire reason for the exception to the function-component rule here.
|
||||
*
|
||||
* The fallback is deliberately calm and specific. A site whose pitch is
|
||||
* "here are the receipts" cannot answer a crash with a shrug: it names the
|
||||
* demo, links the source, and lets the visitor retry without a full reload.
|
||||
*/
|
||||
export class DemoErrorBoundary extends Component<DemoErrorBoundaryProps, DemoErrorBoundaryState> {
|
||||
override state: DemoErrorBoundaryState = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error): DemoErrorBoundaryState {
|
||||
return { error };
|
||||
}
|
||||
|
||||
override componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
// No telemetry endpoint on a static site, and none is wanted. The console
|
||||
// is the only place a maintainer can see this, so keep the component stack.
|
||||
console.error('[pig-demo] a demo surface threw', error, info.componentStack);
|
||||
}
|
||||
|
||||
private handleReset = () => {
|
||||
this.setState({ error: null });
|
||||
this.props.onReset?.();
|
||||
};
|
||||
|
||||
override render() {
|
||||
const { error } = this.state;
|
||||
if (!error) return this.props.children;
|
||||
|
||||
const { demoTitle, sourceHref } = this.props;
|
||||
return (
|
||||
<div role="alert" className="card mx-auto my-10 max-w-xl p-6">
|
||||
<div className="flex items-center gap-2 text-warning">
|
||||
<AlertTriangle className="h-5 w-5" aria-hidden="true" />
|
||||
<h2 className="text-base font-semibold">
|
||||
{demoTitle ? `${demoTitle} failed to render` : 'This demo failed to render'}
|
||||
</h2>
|
||||
</div>
|
||||
<p className="mt-3 text-sm leading-relaxed text-muted">
|
||||
Something in this demo threw while drawing. The rest of the site is unaffected — every
|
||||
other demo is a separate module. The environment and the recorded runs behind this page
|
||||
are in the repository either way, and you can run them yourself.
|
||||
</p>
|
||||
<p className="mt-3 break-words rounded-lg bg-surface-2 px-3 py-2 font-mono text-xs text-muted">
|
||||
{error.message || 'Unknown error'}
|
||||
</p>
|
||||
<div className="mt-5 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={this.handleReset}
|
||||
className="tap inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors duration-2 ease-enter hover:bg-primary/90"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" aria-hidden="true" />
|
||||
Try again
|
||||
</button>
|
||||
<a
|
||||
href={sourceHref ?? REPO_URL}
|
||||
className="tap inline-flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium transition-colors duration-2 ease-enter hover:bg-surface-2"
|
||||
>
|
||||
Read the source
|
||||
<ExternalLink className="h-4 w-4" aria-hidden="true" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { ArrowRight, ListChecks, Scale, Target, TrendingUp } from 'lucide-react';
|
||||
import type { DemoModule } from '@/lib/demo-kit/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type Anatomy = DemoModule['anatomy'];
|
||||
|
||||
export interface EnvAnatomyProps {
|
||||
anatomy: Anatomy;
|
||||
/** `DemoMeta.rewardLine` — six words on what the reward pays for. */
|
||||
rewardLine?: string;
|
||||
/** Set on the gallery/overview page, where the four boxes are context rather
|
||||
* than the lesson, to drop the closing line and tighten the type. */
|
||||
compact?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface Box {
|
||||
key: keyof Anatomy;
|
||||
kicker: string;
|
||||
question: string;
|
||||
Icon: LucideIcon;
|
||||
}
|
||||
|
||||
/**
|
||||
* The four boxes, in the order an executive builds the mental model: what is
|
||||
* being asked, what the agent is allowed to do, who decides whether it was
|
||||
* good, and what number that decision moves.
|
||||
*
|
||||
* The kickers are deliberately generic. This object is the site's one piece of
|
||||
* transferable explanation: someone who learns the machine on a word game
|
||||
* should read the fraud demo as "same machine, different grader", and that only
|
||||
* works if the four labels never change between demos.
|
||||
*/
|
||||
const BOXES: Box[] = [
|
||||
{ key: 'task', kicker: 'The task', question: 'What is the agent asked to do?', Icon: Target },
|
||||
{
|
||||
key: 'actions',
|
||||
kicker: 'Legal actions',
|
||||
question: 'What is it allowed to do?',
|
||||
Icon: ListChecks,
|
||||
},
|
||||
{
|
||||
key: 'grader',
|
||||
kicker: 'The grader',
|
||||
question: 'Who decides whether it was good?',
|
||||
Icon: Scale,
|
||||
},
|
||||
{
|
||||
key: 'score',
|
||||
kicker: 'The score that moves',
|
||||
question: 'What number does that produce?',
|
||||
Icon: TrendingUp,
|
||||
},
|
||||
];
|
||||
|
||||
export function EnvAnatomy({ anatomy, rewardLine, compact = false, className }: EnvAnatomyProps) {
|
||||
return (
|
||||
<div className={cn('space-y-4', className)}>
|
||||
<ol className="flex flex-col lg:flex-row lg:items-stretch">
|
||||
{BOXES.map((box, index) => (
|
||||
<li
|
||||
key={box.key}
|
||||
className="flex flex-col items-stretch lg:flex-1 lg:flex-row lg:items-center"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'card flex flex-1 flex-col gap-2 p-4',
|
||||
// The grader is the box every later demo differs on. It is the
|
||||
// one the eye should land on second, after the task.
|
||||
box.key === 'grader' && 'border-brand/40 bg-accent-subtle/40',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-accent-subtle text-accent-fg">
|
||||
<box.Icon className="h-4 w-4" strokeWidth={2} aria-hidden="true" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold leading-tight">
|
||||
<span className="nums mr-1.5 text-muted">{index + 1}</span>
|
||||
{box.kicker}
|
||||
</p>
|
||||
{!compact ? (
|
||||
<p className="text-xs leading-tight text-muted">{box.question}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<p className={cn('text-pretty text-fg', compact ? 'text-xs' : 'text-sm')}>
|
||||
{anatomy[box.key]}
|
||||
</p>
|
||||
</div>
|
||||
{index < BOXES.length - 1 ? (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="flex items-center justify-center py-2 text-muted lg:px-2 lg:py-0"
|
||||
>
|
||||
<ArrowRight className="h-4 w-4 rotate-90 lg:rotate-0" />
|
||||
</div>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{rewardLine ? (
|
||||
<p className="text-sm text-muted">
|
||||
<span className="font-medium text-fg">This reward: </span>
|
||||
{rewardLine}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!compact ? (
|
||||
<p className="max-w-3xl text-pretty text-sm leading-relaxed text-muted">
|
||||
Every demo on this site is that same machine. The task changes, the legal actions
|
||||
change, and the grader changes — but the grader is always code you can read, and the
|
||||
score is always a number you can watch move. That is what makes an environment
|
||||
different from an eval:{' '}
|
||||
<span className="font-medium text-fg">
|
||||
an environment is an eval you can take the gradient of.
|
||||
</span>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* The sanctioned extension seam.
|
||||
*
|
||||
* A demo that needs something the shell does not have has two options: fork the
|
||||
* shell, or drop it into a slot. This is the second one. Slots are named and
|
||||
* finite, so `check-demos` can see what a demo added and reviewers can see it
|
||||
* in a diff — which is the whole reason this exists rather than letting demos
|
||||
* pass arbitrary children into arbitrary components.
|
||||
*
|
||||
* A slot with nothing in it renders NOTHING, not an empty box: the layout must
|
||||
* not shift depending on whether a demo opted in.
|
||||
*/
|
||||
export type SlotId =
|
||||
| 'hero-aside'
|
||||
| 'below-board'
|
||||
| 'beside-reward'
|
||||
| 'below-timeline'
|
||||
| 'before-limits'
|
||||
| 'after-receipts';
|
||||
|
||||
export interface SlotRegionProps {
|
||||
id: SlotId;
|
||||
/**
|
||||
* Announced to assistive tech when the slot has content. Omit for purely
|
||||
* decorative additions; a region with no label is not exposed as a landmark.
|
||||
*/
|
||||
label?: string;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SlotRegion({ id, label, children, className }: SlotRegionProps) {
|
||||
// `children` can be `false`/`null` from a demo's own conditional. Treat those
|
||||
// as "no slot content" rather than rendering a labelled empty region.
|
||||
if (children === null || children === undefined || children === false) return null;
|
||||
|
||||
if (!label) {
|
||||
return (
|
||||
<div data-slot={id} className={className}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section data-slot={id} aria-label={label} className={cn('contents', className)}>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type StatTone = 'default' | 'positive' | 'warning' | 'danger' | 'info' | 'brand';
|
||||
|
||||
export interface Stat {
|
||||
/** Short. Two or three words; it sits above the number. */
|
||||
label: string;
|
||||
value: ReactNode;
|
||||
/** One clarifying line, shown under the number at a smaller size. */
|
||||
hint?: string;
|
||||
tone?: StatTone;
|
||||
/** Set when this number was derived under an edited reward, not recorded. */
|
||||
edited?: boolean;
|
||||
}
|
||||
|
||||
export interface StatStripProps {
|
||||
stats: Stat[];
|
||||
className?: string;
|
||||
/** Announce changes as they happen. Off by default — the shell owns the
|
||||
* page's single live region and two competing ones talk over each other. */
|
||||
live?: boolean;
|
||||
}
|
||||
|
||||
const TONE: Record<StatTone, string> = {
|
||||
default: 'text-fg',
|
||||
positive: 'text-positive',
|
||||
warning: 'text-warning',
|
||||
danger: 'text-danger',
|
||||
info: 'text-info',
|
||||
brand: 'text-accent-fg',
|
||||
};
|
||||
|
||||
/**
|
||||
* A row of headline numbers. Scrolls horizontally on a phone rather than
|
||||
* wrapping into a ragged grid: four stats reflowing to 2x2 at 390px puts the
|
||||
* least important number in the most prominent corner.
|
||||
*/
|
||||
export function StatStrip({ stats, className, live = false }: StatStripProps) {
|
||||
if (stats.length === 0) return null;
|
||||
return (
|
||||
<dl
|
||||
className={cn(
|
||||
'flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1',
|
||||
'sm:grid sm:snap-none sm:overflow-visible sm:pb-0',
|
||||
stats.length <= 2 ? 'sm:grid-cols-2' : 'sm:grid-cols-3 lg:grid-cols-4',
|
||||
className,
|
||||
)}
|
||||
{...(live ? { 'aria-live': 'polite' as const } : {})}
|
||||
>
|
||||
{stats.map((stat) => (
|
||||
<div
|
||||
key={stat.label}
|
||||
className="card min-w-[9.5rem] flex-1 shrink-0 snap-start px-4 py-3"
|
||||
>
|
||||
<dt className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted">
|
||||
<span className="truncate">{stat.label}</span>
|
||||
{stat.edited ? <EditedChip /> : null}
|
||||
</dt>
|
||||
<dd
|
||||
className={cn(
|
||||
'nums mt-1 text-2xl font-semibold leading-tight',
|
||||
TONE[stat.tone ?? 'default'],
|
||||
)}
|
||||
>
|
||||
{stat.value}
|
||||
</dd>
|
||||
{stat.hint ? <dd className="mt-0.5 text-xs text-muted">{stat.hint}</dd> : null}
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a number the visitor caused rather than one we recorded. It appears on
|
||||
* every derived value in the reward editor; without it, an edited ranking
|
||||
* screenshots identically to a measured one.
|
||||
*/
|
||||
export function EditedChip({ className }: { className?: string }) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-md bg-accent-subtle px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent-fg',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
edited
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Circle, Pause, Play, RotateCcw } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatDate, usePrefersReducedMotion } from './format';
|
||||
|
||||
/** `instant` is not "very fast": it is "do not animate, show me the end". */
|
||||
export type PlaybackSpeed = 1 | 2 | 4 | 'instant';
|
||||
|
||||
export const PLAYBACK_SPEEDS: readonly PlaybackSpeed[] = [1, 2, 4, 'instant'];
|
||||
|
||||
/** Wall-clock dwell on a step at 1x. Not the model's real latency — see below. */
|
||||
const BASE_STEP_MS = 1800;
|
||||
|
||||
export interface UseTracePlaybackOptions {
|
||||
stepCount: number;
|
||||
step: number;
|
||||
onStepChange: (next: number) => void;
|
||||
/**
|
||||
* Dwell time for one step at 1x, in ms. Defaults to a fixed cadence rather
|
||||
* than the recorded `durationMs`, and that is deliberate: real calls run from
|
||||
* 300 ms to half a minute, so replaying at true latency produces a player
|
||||
* that appears frozen. The recorded latency is still shown, verbatim, in the
|
||||
* model-call panel — it is reported, just not used as a timeline.
|
||||
*/
|
||||
stepDurationMs?: (index: number) => number;
|
||||
initialSpeed?: PlaybackSpeed;
|
||||
}
|
||||
|
||||
export interface TracePlayback {
|
||||
playing: boolean;
|
||||
speed: PlaybackSpeed;
|
||||
setPlaying: (playing: boolean) => void;
|
||||
setSpeed: (speed: PlaybackSpeed) => void;
|
||||
toggle: () => void;
|
||||
restart: () => void;
|
||||
atEnd: boolean;
|
||||
}
|
||||
|
||||
export function useTracePlayback({
|
||||
stepCount,
|
||||
step,
|
||||
onStepChange,
|
||||
stepDurationMs,
|
||||
initialSpeed = 1,
|
||||
}: UseTracePlaybackOptions): TracePlayback {
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [speed, setSpeedState] = useState<PlaybackSpeed>(initialSpeed);
|
||||
const atEnd = step >= stepCount - 1;
|
||||
|
||||
// The callback identity changes on every render of the shell; holding it in a
|
||||
// ref keeps it out of the timer effect's deps, or the timer restarts on every
|
||||
// render and the step never lands.
|
||||
const onStepChangeRef = useRef(onStepChange);
|
||||
onStepChangeRef.current = onStepChange;
|
||||
|
||||
const setSpeed = useCallback(
|
||||
(next: PlaybackSpeed) => {
|
||||
setSpeedState(next);
|
||||
if (next === 'instant') {
|
||||
setPlaying(false);
|
||||
onStepChangeRef.current(Math.max(stepCount - 1, 0));
|
||||
}
|
||||
},
|
||||
[stepCount],
|
||||
);
|
||||
|
||||
const restart = useCallback(() => {
|
||||
onStepChangeRef.current(0);
|
||||
setPlaying(stepCount > 1);
|
||||
}, [stepCount]);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
if (stepCount <= 1) return;
|
||||
setPlaying((was) => {
|
||||
if (was) return false;
|
||||
// Pressing play at the end replays from the top rather than doing
|
||||
// nothing, which is what every visitor expects and nobody says out loud.
|
||||
if (step >= stepCount - 1) onStepChangeRef.current(0);
|
||||
return true;
|
||||
});
|
||||
}, [step, stepCount]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing || speed === 'instant' || stepCount <= 1) return;
|
||||
if (step >= stepCount - 1) {
|
||||
setPlaying(false);
|
||||
return;
|
||||
}
|
||||
const base = stepDurationMs?.(step) ?? BASE_STEP_MS;
|
||||
const timer = window.setTimeout(() => {
|
||||
onStepChangeRef.current(step + 1);
|
||||
}, Math.max(base / speed, 120));
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [playing, speed, step, stepCount, stepDurationMs]);
|
||||
|
||||
return { playing, speed, setPlaying, setSpeed, toggle, restart, atEnd };
|
||||
}
|
||||
|
||||
export interface TracePlayerProps {
|
||||
playing: boolean;
|
||||
onPlayingChange: (playing: boolean) => void;
|
||||
speed: PlaybackSpeed;
|
||||
onSpeedChange: (speed: PlaybackSpeed) => void;
|
||||
onRestart: () => void;
|
||||
step: number;
|
||||
stepCount: number;
|
||||
onStepChange: (next: number) => void;
|
||||
/** Straight off the run: never a marketing name for the model. */
|
||||
model: string;
|
||||
capturedAt: string;
|
||||
/** Present only on an `intervened` run; the contract requires it there. */
|
||||
intervention?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transport controls for a recorded rollout.
|
||||
*
|
||||
* There is no spinner anywhere in this component and there never should be. A
|
||||
* spinner implies a request is in flight; nothing here is live, and an exec who
|
||||
* believes they are watching a model think in real time has been misled by the
|
||||
* UI rather than the copy. Hence the permanent badge — it is not a disclosure
|
||||
* we tuck into a footnote, it sits in the transport bar for the whole session.
|
||||
*/
|
||||
export function TracePlayer({
|
||||
playing,
|
||||
onPlayingChange,
|
||||
speed,
|
||||
onSpeedChange,
|
||||
onRestart,
|
||||
step,
|
||||
stepCount,
|
||||
onStepChange,
|
||||
model,
|
||||
capturedAt,
|
||||
intervention,
|
||||
className,
|
||||
}: TracePlayerProps) {
|
||||
const reducedMotion = usePrefersReducedMotion();
|
||||
const canPlay = stepCount > 1;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'card flex flex-wrap items-center gap-x-3 gap-y-2 p-2 sm:gap-x-4',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="tap grid place-items-center rounded-lg text-muted transition-colors duration-2 ease-enter hover:bg-surface-2 hover:text-fg disabled:opacity-40"
|
||||
onClick={() => onStepChange(Math.max(step - 1, 0))}
|
||||
disabled={step <= 0}
|
||||
aria-label="Previous step"
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tap grid place-items-center rounded-lg bg-primary px-4 text-primary-foreground transition-colors duration-2 ease-enter hover:bg-primary/90 disabled:opacity-40"
|
||||
onClick={() => onPlayingChange(!playing)}
|
||||
disabled={!canPlay}
|
||||
aria-label={playing ? 'Pause the recorded run' : 'Play the recorded run'}
|
||||
aria-keyshortcuts="Space"
|
||||
>
|
||||
{playing ? (
|
||||
<Pause className="h-5 w-5" aria-hidden="true" />
|
||||
) : (
|
||||
<Play className="h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tap grid place-items-center rounded-lg text-muted transition-colors duration-2 ease-enter hover:bg-surface-2 hover:text-fg disabled:opacity-40"
|
||||
onClick={() => onStepChange(Math.min(step + 1, Math.max(stepCount - 1, 0)))}
|
||||
disabled={step >= stepCount - 1}
|
||||
aria-label="Next step"
|
||||
>
|
||||
<ChevronRight className="h-5 w-5" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tap grid place-items-center rounded-lg text-muted transition-colors duration-2 ease-enter hover:bg-surface-2 hover:text-fg"
|
||||
onClick={onRestart}
|
||||
aria-label="Restart from the first step"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="nums text-sm text-muted">
|
||||
Step <span className="font-semibold text-fg">{Math.min(step + 1, stepCount)}</span> of{' '}
|
||||
{stepCount}
|
||||
</p>
|
||||
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label="Playback speed"
|
||||
className="flex items-center gap-0.5 rounded-lg bg-surface-2 p-0.5"
|
||||
>
|
||||
{PLAYBACK_SPEEDS.map((option) => {
|
||||
const selected = option === speed;
|
||||
return (
|
||||
<button
|
||||
key={String(option)}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
onClick={() => onSpeedChange(option)}
|
||||
className={cn(
|
||||
'min-h-9 rounded-md px-2.5 text-xs font-medium transition-colors duration-2 ease-enter',
|
||||
selected
|
||||
? 'bg-surface text-fg shadow-sm'
|
||||
: 'text-muted hover:text-fg',
|
||||
)}
|
||||
>
|
||||
{option === 'instant' ? 'Instant' : `${option}x`}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<RecordedBadge model={model} capturedAt={capturedAt} intervention={intervention} />
|
||||
|
||||
{reducedMotion ? (
|
||||
// Not an apology — a statement that the page is behaving as asked. The
|
||||
// steps still advance; only the tile flips and slides are gone.
|
||||
<p className="sr-only">
|
||||
Reduced motion is on. Steps still advance and every change is announced.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface RecordedBadgeProps {
|
||||
model: string;
|
||||
capturedAt: string;
|
||||
intervention?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RecordedBadge({
|
||||
model,
|
||||
capturedAt,
|
||||
intervention,
|
||||
className,
|
||||
}: RecordedBadgeProps) {
|
||||
return (
|
||||
<p
|
||||
className={cn(
|
||||
'ml-auto flex flex-wrap items-center gap-x-1.5 gap-y-1 rounded-lg bg-surface-2 px-2.5 py-1.5 text-xs text-muted',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Circle className="h-2 w-2 shrink-0 fill-muted text-muted" aria-hidden="true" />
|
||||
<span className="font-medium text-fg">Recorded run</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className="nums font-mono">{model}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className="nums">{formatDate(capturedAt)}</span>
|
||||
{intervention ? (
|
||||
<span className="rounded-md bg-accent-subtle px-1.5 py-0.5 font-medium text-accent-fg">
|
||||
{intervention}
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Formatting and environment hooks shared by every shell component.
|
||||
*
|
||||
* Numbers on this site are evidence, so formatting is centralised: an exec who
|
||||
* sees `0.81` in one panel and `0.812` in the next assumes one of them is
|
||||
* rounded in someone's favour. Everything that renders a recorded number goes
|
||||
* through here, and everything that renders one wears `.nums`.
|
||||
*/
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
|
||||
/**
|
||||
* A missing recorded number is an em dash, never a zero. `0` is a measurement;
|
||||
* `—` is the absence of one, and the difference is the whole point of the site.
|
||||
*/
|
||||
export const DASH = '—';
|
||||
|
||||
export function formatNumber(value: number, digits = 3): string {
|
||||
if (!Number.isFinite(value)) return DASH;
|
||||
return value.toFixed(digits);
|
||||
}
|
||||
|
||||
export function formatOrDash(value: number | null | undefined, digits = 3): string {
|
||||
return value === null || value === undefined ? DASH : formatNumber(value, digits);
|
||||
}
|
||||
|
||||
export function formatInt(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return DASH;
|
||||
// en-US grouping is pinned rather than taken from the visitor: the page is
|
||||
// prerendered, and a locale-dependent separator makes the built HTML and the
|
||||
// hydrated DOM disagree.
|
||||
return value.toLocaleString('en-US');
|
||||
}
|
||||
|
||||
export function formatMs(ms: number | null | undefined): string {
|
||||
if (ms === null || ms === undefined || !Number.isFinite(ms)) return DASH;
|
||||
if (ms < 1000) return `${Math.round(ms)} ms`;
|
||||
return `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The verification delta. Seven decimals is not decoration: it is the number
|
||||
* that tells a sceptical engineer we compared floats rather than strings.
|
||||
*/
|
||||
export function formatDelta(delta: number): string {
|
||||
if (!Number.isFinite(delta)) return DASH;
|
||||
// -0 prints as "-0.0000000" and reads like a failure. Normalise it.
|
||||
const normalised = Object.is(delta, -0) ? 0 : delta;
|
||||
return normalised.toFixed(7);
|
||||
}
|
||||
|
||||
export function formatSigned(value: number, digits = 2): string {
|
||||
if (!Number.isFinite(value)) return DASH;
|
||||
const sign = value > 0 ? '+' : '';
|
||||
return `${sign}${value.toFixed(digits)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `2026-08-12` and `2026-08-12T09:31:00Z` both render as `12 Aug 2026`.
|
||||
* Formatted in UTC on purpose: a bare ISO date parses as midnight UTC, and a
|
||||
* visitor west of Greenwich would otherwise see the day before the capture.
|
||||
*/
|
||||
export function formatDate(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return iso;
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
});
|
||||
}
|
||||
|
||||
/** `finish_reason` values are snake_case off the wire; humans read spaces. */
|
||||
export function humaniseToken(token: string): string {
|
||||
return token.replace(/[_-]+/g, ' ');
|
||||
}
|
||||
|
||||
function subscribeToQuery(query: string) {
|
||||
return (onChange: () => void) => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return () => {};
|
||||
const list = window.matchMedia(query);
|
||||
list.addEventListener('change', onChange);
|
||||
return () => list.removeEventListener('change', onChange);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Media queries as React state. `useSyncExternalStore` rather than an effect,
|
||||
* because the server snapshot is explicit: the prerendered HTML is built at the
|
||||
* desktop, motion-allowed default and corrects itself on the client.
|
||||
*/
|
||||
export function useMediaQuery(query: string, serverValue = false): boolean {
|
||||
const subscribe = useCallback(subscribeToQuery(query), [query]);
|
||||
const getSnapshot = useCallback(() => {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return serverValue;
|
||||
return window.matchMedia(query).matches;
|
||||
}, [query, serverValue]);
|
||||
return useSyncExternalStore(subscribe, getSnapshot, () => serverValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduced motion is not only a CSS concern here. The CSS clamps transitions,
|
||||
* but the trace player and the reasoning stream are JS timers: they have to
|
||||
* resolve to their final state immediately, or a visitor who asked for no
|
||||
* motion gets the animation anyway, just without the easing.
|
||||
*/
|
||||
export function usePrefersReducedMotion(): boolean {
|
||||
return useMediaQuery('(prefers-reduced-motion: reduce)');
|
||||
}
|
||||
|
||||
/** The one breakpoint the shell branches on: the drawer/panel split. */
|
||||
export function useIsDesktop(): boolean {
|
||||
return useMediaQuery('(min-width: 1024px)', true);
|
||||
}
|
||||
|
||||
/** Clamp that also copes with a NaN out of `Number(searchParam)`. */
|
||||
export function clampIndex(value: number, length: number): number {
|
||||
if (!Number.isFinite(value) || length <= 0) return 0;
|
||||
return Math.min(Math.max(Math.trunc(value), 0), length - 1);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Resolving `DemoMeta.icon` — a lucide export NAME — to a component.
|
||||
*
|
||||
* The obvious implementations are both wrong, and both were tried:
|
||||
*
|
||||
* `import * as lucide from 'lucide-react'` — kills tree-shaking. Every icon
|
||||
* in the library (~1,500) lands in a chunk to render twelve of them.
|
||||
*
|
||||
* `import('lucide-react/dynamicIconImports')` — correct at runtime, but the
|
||||
* map holds a dynamic import per icon, so Rollup emits ~1,500 chunk files
|
||||
* into `dist/` for a static site that serves twelve.
|
||||
*
|
||||
* So the shell keeps an explicit registry. Adding a demo means adding its icon
|
||||
* here; that is one line, and in exchange the entry chunk stays honest. An
|
||||
* unknown name renders the neutral fallback rather than throwing, because a
|
||||
* typo in a demo's metadata must not take the gallery down.
|
||||
*/
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import {
|
||||
Blocks,
|
||||
Boxes,
|
||||
Braces,
|
||||
Building2,
|
||||
ClipboardCheck,
|
||||
Code,
|
||||
Cpu,
|
||||
Database,
|
||||
FileSearch,
|
||||
Gauge,
|
||||
Grid3x3,
|
||||
HeartPulse,
|
||||
Landmark,
|
||||
LifeBuoy,
|
||||
MessagesSquare,
|
||||
Package,
|
||||
PhoneCall,
|
||||
Plug,
|
||||
Radio,
|
||||
Receipt,
|
||||
Scale,
|
||||
ShieldCheck,
|
||||
ShoppingCart,
|
||||
Stethoscope,
|
||||
Truck,
|
||||
Wallet,
|
||||
Workflow,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
|
||||
const REGISTRY: Record<string, LucideIcon> = {
|
||||
Blocks,
|
||||
Boxes,
|
||||
Braces,
|
||||
Building2,
|
||||
ClipboardCheck,
|
||||
Code,
|
||||
Cpu,
|
||||
Database,
|
||||
FileSearch,
|
||||
Gauge,
|
||||
Grid3x3,
|
||||
HeartPulse,
|
||||
Landmark,
|
||||
LifeBuoy,
|
||||
MessagesSquare,
|
||||
Package,
|
||||
PhoneCall,
|
||||
Plug,
|
||||
Radio,
|
||||
Receipt,
|
||||
Scale,
|
||||
ShieldCheck,
|
||||
ShoppingCart,
|
||||
Stethoscope,
|
||||
Truck,
|
||||
Wallet,
|
||||
Workflow,
|
||||
Zap,
|
||||
};
|
||||
|
||||
export const FallbackDemoIcon: LucideIcon = Boxes;
|
||||
|
||||
/** Every icon name the shell can render, for `check-demos` to assert against. */
|
||||
export const KNOWN_ICON_NAMES: readonly string[] = Object.keys(REGISTRY);
|
||||
|
||||
export function resolveDemoIcon(name: string | undefined): LucideIcon {
|
||||
if (!name) return FallbackDemoIcon;
|
||||
return REGISTRY[name] ?? FallbackDemoIcon;
|
||||
}
|
||||
|
||||
export interface DemoIconProps {
|
||||
/** A lucide export name from `DemoMeta.icon`, e.g. `Grid3x3`. */
|
||||
name: string | undefined;
|
||||
className?: string;
|
||||
/** Icons here are always decorative — the label beside them carries the name. */
|
||||
strokeWidth?: number;
|
||||
}
|
||||
|
||||
export function DemoIcon({ name, className, strokeWidth = 1.75 }: DemoIconProps) {
|
||||
const Icon = resolveDemoIcon(name);
|
||||
return <Icon className={className} strokeWidth={strokeWidth} aria-hidden="true" />;
|
||||
}
|
||||
Reference in New Issue
Block a user