Thinking UI

Thinking

A live reasoning trace: the current step, a running timer, then it folds into “Thought for Ns”.

Code

components/thinking-ui/thinking.tsx
"use client";

import { AnimatePresence, motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { TextShimmer } from "@/components/thinking-ui/text-shimmer";
import { useMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";

export type ThinkingStatus = "thinking" | "done" | "stopped";

export type ThinkingProps = {
  /** thinking: still reasoning. done: finished. stopped: the user ended it early. */
  status: ThinkingStatus;
  /** What the model is doing right now, e.g. "Reading the calendar". Shimmers while thinking; swaps as it changes. */
  label?: string;
  /** Shown as “Thought for Ns” once done. Leave it out to show the time measured while thinking. */
  seconds?: number;
  /** The reasoning trace. Can keep growing while thinking. */
  children: ReactNode;
  defaultOpen?: boolean;
  /** Open while thinking so the trace can be watched, then fold away once done or stopped. */
  autoOpen?: boolean;
  className?: string;
};

export function Thinking({ status, label, seconds, children, defaultOpen = false, autoOpen = false, className }: ThinkingProps) {
  const m = useMotion();
  const contentId = useId();
  const thinking = status === "thinking";
  const elapsed = useElapsed(thinking);
  const [open, setOpen] = useState(defaultOpen || (autoOpen && thinking));

  // Follow the status when asked to; adjusted during render so the panel never paints in the old state
  const [seen, setSeen] = useState(status);
  if (seen !== status) {
    setSeen(status);
    if (autoOpen) setOpen(thinking);
  }

  const total = seconds ?? elapsed;
  const heading =
    status === "thinking" ? label ?? "Thinking…" : status === "stopped" ? "Stopped thinking" : total > 0 ? `Thought for ${total}s` : "Thought";

  return (
    <div className={cn("text-sm", className)}>
      <button
        type="button"
        aria-expanded={open}
        aria-controls={contentId}
        onClick={() => setOpen((o) => !o)}
        className="transition-ui relative inline-flex items-center gap-1.5 text-fg-muted hover:text-fg"
      >
        <AnimatePresence mode="popLayout" initial={false}>
          {/* Keyed by the text, so every new step slides in like the one before it slid out */}
          <motion.span key={heading} {...m.swap()} className="inline-flex items-center gap-1.5">
            {thinking ? <TextShimmer>{heading}</TextShimmer> : heading}
          </motion.span>
        </AnimatePresence>
        {thinking && elapsed > 0 && <span className="font-mono text-xs tabular-nums text-fg-muted">{elapsed}s</span>}
        <motion.svg
          aria-hidden
          viewBox="0 0 16 16"
          className="size-icon-sm"
          animate={{ rotate: open ? 90 : 0 }}
          transition={m.spring("micro")}
        >
          <path d="M6 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </motion.svg>
      </button>

      <AnimatePresence initial={false}>
        {open && (
          <motion.div id={contentId} className="overflow-hidden" {...m.collapse()}>
            <Trace live={thinking}>{children}</Trace>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

/**
 * The reasoning text. While it streams in, it shows a short window pinned to the newest line with the
 * older lines fading out at the top; once thinking ends, the whole trace opens to its full height.
 */
function Trace({ live, children }: { live: boolean; children: ReactNode }) {
  const m = useMotion();
  const box = useRef<HTMLDivElement>(null);
  const [overflowing, setOverflowing] = useState(false);

  useLayoutEffect(() => {
    const el = box.current;
    const inner = el?.firstElementChild;
    if (!el || !inner || !live) return;
    const pin = () => {
      el.scrollTop = el.scrollHeight;
      setOverflowing(el.scrollHeight > el.clientHeight + 1);
    };
    pin();
    const ro = new ResizeObserver(pin);
    ro.observe(inner);
    return () => ro.disconnect();
  }, [live]);

  const fade = live && overflowing ? "linear-gradient(to bottom, transparent, #000 2.5rem)" : undefined;

  return (
    <motion.div
      ref={box}
      className="mt-2 overflow-hidden border-l border-line pl-3"
      initial={false}
      animate={{ maxHeight: live ? 128 : 1200 }}
      transition={m.spring("layout")}
      style={{ maskImage: fade, WebkitMaskImage: fade }}
    >
      <div className="leading-relaxed text-fg-tertiary">{children}</div>
    </motion.div>
  );
}

/** Whole seconds since `running` last turned on; holds its value once it turns off. */
function useElapsed(running: boolean) {
  const [elapsed, setElapsed] = useState(0);
  useEffect(() => {
    if (!running) return;
    const start = performance.now();
    // eslint-disable-next-line react-hooks/set-state-in-effect -- a new run starts the count from zero
    setElapsed(0);
    const id = setInterval(() => setElapsed(Math.floor((performance.now() - start) / 1000)), 250);
    return () => clearInterval(id);
  }, [running]);
  return elapsed;
}

Motion notes

  • Each new step label slides in with a short vertical slide and blur, so the status change reads as progress.
  • While thinking, the trace shows a short window pinned to the newest line, with older lines fading out at the top.
  • With autoOpen it opens while thinking and folds away when done, on a zero-bounce spring that never overshoots.
  • Stopping early reads as “Stopped thinking”, neutral rather than an error.

Installation

  1. 1

    Install dependencies

    Terminal
    npm install motion clsx tailwind-merge
  2. 2

    Add the design tokens and motion system (once per project)

    Copy styles/tokens/*, lib/motion.tsx and lib/utils.ts from Get started.

  3. 3

    Add the components it uses

    Text Shimmer

  4. 4

    Paste the source into components/thinking-ui/thinking.tsx

    Copy it from the Code tab, or use Copy prompt to let your coding agent do all of this.

Usage

Example
<Thinking status={status} label={step} autoOpen>
  <StreamingText text={reasoning} streaming={status === "thinking"} />
</Thinking>

Props

PropTypeDefaultDescription
status"thinking" | "done" | "stopped"—Current reasoning state. stopped: the user ended it early.
labelstring—What the model is doing now, e.g. “Reading the calendar”. Shimmers while thinking.
secondsnumber—Shown as “Thought for Ns” when done. Defaults to the time measured while thinking.
childrenReactNode—The reasoning trace. Can keep growing while thinking.
autoOpenbooleanfalseOpen while thinking, fold away once done or stopped.
defaultOpenbooleanfalseStart expanded.