Aadi

Step Timer

AI chats

About

Live and final durations for each step an agent runs, hidden for quick steps and ticking in whole seconds for long ones.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Step Timer to your project and fits it to your theme.

Code

How Step Timer is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { forwardRef, createElement, type SVGAttributes, type ForwardRefExoticComponent, type RefAttributes } from "react"
import { cn } from "@/lib/utils"
import { StepTimer } from "@/components/ui/step-timer"

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

interface Step {
  label: React.ReactNode
  /** The label while the step runs. */
  active: React.ReactNode
  /** How long the step runs in the demo, so the final time is the time you watched. */
  ms: number
  prefix?: string
}

function Code({ children }: { children: React.ReactNode }) {
  return <code className="font-mono text-[0.92em]">{children}</code>
}

/** An agent fixing a flaky test. Quick steps never flash a counter; long ones tick each second. */
const STEPS: Step[] = [
  { label: "Looked at why it fails only on CI", active: "Thinking", ms: 2300, prefix: "Thought for" },
  { label: <>Read <Code>src/cart/coupon.test.ts</Code></>, active: <>Reading <Code>src/cart/coupon.test.ts</Code></>, ms: 420 },
  { label: <>Searched the code for <Code>applyCoupon</Code></>, active: <>Searching the code for <Code>applyCoupon</Code></>, ms: 780 },
  { label: <>Ran <Code>pnpm test coupon</Code></>, active: <>Running <Code>pnpm test coupon</Code></>, ms: 3400 },
  { label: <>Edited <Code>src/cart/coupon.ts</Code></>, active: <>Editing <Code>src/cart/coupon.ts</Code></>, ms: 560 },
  { label: <>Ran <Code>pnpm test coupon</Code>, 14 passed</>, active: <>Running <Code>pnpm test coupon</Code></>, ms: 2600 },
]

const HOLD_MS = 3200

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

interface IconProps extends SVGAttributes<SVGSVGElement> {
  /** Width and height. Number means px. Default 24. */
  size?: number | string
  /** Stroke width in viewBox units (24 grid). Default 1.5. */
  strokeWidth?: number | string
  /** Keep the rendered stroke at `strokeWidth` px at any size. */
  absoluteStrokeWidth?: boolean
  /** Stroke color. Default currentColor. */
  color?: string
  /** Accessible name. Renders <title> and sets role="img"; without it the icon is aria-hidden. */
  title?: string
}

type Icon = ForwardRefExoticComponent<IconProps & RefAttributes<SVGSVGElement>>

/** Shape elements an icon may contain. */
type IconElement = "path" | "circle" | "rect" | "ellipse" | "line" | "polyline" | "polygon"

/** An icon's drawing: a flat list of [element, attributes] pairs, lucide compatible. */
type IconNode = ReadonlyArray<readonly [IconElement, Readonly<Record<string, string>>]>

const toPascal = (name: string): string =>
  name
    .split("-")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join("")

/**
 * Builds a React icon component from an icon node.
 * `name` is the kebab-case icon name, used for the class `chatcn-icon-<name>` and displayName.
 */
function createIcon(name: string, iconNode: IconNode): Icon {
  // biome-ignore lint/correctness/noComponentHookFactories: runs once per icon at module load
  const Component = forwardRef<SVGSVGElement, IconProps>(function ChatcnIcon(
    {
      size = 24,
      strokeWidth = 1.5,
      absoluteStrokeWidth = false,
      color = "currentColor",
      title,
      className,
      children,
      ...rest
    },
    ref,
  ) {
    const stroke = absoluteStrokeWidth
      ? (Number(strokeWidth) * 24) / Number.parseFloat(String(size))
      : strokeWidth
    const labelled = Boolean(title || rest["aria-label"] || rest["aria-labelledby"])
    return createElement(
      "svg",
      {
        ref,
        xmlns: "http://www.w3.org/2000/svg",
        width: size,
        height: size,
        viewBox: "0 0 24 24",
        fill: "none",
        stroke: color,
        strokeWidth: stroke,
        strokeLinecap: "round",
        strokeLinejoin: "round",
        "data-slot": "icon",
        className: className
          ? `chatcn-icon chatcn-icon-${name} ${className}`
          : `chatcn-icon chatcn-icon-${name}`,
        ...(labelled ? { role: "img" } : { "aria-hidden": true }),
        ...rest,
      },
      title ? createElement("title", null, title) : null,
      ...iconNode.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })),
      children,
    )
  })
  Component.displayName = `${toPascal(name)}Icon`
  return Component
}

const iconNode: IconNode = [
  ["path", {"d":"m4.5 12.75 3.23 3.23a2.5 2.5 0 0 0 3.54 0l8.48-8.48"}],
]

const CheckIcon: Icon = /* @__PURE__ */ createIcon("check", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M12 3a9 9 0 1 1-9 9"}],
]

const LoaderCircleIcon: Icon = /* @__PURE__ */ createIcon("loader-circle", iconNode2)

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * An agent run, step by step: each step's timer stays hidden for its first second, then ticks in
 * whole seconds, then lands on the exact time. Loops.
 */
export default function StepTimerPreview() {
  const reduced = React.useRef(false)
  // `current` is the running step; STEPS.length means the run is done.
  const [run, setRun] = React.useState({ current: 0, startedAt: 0, done: [] as number[] })

  React.useEffect(() => {
    reduced.current = reducedMotion()
    if (reduced.current) {
      setRun({ current: STEPS.length, startedAt: 0, done: STEPS.map((s) => s.ms) })
      return
    }
    setRun({ current: 0, startedAt: Date.now(), done: [] })
  }, [])

  React.useEffect(() => {
    if (reduced.current || run.startedAt === 0) return
    const finished = run.current >= STEPS.length
    const id = window.setTimeout(
      () => {
        setRun((r) =>
          r.current >= STEPS.length
            ? { current: 0, startedAt: Date.now(), done: [] }
            : { current: r.current + 1, startedAt: Date.now(), done: [...r.done, STEPS[r.current]!.ms] },
        )
      },
      finished ? HOLD_MS : STEPS[run.current]!.ms,
    )
    return () => window.clearTimeout(id)
  }, [run])

  const finished = run.current >= STEPS.length
  const total = run.done.reduce((a, b) => a + b, 0)

  return (
    <FitFrame minWidth="34rem">
      <div className="flex w-full flex-col items-center justify-center gap-5 p-6">
        <div className="rounded-(--chatcn-radius-lg) bg-(color:--chatcn-card) shadow-(--chatcn-shadow-sm) w-full max-w-lg p-4">
          <div className="flex items-center gap-2 pb-3">
            <p className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) flex-1 truncate font-medium">Fix the flaky coupon test</p>
            <span
              className={cn(
                "text-[0.75rem]/[1rem] inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 font-medium",
                finished ? "bg-(color:--chatcn-fill) text-(color:--chatcn-fg)" : "bg-(color:--chatcn-fill) text-(color:--chatcn-fg-muted)",
              )}
            >
              {finished ? (
                <>
                  <CheckIcon className="size-3.5" aria-hidden="true" />
                  <span>
                    Done in <StepTimer durationMs={total} precise={false} className="text-(color:--chatcn-fg)" />
                  </span>
                </>
              ) : (
                <>
                  <LoaderCircleIcon className="size-3.5 animate-spin" aria-hidden="true" />
                  Working
                </>
              )}
            </span>
          </div>
          <ol className="border-(color:--chatcn-border) flex flex-col border-t pt-1">
            {STEPS.map((step, i) => {
              const state = i < run.current ? "done" : i === run.current ? "running" : "waiting"
              return (
                <li
                  // biome-ignore lint/suspicious/noArrayIndexKey: a fixed list.
                  key={i}
                  className={cn(
                    "flex h-9 items-center gap-2.5 transition-opacity duration-300",
                    state === "waiting" ? "opacity-0" : "opacity-100",
                  )}
                >
                  <span className="text-(color:--chatcn-fg-subtle) flex size-4 shrink-0 items-center justify-center">
                    {state === "done" ? (
                      <CheckIcon className="size-4" aria-hidden="true" />
                    ) : state === "running" ? (
                      <LoaderCircleIcon className="size-4 animate-spin" aria-hidden="true" />
                    ) : null}
                  </span>
                  <span
                    className={cn(
                      "text-[0.8125rem]/[1.25rem] min-w-0 flex-1 truncate",
                      state === "running" ? "text-(color:--chatcn-fg)" : "text-(color:--chatcn-fg-muted)",
                    )}
                  >
                    {state === "running" ? step.active : step.label}
                  </span>
                  {state === "running" ? (
                    <StepTimer key={`${i}-${run.startedAt}`} running startedAt={run.startedAt} />
                  ) : state === "done" ? (
                    <StepTimer durationMs={run.done[i]} prefix={step.prefix} />
                  ) : null}
                </li>
              )
            })}
          </ol>
        </div>
        <MoreOn slug="step-timer">Live and final times for each step an agent takes. On</MoreOn>
      </div>
    </FitFrame>
  )
}

More by Aadi

View all
  • Stat Card

    Stat Card

    46
  • Audio Visualizer

    Audio Visualizer

    32
  • Dither Orb

    Dither Orb

    24
  • Voice Orb

    Voice Orb

    20
  • Weather Card

    Weather Card

    17
  • Waveform

    Waveform

    15
  • Ticker Card

    Ticker Card

    15
  • Message Feedback

    Message Feedback

    13

More in AI chats

View all
  • AI Actions

    AI Actions

    351
  • Aquarium Prompt

    Aquarium Prompt

    113
  • Agent Chat

    Agent Chat

    21
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    60
  • Research Report

    Research Report

    7
  • Tool Web Fetch

    Tool Web Fetch

    4
  • Color Picker

    Color Picker

    201
  • Suggestions

    Suggestions

    40

Explore more

Part of chatcn — browse the full library on 21st.dev.