Model picker
Every model streams the same answer at once, at its own real speed. The bars are time, so the race reads at a glance, and the answer streams in full beneath them for the model you point at, with what one task costs.
npx shadcn@latest add https://uimaxxer.com/r/model-picker.jsonPasskeysFix the duplicate Stripe charge
Which model should take this one?
Captain
Why does the Stripe webhook charge twice on retry?
Every model streams this answer: The retry handler charges again because it keys on the request, not the Stripe event. Store event.id before charging and return 200 if you have seen it. I would also move the email send after the commit, so a rollback never mails a receipt.
"use client";
// uimaxxer · Model picker, MIT. Idea: every model streams the same answer at once, at its own real speed, so the pick is a race you watch: bars are time, and the answer streams in full beneath them for the model you point at. Delight: each lane's finish time turns from grey to ink the instant its last word lands, and the fastest is marked.
import { useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import { cx } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
export type PickerModel = {
id: string;
name: string;
/** Output tokens per second. */
tps: number;
/** Time to first token, ms. */
ttft: number;
/** US dollars per million input and output tokens. */
input: number;
output: number;
};
type ModelPickerProps = {
models: PickerModel[];
value?: string;
defaultValue?: string;
onValueChange?: (id: string) => void;
/** The answer every model streams, so only the speed differs. */
sample: string;
/** The task the cost is quoted for, in tokens. */
task: { label: string; input: number; output: number };
/** What was asked, shown above the race. */
prompt?: string;
"aria-label"?: string;
className?: string;
};
const TOKENS_PER_WORD = 1.3;
const money = (n: number) => (n === 0 ? "Free" : n < 0.1 ? `$${n.toFixed(3)}` : `$${n.toFixed(2)}`);
export const costPerTask = (m: PickerModel, t: { input: number; output: number }) => (t.input * m.input + t.output * m.output) / 1e6;
/** Words shown and seconds on the clock for one model, t ms after the start. */
function lane(m: PickerModel, words: string[], spoken: number, t: number) {
const perWord = (1000 * TOKENS_PER_WORD) / m.tps;
const total = m.ttft + perWord * spoken;
const said = t < m.ttft ? 0 : Math.min(spoken, Math.floor((t - m.ttft) / perWord) + 1);
let n = 0;
let seen = 0;
while (n < words.length && seen < said) {
if (words[n]?.trim()) seen++;
n++;
}
return { n: said >= spoken ? words.length : n, said, clock: Math.min(t, total), done: said >= spoken, total };
}
export function ModelPicker({ models, value, defaultValue, onValueChange, sample, task, prompt, className, ...rest }: ModelPickerProps) {
const [inner, setInner] = useState(defaultValue ?? models[0]?.id ?? "");
const picked = value ?? inner;
const words = sample.split(/(\s+)/).filter(Boolean);
const spoken = words.filter((w) => w.trim()).length;
const finish = (m: PickerModel) => m.ttft + ((1000 * TOKENS_PER_WORD) / m.tps) * spoken;
const longest = Math.max(...models.map(finish));
const winner = models.reduce<PickerModel | undefined>((w, m) => (!w || finish(m) < finish(w) ? m : w), undefined)?.id;
// It opens on the finished race, so the result is never blank, then runs it once shortly after load.
const [t, setT] = useState(longest);
const [run, setRun] = useState(0); // bump to race again
// The answer pane follows the pointer or focus, and rests on the picked model.
const [preview, setPreview] = useState<string | null>(null);
const opts = useRef<Array<HTMLButtonElement | null>>([]);
const reduce = useReducedMotion();
const id = useId();
// One clock for the whole race, so every lane starts on the same gun.
useEffect(() => {
if (reduce) {
setT(longest);
return;
}
let raf = 0;
const go = () => {
setT(0);
const t0 = performance.now();
const tick = () => {
const now = performance.now() - t0;
setT(Math.min(now, longest));
if (now < longest) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
};
const wait = setTimeout(go, run === 0 ? 1400 : 0);
return () => {
clearTimeout(wait);
cancelAnimationFrame(raf);
};
}, [run, longest, reduce]);
const select = (m: PickerModel) => {
if (value === undefined) setInner(m.id);
onValueChange?.(m.id);
};
const key = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {
const n = models.length;
const to = e.key === "ArrowDown" ? (i + 1) % n : e.key === "ArrowUp" ? (i - 1 + n) % n : e.key === "Home" ? 0 : e.key === "End" ? n - 1 : -1;
if (to < 0) return;
e.preventDefault();
opts.current[to]?.focus();
};
return (
<div className={cx("@container raised rounded-shell p-2", className)}>
<div className="flex items-center gap-3 px-3 pb-2 pt-1.5">
<p className="min-w-0 flex-1 truncate text-[14px] text-ink-2">{prompt ?? "The same answer from every model"}</p>
<button
type="button"
onClick={() => setRun((r) => r + 1)}
className="pressable relative -mr-1 flex h-8 items-center gap-1.5 rounded-inner px-2.5 text-[13px] font-medium text-ink-2 transition-colors duration-150 before:absolute before:-inset-1.5 before:content-[''] hover:bg-hover hover:text-ink focus-visible:bg-hover"
>
<Icon name="replay" size={15} />
Race again
</button>
</div>
<p id={`${id}-answer`} className="sr-only">
Every model streams this answer: {sample}
</p>
<div
role="listbox"
aria-label={rest["aria-label"] ?? "Model"}
aria-orientation="vertical"
aria-describedby={`${id}-answer`}
className="flex flex-col gap-0.5"
onPointerLeave={() => setPreview(null)}
>
{models.map((m, i) => {
const on = m.id === picked;
const l = lane(m, words, spoken, t);
// The bar is time, not progress: it grows with the race clock and freezes where this model finished,
// so the finished race still reads as a race (short bars won).
const pct = longest ? (l.clock / longest) * 100 : 0;
const first = m.id === winner;
return (
<button
key={m.id}
ref={(el) => {
opts.current[i] = el;
}}
type="button"
role="option"
aria-selected={on}
tabIndex={on ? 0 : -1}
onClick={() => select(m)}
onKeyDown={(e) => key(e, i)}
onPointerEnter={() => setPreview(m.id)}
onFocus={() => setPreview(m.id)}
onBlur={() => setPreview(null)}
className={cx(
"pressable group grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 rounded-inner px-3 py-2 text-left transition-colors duration-150 @[560px]:grid-cols-[7.5rem_minmax(0,1fr)_4.5rem_4rem]",
on ? "bg-hover" : "hover:bg-hover focus-visible:bg-hover",
)}
>
<span className="min-w-0">
<span className="flex items-center gap-1.5 text-[16px] font-medium text-ink">
{m.name}
{on ? <Icon name="check" size={15} /> : null}
</span>
<span className="tnum block text-[12.5px] tracking-[0.005em] text-ink-3">
{m.tps} tokens/s<span className="@[560px]:hidden">, {money(costPerTask(m, task))} a {task.label}</span>
</span>
</span>
{/* The track: a raised bar slides along a recessed well; its length is time. */}
<span aria-hidden="true" className="well relative col-span-2 row-start-2 h-9 overflow-hidden rounded-inner @[560px]:col-span-1 @[560px]:col-start-2 @[560px]:row-start-1">
<span
className={cx("absolute inset-y-[3px] left-[3px] rounded-[6px]", on ? "bg-primary" : "raised [.dark_&]:bg-rim-strong [[data-theme=dark]_&]:bg-rim-strong")}
style={{ width: `calc(${pct}% - 6px * ${pct / 100})`, minWidth: l.said ? 6 : 0 }}
/>
{/* Only a short note rides the bar, never the words: the wait for the first token, then a count, just past the bar's end or inside once the bar can hold it. */}
{!l.done || l.said > 0 ? (
<span
className={cx(
"tnum absolute inset-y-0 flex items-center whitespace-nowrap text-[12.5px]",
pct > 72 ? (on ? "-translate-x-full pr-2.5 text-primary-ink" : "-translate-x-full pr-2.5 text-ink-2") : "pl-2 text-ink-3",
)}
style={{ left: `calc(${pct}% - 6px * ${pct / 100} + 3px)` }}
>
{l.said === 0 ? `first token in ${(m.ttft / 1000).toFixed(1)} s` : `${Math.round(l.said * TOKENS_PER_WORD)} ${Math.round(l.said * TOKENS_PER_WORD) === 1 ? "token" : "tokens"}`}
</span>
) : null}
</span>
{/* Each lane's own finish time, known from its speed: grey while it runs, ink the instant its last word lands. */}
<span className="flex flex-col items-end gap-1 @[560px]:col-start-3">
<span className={cx("tnum display text-right text-[26px] font-semibold leading-none transition-colors duration-150", !l.done ? "text-ink-3" : first ? "text-accent-ink" : "text-ink")}>
{(l.total / 1000).toFixed(1)}
<span className="text-[14px] font-medium tracking-normal"> s</span>
</span>
{first && l.done ? <span className="text-[12px] font-medium text-accent-ink">Fastest</span> : null}
</span>
<span className="tnum hidden text-right text-[13px] text-ink-2 @[560px]:block">{money(costPerTask(m, task))}</span>
</button>
);
})}
</div>
<Answer model={models.find((m) => m.id === (preview ?? picked)) ?? models[0]} words={words} spoken={spoken} t={t} />
</div>
);
}
/** The full answer for one model, wrapped and growing at that model's speed. Its height is fixed, so nothing below moves. */
function Answer({ model, words, spoken, t }: { model?: PickerModel; words: string[]; spoken: number; t: number }) {
if (!model) return null;
const l = lane(model, words, spoken, t);
return (
<div aria-hidden="true" className="well mx-1 mb-1 mt-2 rounded-inner px-4 py-3">
<p className="mb-1 text-[12.5px] text-ink-3">
<span className="font-medium text-ink-2">{model.name}</span>
{l.said === 0 && !l.done ? `, first token in ${(model.ttft / 1000).toFixed(1)} s` : l.done ? `, answered in ${(l.total / 1000).toFixed(1)} s` : ", streaming"}
</p>
{/* The whole answer sits invisible underneath, so the pane is its final height from the first frame. */}
<p className="grid text-[14px] leading-[1.5] text-ink">
<span className="invisible col-start-1 row-start-1">{words.join("")}</span>
<span className="col-start-1 row-start-1">
{words.slice(0, l.n).join("")}
{!l.done ? <span className="ml-px inline-block h-[1.05em] w-[2px] translate-y-[3px] bg-accent" /> : null}
</span>
</p>
</div>
);
}Usage
import { ModelPicker } from "@/components/ui/model-picker"
<ModelPicker
models={[{ id: "fast", name: "Fast", tps: 160, ttft: 250, input: 0.8, output: 4 }]}
sample="Store event.id before charging and return 200 if you have seen it."
task={{ label: "review", input: 18000, output: 1200 }}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| models | { id; name; tps; ttft; input; output }[] | tps is output tokens a second, ttft the wait for the first token in ms, input and output are $ per million tokens. | |
| sample | string | The answer every model streams, so only the speed differs. | |
| task | { label: string; input: number; output: number } | The job the cost is quoted for, in tokens, e.g. one review. | |
| prompt | string | What was asked, shown above the race. | |
| value | string | Controlled model id. | |
| defaultValue | string | models[0].id | Initial model when uncontrolled. |
| onValueChange | (id: string) => void | Called when a model is picked. |
Keyboard
- ↑ ↓
- Move between models
- Enter / Space
- Pick the focused model
Accessibility
- role=listbox with role=option and aria-selected; arrows move focus, Enter picks.
- Each option is named by its model, speed and cost; the streamed text is hidden from screen readers and the full answer is linked once with aria-describedby, so the race never talks over the user.
- Race again is a real button with visible text.
- Reduced motion shows every lane finished at once, with the time each would take.