Skip to content
Shaken UI
Sign in

Chain of Thought

Save

A summary line that expands into the ordered steps an agent took, each on a hairline rail with a status glyph, the sources it read, and any images.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Chain of Thought preview
  1. Searched for pricing pages of three analytics tools, In progress

Installation

npx @shakenui/cli add chain-of-thought

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add chain-of-thought --dry-run

Usage

chain-of-thought-example.tsx
import { ChainOfThought } from "@/components/shaken/agent/chain-of-thought";

export default function ChainOfThoughtExample() {
  return (
    <ChainOfThought
      className="max-w-lg"
      defaultOpen
      summary="Checked 5 sources on webhook retries"
      steps={[
        {
          id: "search",
          label: "Searched for webhook retry behavior",
          detail: "5 results",
          results: [
            { title: "Webhooks: retries and backoff", url: "https://docs.stripe.com/webhooks" },
            { title: "Delivering webhooks reliably", url: "https://github.blog/engineering/webhooks" },
            { title: "Idempotent receivers", url: "https://developer.mozilla.org/en-US/docs/Glossary/Idempotent" },
            { title: "Retry policies", url: "https://learn.microsoft.com/azure/architecture/patterns/retry" },
            { title: "Exponential backoff", url: "https://cloud.google.com/storage/docs/retry-strategy" },
          ],
        },
        { id: "read", label: "Read the retry and backoff guide", detail: "Retries continue for up to 3 days with exponential backoff" },
        { id: "compare", label: "Compared it with the current handler", detail: "The handler returns 500 on duplicates, which triggers more retries" },
        { id: "draft", label: "Drafted an idempotency fix" },
      ]}
    />
  );
}

API

PropTypeDefaultDescription
steps{ id, label, status?, detail?, activity?, results?, images?, content? }[]—Steps in order. status is queued, running, done (default), failed, or skipped. results are { title, url } sources; images are { src, alt, caption? }.
summaryReactNode"Took N steps"The collapsed line once finished. While a step runs, the line shows that step with its live mark instead.
open / defaultOpen / onOpenChangeboolean / boolean / (open) => voiddefaultOpen falseControlled or uncontrolled open state.
maxResultsnumber4Sources shown per step before the rest fold into "+N".

Accessibility

  • Built on Base UI Collapsible: the summary line is a button with aria-expanded, operable with Enter and Space.
  • Every step has a screen-reader status after its label; glyphs and marks are decorative. Skipped steps are struck through and labeled.
  • Source links name the page title before the host name, so the accessible name includes the visible text. They open in a new tab.
  • Images require alt text. The list is aria-busy while a step runs.
  • With reduced motion the marks hold still and steps, glyphs, and the panel appear without animation.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/chain-of-thought.tsxchain-of-thought
  • Also installs agent-state@0.1.0registry dependency
  • Also installs step-list@0.3.0registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/chain-of-thought/0.1.0.json.

agent/chain-of-thought.tsxShow
agent/chain-of-thought.tsx
"use client";

import { Collapsible } from "@base-ui/react/collapsible";
import type { ReactNode } from "react";
import { type AgentActivity, AgentMark } from "./agent-state";
import { StatusGlyph, type StatusGlyphKind } from "./step-list";

function cx(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export type ChainOfThoughtStatus = "queued" | "running" | "done" | "failed" | "skipped";

const glyphs: Record<Exclude<ChainOfThoughtStatus, "running">, StatusGlyphKind> = {
  queued: "queued",
  done: "success",
  failed: "failed",
  skipped: "skipped",
};

const spoken: Record<ChainOfThoughtStatus, string> = {
  queued: "Queued",
  running: "In progress",
  done: "Done",
  failed: "Failed",
  skipped: "Skipped",
};

export interface ChainOfThoughtResult {
  /** Page title. Read by screen readers before the host name. */
  title: string;
  url: string;
}

export interface ChainOfThoughtImage {
  src: string;
  alt: string;
  caption?: ReactNode;
}

export interface ChainOfThoughtStep {
  id: string;
  /** What the agent did, in a few words: "Searched for rate limit docs". */
  label: ReactNode;
  /** @default "done" */
  status?: ChainOfThoughtStatus;
  /** A secondary line: what it found, or why it failed. */
  detail?: ReactNode;
  /** Which Agent State mark moves while this step runs. Defaults to thinking. */
  activity?: AgentActivity;
  /** Sources the step looked at, shown as host name links. */
  results?: ChainOfThoughtResult[];
  /** Images the step looked at or produced, shown as a small grid of thumbnails. */
  images?: ChainOfThoughtImage[];
  /** Any extra content under the step, for example a quoted snippet. */
  content?: ReactNode;
}

export interface ChainOfThoughtProps {
  steps: ChainOfThoughtStep[];
  /**
   * The collapsed line once the agent has finished, for example "Checked 6 sources". While a
   * step runs, the line shows that step instead. Defaults to "Took N steps".
   */
  summary?: ReactNode;
  /** Controlled open state. Pair with `onOpenChange`. */
  open?: boolean;
  /** Initial open state when uncontrolled. */
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** Shows at most this many sources per step and folds the rest into "+N". @default 4 */
  maxResults?: number;
  className?: string;
}

/**
 * A summary line that expands into the ordered steps the agent took. Each step sits on a
 * hairline rail with its status glyph, an optional detail line, the sources it read, and any
 * images. While a step runs, the summary line follows it with that step's live mark.
 */
export function ChainOfThought({
  steps,
  summary,
  open,
  defaultOpen = false,
  onOpenChange,
  maxResults = 4,
  className,
}: ChainOfThoughtProps) {
  const running = steps.find((step) => (step.status ?? "done") === "running");
  const failed = steps.some((step) => step.status === "failed");
  const lineText = running ? running.label : (summary ?? `Took ${steps.length} ${steps.length === 1 ? "step" : "steps"}`);

  return (
    <Collapsible.Root
      open={open}
      defaultOpen={defaultOpen}
      onOpenChange={onOpenChange ? (next) => onOpenChange(next) : undefined}
      data-running={running ? "" : undefined}
      className={cx("w-full min-w-0", className)}
    >
      <Collapsible.Trigger
        className={cx(
          "group -mx-1.5 flex h-7 max-w-[calc(100%+0.75rem)] cursor-pointer items-center gap-2 rounded-md px-1.5 text-left text-sm select-none",
          "text-zinc-600 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.04] hover:text-zinc-950 data-[panel-open]:text-zinc-950",
          "dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white dark:data-[panel-open]:text-white",
          "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        )}
      >
        <span aria-hidden="true" className="inline-flex size-4 shrink-0 items-center justify-center">
          {running ? (
            <AgentMark key={running.id} activity={running.activity ?? "thinking"} size={16} className="text-zinc-950 dark:text-white" />
          ) : failed ? (
            <StatusGlyph kind="failed" />
          ) : (
            <RailIcon />
          )}
        </span>
        <span
          key={running ? running.id : "summary"}
          className={cx(
            "min-w-0 truncate",
            running ? "after:content-['…']" : "",
            `transition-[opacity,filter,translate] duration-300 ${ease} starting:translate-y-[3px] starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`,
          )}
        >
          {lineText}
        </span>
        {failed && !running ? <span className="sr-only">, one or more steps failed</span> : null}
        <svg
          aria-hidden="true"
          viewBox="0 0 16 16"
          fill="none"
          className={cx(
            "size-3.5 shrink-0 text-zinc-400 dark:text-zinc-500",
            `transition-[rotate,color] duration-220 ${ease} motion-reduce:transition-none`,
            "group-hover:text-current group-data-[panel-open]:rotate-180 group-data-[panel-open]:text-current",
          )}
        >
          <path d="m4.5 6.25 3.5 3.5 3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </Collapsible.Trigger>

      <Collapsible.Panel
        className={cx(
          "h-(--collapsible-panel-height) overflow-hidden",
          `transition-[height,opacity] duration-220 ${ease} motion-reduce:transition-none`,
          "data-[starting-style]:h-0 data-[starting-style]:opacity-0",
          "data-[ending-style]:h-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-180",
        )}
      >
        <ol aria-busy={running ? true : undefined} className="grid pt-3 pb-1">
          {steps.map((step, index) => (
            <Step key={step.id} step={step} last={index === steps.length - 1} maxResults={maxResults} />
          ))}
        </ol>
      </Collapsible.Panel>
    </Collapsible.Root>
  );
}

function Step({ step, last, maxResults }: { step: ChainOfThoughtStep; last: boolean; maxResults: number }) {
  const status = step.status ?? "done";
  const results = step.results ?? [];
  const shown = results.slice(0, maxResults);
  const hidden = results.length - shown.length;

  return (
    <li
      data-status={status}
      className={cx(
        "relative grid grid-cols-[1rem_minmax(0,1fr)] gap-x-3 pb-4 last:pb-0",
        `transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`,
      )}
    >
      {!last ? (
        <span
          aria-hidden="true"
          className={cx(
            "absolute top-6 bottom-1 left-[7.5px] w-px transition-colors duration-300 motion-reduce:transition-none",
            status === "done" ? "bg-zinc-950/20 dark:bg-white/20" : "bg-zinc-950/[0.08] dark:bg-white/10",
          )}
        />
      ) : null}
      <span aria-hidden="true" className="flex h-5 w-4 items-center justify-center">
        {status === "running" ? (
          <AgentMark activity={step.activity ?? "thinking"} size={16} className="text-zinc-950 dark:text-white" />
        ) : (
          <StatusGlyph key={status} kind={glyphs[status]} />
        )}
      </span>

      <div className="min-w-0">
        <p
          className={cx(
            "text-sm leading-5 break-words transition-colors duration-200 motion-reduce:transition-none",
            status === "queued" ? "text-zinc-500" : status === "skipped" ? "text-zinc-500 line-through decoration-zinc-500/60" : "text-zinc-950 dark:text-white",
          )}
        >
          {step.label}
          <span className="sr-only">, {spoken[status]}</span>
        </p>
        {step.detail != null ? (
          <p className={cx("mt-0.5 text-xs leading-5", status === "failed" ? "text-red-600 dark:text-red-400" : "text-zinc-500")}>{step.detail}</p>
        ) : null}

        {shown.length ? (
          <ul aria-label="Sources" className="mt-2 flex flex-wrap gap-1.5">
            {shown.map((result) => (
              <li key={result.url} className={`transition-opacity duration-200 ${ease} starting:opacity-0 motion-reduce:transition-none`}>
                <a
                  href={result.url}
                  target="_blank"
                  rel="noreferrer"
                  title={result.title}
                  className={cx(
                    "inline-flex h-6 max-w-56 items-center gap-1.5 rounded-md border px-2 text-xs",
                    "border-zinc-950/10 text-zinc-600 transition-[background-color,border-color,color] duration-150 ease-out motion-reduce:transition-none",
                    "hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] hover:text-zinc-950",
                    "dark:border-white/10 dark:text-zinc-400 dark:hover:border-white/20 dark:hover:bg-white/[0.06] dark:hover:text-white",
                    "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                  )}
                >
                  <GlobeIcon />
                  <span className="sr-only">{result.title}, </span>
                  <span className="truncate">{hostname(result.url)}</span>
                </a>
              </li>
            ))}
            {hidden > 0 ? (
              <li className="inline-flex h-6 items-center px-1 font-mono text-xs text-zinc-500 tabular-nums">
                <span aria-hidden="true">+{hidden}</span>
                <span className="sr-only">and {hidden} more</span>
              </li>
            ) : null}
          </ul>
        ) : null}

        {step.images?.length ? (
          <div className="mt-2 grid grid-cols-2 gap-2 sm:grid-cols-3">
            {step.images.map((image) => (
              <figure key={image.src} className="min-w-0">
                <img
                  src={image.src}
                  alt={image.alt}
                  loading="lazy"
                  className="aspect-[4/3] w-full rounded-lg border border-zinc-950/10 bg-zinc-950/[0.02] object-cover dark:border-white/10 dark:bg-transparent"
                />
                {image.caption != null ? <figcaption className="mt-1 truncate text-xs text-zinc-500">{image.caption}</figcaption> : null}
              </figure>
            ))}
          </div>
        ) : null}

        {step.content != null ? <div className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">{step.content}</div> : null}
      </div>
    </li>
  );
}

function hostname(url: string): string {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return url;
  }
}

/** Three nodes on a rail: the collapsed form of the step list. */
function RailIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" className="size-4 text-zinc-400 dark:text-zinc-500">
      <circle cx="4.5" cy="3.5" r="1.25" />
      <circle cx="4.5" cy="8" r="1.25" />
      <circle cx="4.5" cy="12.5" r="1.25" />
      <path d="M8.5 3.5h5M8.5 8h3.5M8.5 12.5h5" />
    </svg>
  );
}

function GlobeIcon() {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.25} className="size-3 shrink-0 opacity-70">
      <circle cx="8" cy="8" r="6" />
      <path d="M2 8h12M8 2c1.7 1.7 2.5 3.7 2.5 6S9.7 12.3 8 14C6.3 12.3 5.5 10.3 5.5 8S6.3 3.7 8 2Z" />
    </svg>
  );
}