AI Reasoning
Show the thinking: a shimmering disclosure with a timer, a thought trail on a rail, and a one-line ticker beside a thinking face.
"use client"
import * as React from "react"
import { Brain, ChevronRight, ChevronUp } from "lucide-react"
import {
AiKitStyles,
AiStyle,
cx,
Face,
Roll,
type AiShape,
type AiTone,
} from "@/lib/ai-kit"
const CSS = `
.aik-rs-disc{display:grid;gap:10px;width:min(100%,380px);min-height:228px;align-content:start}
.aik-rs-head{display:inline-flex;align-items:center;gap:7px;height:28px;justify-self:start;font-size:13px;color:var(--aik-text-2)}
.aik-rs-head > .ic:first-child{color:var(--aik-purple)}
.aik-rs-label{font-weight:500}
.aik-rs-time{font:11.5px var(--aik-mono);color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-rs-disc[data-st="done"] .aik-rs-time{display:none}
.aik-rs-chev{color:var(--aik-text-3);transition:transform var(--aik-d-state) var(--aik-ease-out)}
.aik-rs-disc[data-open="true"]:not([data-leaving]) .aik-rs-chev{transform:rotate(90deg)}
.aik-rs-body{display:grid;gap:6px;padding-left:13px;margin-left:7px;border-left:1.5px solid var(--aik-line-2);color:var(--aik-text-2);font-size:13px;line-height:19px}
.aik-rs-disc[data-open="false"] .aik-rs-body{display:none}
.aik-rs-disc[data-leaving] .aik-rs-body{animation:aik-out var(--aik-d-exit) var(--aik-ease-in) both}
.aik-rs-ans{font-size:14.5px;line-height:23px;display:none}
.aik-rs-disc[data-ans] .aik-rs-ans{display:block;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-rs-tw{display:grid;width:min(100%,360px);min-height:208px;align-content:start}
.aik-rs-tw > *{grid-area:1/1;align-self:start}
.aik-rs-trail{display:grid}
.aik-rs-li{position:relative;display:grid;grid-template-columns:8px minmax(0,1fr) auto;gap:12px;align-items:start;padding-block:7px;font-size:13.5px;line-height:20px;color:var(--aik-text-2)}
.aik-rs-li::before,.aik-rs-li::after{content:"";position:absolute;left:3.25px;top:23px;bottom:-9px;inline-size:1.5px}
.aik-rs-li::after{background:var(--aik-line-2)}
.aik-rs-li::before{z-index:1;background:var(--aik-text-3);transform:scaleY(0);transform-origin:50% 0;transition:transform var(--aik-d-panel) var(--aik-ease-out)}
.aik-rs-li:last-child::before,.aik-rs-li:last-child::after{display:none}
.aik-rs-li[data-st="done"]::before{transform:none}
.aik-rs-dot{inline-size:8px;block-size:8px;margin-top:6px;border-radius:50%;background:var(--aik-text-3);position:relative;transition:background var(--aik-d-state)}
.aik-rs-li[data-st="cur"]{color:var(--aik-text)}
.aik-rs-li[data-st="cur"] .aik-rs-dot{background:var(--aik-blue)}
.aik-rs-li[data-st="cur"] .aik-rs-dot::after{content:"";position:absolute;inset:-4px;border-radius:50%;border:1.5px solid var(--aik-blue);animation:aik-rs-ping 1.2s var(--aik-ease-out) infinite}
@keyframes aik-rs-ping{from{opacity:.7;transform:scale(.6)}to{opacity:0;transform:scale(1.25)}}
@media (prefers-reduced-motion: reduce){.aik-rs-li[data-st="cur"] .aik-rs-dot::after{animation:none;opacity:.4}}
.aik-rs-li em{font:11.5px/20px var(--aik-mono);font-style:normal;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-rs-tw[data-leaving] .aik-rs-trail{animation:aik-out var(--aik-d-exit) var(--aik-ease-in) both}
.aik-rs-tw[data-st="sum"] .aik-rs-trail{visibility:hidden}
.aik-rs-sum{display:inline-flex;align-items:center;gap:10px;height:36px;padding:0 10px 0 12px;border-radius:12px;background:var(--aik-card);box-shadow:var(--aik-sh-card);justify-self:start;font-size:13px;visibility:hidden}
.aik-rs-tw[data-st="sum"] .aik-rs-sum{visibility:visible;animation:aik-pop var(--aik-d-enter) var(--aik-ease-out) both}
.aik-rs-mini{display:inline-flex;gap:4px}
.aik-rs-mini i{inline-size:6px;block-size:6px;border-radius:50%;background:var(--aik-text-3)}
.aik-rs-sum b{font-weight:500}
.aik-rs-sum span:not(.aik-rs-mini){font:11.5px var(--aik-mono);color:var(--aik-text-3)}
.aik-rs-sum .ic{color:var(--aik-text-3)}
.aik-rs-tick{display:grid;gap:10px;width:min(100%,360px);padding:12px 14px 12px 12px;border-radius:18px;background:var(--aik-card);box-shadow:var(--aik-sh-pop)}
.aik-rs-trow{display:flex;align-items:center;gap:12px;min-width:0}
.aik-rs-trow .aik-face{--aik-fs:36px}
.aik-rs-tcol{display:grid;gap:1px;flex:1;min-width:0}
.aik-rs-tcol .aik-roll{inline-size:100%;font-size:14px;line-height:20px;font-weight:500}
.aik-rs-tn{font:11.5px var(--aik-mono);color:var(--aik-text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
.aik-rs-segs{display:grid;grid-template-columns:repeat(5,1fr);gap:4px}
.aik-rs-segs i{block-size:3px;border-radius:2px;background:var(--aik-line-2);position:relative;overflow:hidden}
.aik-rs-segs i::after{content:"";position:absolute;inset:0;background:var(--aik-purple);transform:scaleX(0);transform-origin:0 50%;transition:transform var(--aik-d-move) var(--aik-ease-out)}
.aik-rs-segs i[data-on]::after{transform:none}
.aik-rs-tick[data-st="done"] .aik-rs-segs i::after{background:var(--aik-green)}
.aik-rs-head{border-radius:8px}
.aik-rs-body p{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both;animation-delay:calc(min(var(--i,0),8)*var(--aik-stagger))}
.aik-rs-li{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-rs-sum{transition:transform var(--aik-d-press) var(--aik-ease-out)}
.aik-rs-sum:active{transform:scale(.97)}
.aik-rs-fold{justify-self:start;margin:6px 0 0 14px}
.aik-rs-tw[data-st="sum"] .aik-rs-fold{display:none}
.aik-rs-tw{grid-template-columns:minmax(0,1fr)}
.aik-rs-wrap{display:grid;align-content:start}
`
/** How long a leaving element stays mounted, matching `--aik-d-exit`. */
const EXIT_MS = 160
/** Controlled-or-not open state whose close plays a leave before it lands. */
function useFold(
controlled: boolean | undefined,
fallback: boolean,
onChange?: (open: boolean) => void
) {
const [own, setOwn] = React.useState(fallback)
const [leaving, setLeaving] = React.useState(false)
const open = controlled ?? own
const timer = React.useRef<number | undefined>(undefined)
React.useEffect(() => () => window.clearTimeout(timer.current), [])
const set = React.useCallback(
(next: boolean) => {
window.clearTimeout(timer.current)
const commit = () => {
setLeaving(false)
setOwn(next)
onChange?.(next)
}
const still = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches
if (next || still) return commit()
setLeaving(true)
timer.current = window.setTimeout(commit, EXIT_MS)
},
[onChange]
)
return { open, leaving, set, setOwn }
}
export interface AiReasoningProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The reasoning so far, one line per entry. */
thoughts: string[]
/** `thinking` shimmers the label and shows the timer; `done` folds the lines away. */
status: "thinking" | "done"
/** Elapsed time while thinking, already formatted. */
elapsed?: string
/** The label once done, such as "Thought for 4s". */
summary?: string
/** Controls the disclosure. Omit to let it open while thinking and fold when done. */
open?: boolean
onOpenChange?: (open: boolean) => void
/** The answer that follows the reasoning. */
children?: React.ReactNode
}
/** A disclosure for reasoning: live while the agent thinks, one line you can reopen afterwards. */
export function AiReasoning({
thoughts,
status,
elapsed,
summary = "Thought it through",
open: controlled,
onOpenChange,
children,
className,
...rest
}: AiReasoningProps) {
const id = React.useId()
const thinking = status === "thinking"
const { open, leaving, set, setOwn } = useFold(
controlled,
thinking,
onOpenChange
)
const seen = React.useRef(status)
React.useEffect(() => {
if (seen.current === status) return
seen.current = status
if (status === "done") set(false)
else setOwn(true)
}, [status, set, setOwn])
return (
<div
{...rest}
className={cx("aik aik-rs-disc", className)}
data-st={status}
data-open={open}
data-leaving={leaving ? "" : undefined}
data-ans={children ? "" : undefined}
>
<AiKitStyles />
<AiStyle id="ai-reasoning" css={CSS} />
<button
type="button"
className="aik-rs-head"
aria-expanded={open && !leaving}
aria-controls={id}
onClick={() => set(!open || leaving)}
>
<Brain size={16} className="ic" />
<span className={cx("aik-rs-label", thinking && "aik-shimmer")}>
{thinking ? "Thinking" : summary}
</span>
{thinking && elapsed ? (
<span className="aik-rs-time">{elapsed}</span>
) : null}
<ChevronRight size={14} className="aik-rs-chev" />
</button>
<div className="aik-rs-body" id={id} aria-live="polite">
{thoughts.map((line, at) => (
<p key={at} style={{ "--i": at } as React.CSSProperties}>
{line}
</p>
))}
</div>
{children ? <div className="aik-rs-ans">{children}</div> : null}
</div>
)
}
export interface AiThought {
text: string
/** How long this thought took, already formatted. */
time?: string
}
export interface AiThoughtTrailProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The thoughts that have arrived, in order. */
thoughts: AiThought[]
/** Index of the thought in progress. Pass `thoughts.length` once all are finished. */
current: number
/** Total thinking time for the summary, already formatted. */
total?: string
/** Controls the summary state. Omit to let the trail manage it. */
collapsed?: boolean
onCollapsedChange?: (collapsed: boolean) => void
}
/** Thoughts on a rail: each ticks in beside a dot, and the finished trail folds to a summary. */
export function AiThoughtTrail({
thoughts,
current,
total,
collapsed: controlled,
onCollapsedChange,
className,
...rest
}: AiThoughtTrailProps) {
const id = React.useId()
const finished = current >= thoughts.length && thoughts.length > 0
const invert = React.useCallback(
(open: boolean) => onCollapsedChange?.(!open),
[onCollapsedChange]
)
const { open, leaving, set } = useFold(
controlled === undefined ? undefined : !controlled,
true,
invert
)
return (
<div
{...rest}
className={cx("aik aik-rs-tw", className)}
data-st={open ? "live" : "sum"}
data-leaving={leaving ? "" : undefined}
>
<AiKitStyles />
<AiStyle id="ai-reasoning" css={CSS} />
<div className="aik-rs-wrap" id={id}>
<ol className="aik-rs-trail" aria-live="polite">
{thoughts.map((thought, at) => (
<li
key={at}
className="aik-rs-li"
data-st={at < current ? "done" : at === current ? "cur" : "todo"}
>
<i className="aik-rs-dot" />
<span>{thought.text}</span>
{thought.time ? <em>{thought.time}</em> : <em />}
</li>
))}
</ol>
{finished ? (
<button
type="button"
className="aik-btn sm ghost aik-rs-fold"
aria-expanded="true"
aria-controls={id}
onClick={() => set(false)}
>
<ChevronUp size={14} />
Collapse
</button>
) : null}
</div>
<button
type="button"
className="aik-rs-sum"
aria-expanded="false"
aria-controls={id}
tabIndex={open ? -1 : 0}
onClick={() => set(true)}
>
<span className="aik-rs-mini">
{thoughts.slice(0, 6).map((_, at) => (
<i key={at} />
))}
</span>
<b>
{thoughts.length} {thoughts.length === 1 ? "thought" : "thoughts"}
</b>
{total ? <span>{total}</span> : null}
<ChevronRight size={14} className="ic" />
</button>
</div>
)
}
export interface AiThoughtTickerProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"children"
> {
/** The small line above the thought, such as "Odo is thinking". */
label: string
/** The thought in progress. Rolls over in place when it changes. */
thought: string
/** How many steps are complete, counting the current one. */
step: number
/** How many steps there are in total. */
steps?: number
status?: "thinking" | "done"
/** Face colour: a named tone or any CSS colour. */
tone?: AiTone | (string & {})
shape?: AiShape
}
/** No disclosure at all: one line that rolls through the current thought beside a thinking face. */
export function AiThoughtTicker({
label,
thought,
step,
steps = 5,
status = "thinking",
tone = "violet",
shape = "blob",
className,
...rest
}: AiThoughtTickerProps) {
const done = status === "done"
return (
<div
{...rest}
className={cx("aik aik-rs-tick", className)}
data-st={done ? "done" : "live"}
role="status"
>
<AiKitStyles />
<AiStyle id="ai-reasoning" css={CSS} />
<div className="aik-rs-trow">
<Face
size={36}
mood={done ? "happy" : "think"}
tone={tone}
shape={shape}
/>
<div className="aik-rs-tcol">
<span className="aik-label">{label}</span>
<Roll>{thought}</Roll>
</div>
<span className="aik-rs-tn">
{Math.min(step, steps)} / {steps}
</span>
</div>
<div
className="aik-rs-segs"
style={{ gridTemplateColumns: `repeat(${steps}, 1fr)` }}
>
{Array.from({ length: steps }, (_, at) => (
<i key={at} data-on={at < step ? "" : undefined} />
))}
</div>
</div>
)
}
Installation
One command adds ai-reasoning and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.
"use client"
import * as React from "react"
import { AiDemo } from "@/lib/ai-demo"
import { useAiLoop } from "@/lib/ai-kit"
import {
AiReasoning,
AiThoughtTicker,
AiThoughtTrail,
type AiThought,
} from "@/registry/tween/ai-reasoning"
const clock = (seconds: number) => `0:${String(seconds).padStart(2, "0")}`
const LINES = [
"The hero has one headline and a paragraph under it.",
"Revealing both would compete, so animate the headline only.",
"text-skew-reveal is already installed. No new dependency.",
]
function Disclosure() {
const root = React.useRef<HTMLDivElement>(null)
const [count, setCount] = React.useState(LINES.length)
const [status, setStatus] = React.useState<"thinking" | "done">("thinking")
const [seconds, setSeconds] = React.useState(3)
const [answer, setAnswer] = React.useState(false)
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setAnswer(false)
setStatus("thinking")
setCount(0)
setSeconds(0)
for (let at = 1; at <= LINES.length; at++) {
await sleep(650)
setCount(at)
await sleep(650)
setSeconds(at)
}
await sleep(900)
setSeconds(4)
setStatus("done")
await sleep(450)
setAnswer(true)
await sleep(2800)
},
{ gap: 500, enabled: !hands }
)
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 380px)" }}
onPointerDown={() => {
setHands(true)
setCount(LINES.length)
setStatus("done")
setAnswer(true)
}}
>
<AiReasoning
thoughts={LINES.slice(0, count)}
status={status}
elapsed={clock(seconds)}
summary="Thought for 4s"
>
{answer
? "I will reveal the headline only and leave the paragraph still."
: null}
</AiReasoning>
</div>
)
}
const TRAIL: AiThought[] = [
{ text: "Read the hero and its props", time: "0.6s" },
{ text: "Compared three reveal components", time: "1.1s" },
{ text: "Checked reduced motion handling", time: "0.5s" },
{ text: "Choosing the stagger value", time: "0.9s" },
]
function Trail() {
const root = React.useRef<HTMLDivElement>(null)
const [count, setCount] = React.useState(TRAIL.length)
const [current, setCurrent] = React.useState(TRAIL.length - 1)
const [collapsed, setCollapsed] = React.useState(false)
const [hands, setHands] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setCollapsed(false)
setCount(0)
setCurrent(0)
await sleep(500)
for (let at = 0; at < TRAIL.length; at++) {
setCount(at + 1)
setCurrent(at)
await sleep(1100)
}
setCurrent(TRAIL.length)
await sleep(1100)
setCollapsed(true)
await sleep(2400)
},
{ gap: 500, enabled: !hands }
)
return (
<div
ref={root}
style={{ display: "grid", width: "min(100%, 360px)" }}
onPointerDown={() => {
setHands(true)
setCount(TRAIL.length)
setCurrent(TRAIL.length)
}}
>
<AiThoughtTrail
thoughts={TRAIL.slice(0, count)}
current={current}
total="3.1s"
collapsed={collapsed}
onCollapsedChange={setCollapsed}
/>
</div>
)
}
const TICKS = [
"Reading the hero section",
"Listing reveal components",
"Comparing three eases",
"Checking reduced motion",
"Choosing the stagger value",
]
function Ticker() {
const root = React.useRef<HTMLDivElement>(null)
const [step, setStep] = React.useState(3)
const [done, setDone] = React.useState(false)
useAiLoop(
root,
async ({ sleep }) => {
setDone(false)
for (let at = 1; at <= TICKS.length; at++) {
setStep(at)
await sleep(1300)
}
setDone(true)
await sleep(2000)
},
{ gap: 500 }
)
return (
<div ref={root} style={{ display: "grid", width: "min(100%, 360px)" }}>
<AiThoughtTicker
label={done ? "Odo is ready" : "Odo is thinking"}
thought={done ? "Stagger set to 0.05s" : (TICKS[step - 1] ?? "")}
step={step}
steps={TICKS.length}
status={done ? "done" : "thinking"}
/>
</div>
)
}
export function AiReasoningDemo({ only }: { only?: string }) {
return (
<AiDemo
only={only}
tabs={[
{ name: "Disclosure", node: <Disclosure /> },
{ name: "Thought trail", node: <Trail /> },
{ name: "Ticker", node: <Ticker /> },
]}
/>
)
}
Installation
Usage
import {
AiReasoning,
AiThoughtTicker,
AiThoughtTrail,
} from "@/components/ui/ai-reasoning"<AiReasoning
thoughts={lines}
status={thinking ? "thinking" : "done"}
elapsed="0:03"
summary="Thought for 4s"
>
I will reveal the headline only.
</AiReasoning>With the AI SDK, split the message's reasoning part into lines for thoughts and use its state for status.
Versions
AiReasoningis a disclosure. While thinking, the label shimmers beside a timer and lines stagger in. Whenstatusturnsdoneit fades out and folds tosummary; the button reopens it, andaria-expandedfollows.AiThoughtTrailputs each thought beside a dot on a rail. The current dot pings blue and the rail fills behind finished thoughts. Once everything is done it can fold to a summary chip that reopens the trail.AiThoughtTickerhas no disclosure. One line rolls through the current thought beside a thinking face, with a segment per step.
Props
AiReasoning
| Prop | Type | Default | Description |
|---|---|---|---|
thoughts | string[] | The reasoning so far, one line per entry. | |
status | "thinking" | "done" | Thinking shimmers the label; done folds the lines. | |
elapsed | string | Elapsed time while thinking. | |
summary | string | "Thought it through" | The label once done. |
open | boolean | Controls the disclosure. Omit to let it manage itself. | |
onOpenChange | (open: boolean) => void | Called when the disclosure opens or closes. | |
children | ReactNode | The answer shown under the reasoning. |
AiThoughtTrail
| Prop | Type | Default | Description |
|---|---|---|---|
thoughts | { text, time? }[] | The thoughts that have arrived. | |
current | number | Index of the thought in progress, or the length when all are done. | |
total | string | Total time for the summary chip. | |
collapsed | boolean | Controls the summary state. | |
onCollapsedChange | (collapsed: boolean) => void | Called when the trail folds or reopens. |
AiThoughtTicker
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | The small line above the thought. | |
thought | string | The thought in progress. Rolls on change. | |
step | number | Steps complete, counting the current one. | |
steps | number | 5 | Total steps. |
status | "thinking" | "done" | "thinking" | Done turns the segments green. |