Skip to content

The platform for continuously improving AI agents.

11.5 KB
Raw Blame
// Adapted from AI SDK Agents thinking-state; see NOTICE.md.

import type { ReactNode } from "react";

import { AnimatePresence, motion, useReducedMotion } from "motion/react";

import { ToolMark } from "@/components/tool-mark";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Icon as AppIcon } from "@/components/ui/icons";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { ComponentIcon } from "./component-icon";

const AlertCircleIcon = AppIcon.warning;
const ArrowDown01Icon = AppIcon.chevronDown;
const Tick02Icon = AppIcon.success;

export type ThinkingStatus = "working" | "done" | "settled" | "error";
export type ThinkingStepStatus = "pending" | "active" | "done" | "error";

export interface ThinkingStep {
  id: string;
  label: string;
  status?: ThinkingStepStatus;
  detail?: string;
  icon?: ReactNode;
  tool?: string;
  content?: ReactNode;
  collapsible?: boolean;
  stateLabel?: string;
}

export interface ThinkingStateClassNames {
  root?: string;
  header?: string;
  label?: string;
  steps?: string;
  step?: string;
}

export interface ThinkingStateProps {
  status: ThinkingStatus;
  steps: readonly ThinkingStep[];
  label: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  classNames?: ThinkingStateClassNames;
}

const EASE = [0.4, 0, 0.2, 1] as const;

const THEME_VARS =
  "[--thinking-state-done:var(--success)] [--thinking-state-error:var(--destructive)]";

const ENTER_CLASS =
  "fade-in-0 slide-in-from-bottom-2 animate-in fill-mode-both duration-300 ease-out motion-reduce:animate-none";

const stepStatus = (step: ThinkingStep): ThinkingStepStatus => step.status ?? "done";

const DashedRing = ({ spinning }: { spinning: boolean }) =>
  spinning ? <Spinner size="sm" /> : <AppIcon.circle className="size-3.5" />;

const activeTool = (steps: readonly ThinkingStep[]): string | undefined =>
  [...steps].reverse().find((step) => stepStatus(step) === "active" && step.tool)?.tool;

const HeaderMark = ({ blinking, tool }: { blinking: boolean; tool?: string }) =>
  tool ? <ToolMark className="size-4" name={tool} /> : <ThinkingEye blinking={blinking} />;

const ThinkingEye = ({ blinking }: { blinking: boolean }) => (
  <img
    alt=""
    className="thinking-eye size-4 object-contain"
    data-slot="thinking-state-eye"
    height={16}
    src={blinking ? "/thinking-eye.gif?brand=2026-01" : "/favicon.png"}
    width={16}
  />
);

const GLYPH_TONE: Record<ThinkingStepStatus, string> = {
  active: "text-card-foreground",
  done: "text-(--thinking-state-done)",
  error: "text-(--thinking-state-error)",
  pending: "text-muted-foreground/70",
};

const StatusGlyph = ({ status, className }: { status: ThinkingStepStatus; className?: string }) => {
  const reduce = useReducedMotion();
  const settled = status === "done" || status === "error";
  return (
    <span
      className={cn(
        "relative inline-flex size-3.5 flex-none items-center justify-center",
        GLYPH_TONE[status],
        className
      )}
      data-slot="thinking-state-glyph"
      data-status={status}
    >
      <AnimatePresence initial={false} mode="popLayout">
        <motion.span
          animate={{ filter: "blur(0px)", opacity: 1, scale: 1 }}
          className="inline-flex size-full items-center justify-center"
          exit={{ filter: "blur(2px)", opacity: 0, scale: 0.4 }}
          initial={{ filter: "blur(2px)", opacity: 0, scale: 0.4 }}
          key={settled ? status : "ring"}
          transition={{ duration: reduce ? 0 : 0.25, ease: EASE }}
        >
          {settled ? (
            <ComponentIcon
              aria-hidden="true"
              className="size-full"
              icon={status === "done" ? Tick02Icon : AlertCircleIcon}
              strokeWidth={2.4}
            />
          ) : (
            <DashedRing spinning={status === "active"} />
          )}
        </motion.span>
      </AnimatePresence>
    </span>
  );
};

const RollingLabel = ({
  className,
  label,
  shimmer,
}: {
  className?: string;
  label: string;
  shimmer: boolean;
}) => {
  const reduce = useReducedMotion();
  return (
    <span
      className={cn("relative inline-flex min-w-0", className)}
      data-slot="thinking-state-label"
    >
      <AnimatePresence initial={false} mode="popLayout">
        <motion.span
          animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
          className={cn("block min-w-0 truncate", shimmer && "status-shimmer")}
          exit={{ filter: "blur(3px)", opacity: 0, y: "-0.5em" }}
          initial={{ filter: "blur(3px)", opacity: 0, y: "0.5em" }}
          key={label}
          transition={{ duration: reduce ? 0 : 0.28, ease: EASE }}
        >
          {label}
        </motion.span>
      </AnimatePresence>
    </span>
  );
};

const STEP_LABEL_TONE: Record<ThinkingStepStatus, string> = {
  active: "text-card-foreground",
  done: "text-card-foreground",
  error: "text-card-foreground",
  pending: "text-muted-foreground",
};

const ThinkingStepRow = ({
  classNames,
  isFirst,
  isLast,
  step,
}: {
  classNames?: ThinkingStateClassNames;
  isFirst: boolean;
  isLast: boolean;
  step: ThinkingStep;
}) => {
  const reduce = useReducedMotion();
  const status = stepStatus(step);
  const title = (
    <>
      <span className={cn("min-w-0 flex-1", status === "active" && "status-shimmer")}>
        {step.label}
      </span>
      {step.stateLabel && <span className="shrink-0 text-muted-foreground">{step.stateLabel}</span>}
    </>
  );
  const row = cn("flex min-h-6 items-center gap-2 text-xs leading-5", STEP_LABEL_TONE[status]);
  return (
    <motion.li
      animate={{
        filter: "blur(0px)",
        height: "auto",
        opacity: 1,
        // Clip only while growing, so focus rings on sources are not cut off.
        transitionEnd: { overflow: "visible" },
      }}
      className="relative"
      data-slot="thinking-state-step"
      data-status={status}
      initial={{
        filter: "blur(4px)",
        height: 0,
        opacity: 0,
        overflow: "hidden",
      }}
      transition={{ duration: reduce ? 0 : 0.3, ease: EASE }}
    >
      <div className={cn("flex min-w-0 gap-2", classNames?.step)}>
        <span className="flex w-6 flex-none flex-col items-center">
          <span
            aria-hidden
            className={cn("h-[3px] w-px shrink-0 bg-foreground/12", isFirst && "invisible")}
          />
          {step.tool || step.icon ? (
            <span className="relative flex size-5 items-center justify-center rounded-sm bg-wash-raised text-muted-foreground">
              {step.tool ? <ToolMark name={step.tool} /> : step.icon}
              {(status === "active" || status === "error") && (
                <StatusGlyph
                  className="absolute -right-1 -bottom-1 rounded-xs bg-card"
                  status={status}
                />
              )}
            </span>
          ) : (
            <StatusGlyph status={status} />
          )}
          {isLast ? null : <span aria-hidden="true" className="w-px flex-1 bg-foreground/12" />}
        </span>
        <div className={cn("flex min-w-0 flex-1 flex-col gap-1.5", !isLast && "pb-2.5")}>
          {step.content && step.collapsible ? (
            <Collapsible defaultOpen={status === "active" || status === "error"}>
              <CollapsibleTrigger
                className={cn(
                  row,
                  "group w-full rounded-sm text-left hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
                )}
              >
                {title}
                <AppIcon.chevronDown
                  aria-hidden
                  className="size-3 shrink-0 -rotate-90 text-muted-foreground transition-transform group-data-[state=open]:rotate-0 motion-reduce:transition-none"
                />
              </CollapsibleTrigger>
              <CollapsibleContent className="pt-1.5">{step.content}</CollapsibleContent>
            </Collapsible>
          ) : (
            <>
              <div className={row}>{title}</div>
              {step.content}
            </>
          )}
          {step.detail ? (
            <p
              className={cn(
                "-mt-1 line-clamp-2 text-xs leading-4 break-words text-pretty",
                status === "error" ? "text-(--thinking-state-error)" : "text-muted-foreground"
              )}
            >
              {step.detail}
            </p>
          ) : null}
        </div>
      </div>
    </motion.li>
  );
};

export const ThinkingState = ({
  status,
  steps,
  label,
  open,
  onOpenChange,
  classNames,
}: ThinkingStateProps) => {
  const reduce = useReducedMotion();
  const working = status === "working";
  const blinking = working && !reduce;
  const tool = working ? activeTool(steps) : undefined;
  const hasSteps = steps.length > 0;
  return (
    <section
      aria-label="Assistant activity"
      className={cn(
        THEME_VARS,
        ENTER_CLASS,
        "flex w-full max-w-full min-w-0 flex-col rounded-md bg-card p-3 text-card-foreground  transition-shadow duration-150 ease-out ",
        classNames?.root
      )}
      data-slot="thinking-state"
      data-state={open ? "open" : "closed"}
      data-status={status}
      data-variant="panel"
    >
      <button
        aria-expanded={hasSteps ? open : undefined}
        aria-label={label}
        className={cn(
          "relative flex h-6 w-full min-w-0 items-center gap-2 rounded-md border-0 bg-transparent p-0 text-left after:absolute after:-inset-1.5 after:content-[''] focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none ",
          hasSteps ? "cursor-pointer" : "cursor-default",
          classNames?.header
        )}
        data-slot="thinking-state-header"
        disabled={!hasSteps}
        onClick={() => onOpenChange(!open)}
        type="button"
      >
        <span className="inline-flex size-6 flex-none items-center justify-center rounded-md bg-muted ">
          <HeaderMark blinking={blinking} tool={tool} />
        </span>
        <output
          aria-live="polite"
          className={cn("flex min-w-0 flex-1 text-xs leading-5 font-medium ", classNames?.label)}
        >
          <RollingLabel label={label} shimmer={working} />
        </output>
        {hasSteps ? (
          <ComponentIcon
            aria-hidden="true"
            className={cn(
              "size-3 flex-none text-muted-foreground transition-transform duration-150 ease-out motion-reduce:transition-none",
              open ? "rotate-0" : "-rotate-90"
            )}
            icon={ArrowDown01Icon}
            strokeWidth={2}
          />
        ) : null}
      </button>
      <AnimatePresence initial={false}>
        {open && hasSteps ? (
          <motion.div
            animate={{ height: "auto", opacity: 1 }}
            className="overflow-hidden"
            exit={{ height: 0, opacity: 0 }}
            initial={{ height: 0, opacity: 0 }}
            key="steps"
            transition={{ duration: reduce ? 0 : 0.25, ease: EASE }}
          >
            <ul
              className={cn("m-0 flex list-none flex-col p-0 pt-3", classNames?.steps)}
              data-slot="thinking-state-steps"
            >
              {steps.map((step, index) => (
                <ThinkingStepRow
                  classNames={classNames}
                  isFirst={index === 0}
                  isLast={index === steps.length - 1}
                  key={step.id}
                  step={step}
                />
              ))}
            </ul>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </section>
  );
};