Skip to content

The platform for continuously improving AI agents.

9.5 KB
Raw Blame
import { createContext, useContext, useEffect, useRef, useState } from "react";

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

import { Icon as AppIcon } from "@/components/ui/icons";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { ComponentIcon, type IconSvgElement } from "./component-icon";

const Alert02Icon = AppIcon.warning;
const PauseIcon = AppIcon.stop;
type InterruptionReason = "stopped" | "error";
interface InterruptedReplyProps {
  reason?: InterruptionReason;
  text?: string;
  onContinue?: () => void | Promise<void>;
  className?: string;
}

type Phase = "interrupted" | "continuing";

const LABEL: Record<InterruptionReason, string> = {
  error: "Response interrupted",
  stopped: "Response stopped",
};

const ICON: Record<InterruptionReason, IconSvgElement> = {
  error: Alert02Icon,
  stopped: PauseIcon,
};

const EASE_OUT = [0.25, 1, 0.5, 1] as const;

const THEME_VARS = [
  "[--interrupted-reply-error:var(--destructive)]",
  "[--interrupted-reply-mark:color-mix(in_oklab,var(--foreground)_38%,transparent)]",
].join(" ");

const TEXT_CLASS =
  "m-0 text-sm leading-[1.6]  text-pretty [overflow-wrap:anywhere] whitespace-pre-wrap text-card-foreground";

const FOCUS_CLASS = "focus-visible:ring-2 focus-visible:ring-ring/50  focus-visible:outline-none";

const PILL_CLASS = cn(
  "relative inline-flex h-6 flex-none cursor-pointer items-center overflow-hidden rounded-sm border border-border bg-control px-2.5 text-xs leading-none font-medium text-card-foreground transition-[background-color,opacity,scale] duration-150 ease-out after:absolute after:inset-x-0 after:-inset-y-2 after:content-[''] hover:bg-control-hover active:scale-[0.96] motion-reduce:transition-none",
  FOCUS_CLASS
);

const errorText = (error: Error | string | null | undefined): string => {
  const text = typeof error === "string" ? error : (error?.message ?? "");
  return text.trim();
};

const MarkContext = createContext<Phase | null>(null);

interface InterruptedReplyMarkProps {
  className?: string;
}

const InterruptedReplyMark = ({ className }: InterruptedReplyMarkProps) => {
  const phase = useContext(MarkContext);
  const active = phase === "continuing";
  return (
    <span
      aria-hidden="true"
      className={cn(
        "ml-1 inline-flex h-[1em] translate-y-[0.08em] animate-in items-center gap-[3px] align-baseline text-(--interrupted-reply-mark) duration-300 ease-out fade-in-0 motion-reduce:animate-none",
        className
      )}
      data-slot="interrupted-reply-mark"
      data-state={active ? "active" : "idle"}
    >
      {[0, 1, 2].map((index) => (
        <span
          className={cn(
            "size-[3px] rounded-sm bg-current",
            active && "animate-pulse [animation-duration:1.1s] motion-reduce:animate-none"
          )}
          key={index}
          style={active ? { animationDelay: `${index * 160}ms` } : undefined}
        />
      ))}
    </span>
  );
};

const PlainReply = ({
  className,
  markClassName,
  text,
}: {
  className?: string;
  markClassName?: string;
  text: string;
}) => {
  const trimmed = text.trimEnd();
  const split = trimmed.search(/\S+$/u);
  const head = split > 0 ? trimmed.slice(0, split) : "";
  const tail = split > 0 ? trimmed.slice(split) : trimmed;
  return (
    <p className={cn(TEXT_CLASS, className)} data-slot="interrupted-reply-text">
      {head}
      <span className="whitespace-nowrap">
        {tail}
        <InterruptedReplyMark className={markClassName} />
      </span>
    </p>
  );
};

const MorphLabel = ({ busy, label }: { busy: boolean; label: string }) => {
  const reduce = useReducedMotion();
  const faded = reduce ? { opacity: 0 } : { filter: "blur(2px)", opacity: 0 };
  const content = (
    <>
      {busy ? <Spinner size="sm" /> : null}
      {label}
    </>
  );
  return (
    <span className="relative flex h-full items-center transition-[width] duration-200 ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none">
      <span
        aria-hidden="true"
        className="invisible absolute flex items-center gap-1 whitespace-nowrap"
      >
        {content}
      </span>
      <AnimatePresence initial={false} mode="popLayout">
        <motion.span
          animate={{ filter: "blur(0px)", opacity: 1 }}
          className="flex items-center gap-1 whitespace-nowrap"
          exit={{ ...faded, transition: { duration: 0.1, ease: EASE_OUT } }}
          initial={faded}
          key={label}
          transition={{ duration: 0.18, ease: EASE_OUT }}
        >
          {content}
        </motion.span>
      </AnimatePresence>
    </span>
  );
};

const StatusLine = ({
  className,
  icon,
  label,
}: {
  className?: string;
  icon: IconSvgElement;
  label: string;
}) => {
  const reduce = useReducedMotion();
  const faded = reduce ? { opacity: 0 } : { filter: "blur(2px)", opacity: 0, y: 3 };
  return (
    <span className="relative flex h-6 min-w-0 flex-1 items-center overflow-hidden">
      <AnimatePresence initial={false} mode="popLayout">
        <motion.span
          animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
          className={cn(
            "flex min-w-0 items-center gap-1.5 text-xs leading-4 text-muted-foreground",
            className
          )}
          data-slot="interrupted-reply-label"
          exit={{
            ...faded,
            transition: { duration: 0.12, ease: EASE_OUT },
            y: reduce ? 0 : -3,
          }}
          initial={faded}
          key={label}
          transition={{ duration: 0.22, ease: EASE_OUT }}
        >
          <ComponentIcon
            aria-hidden="true"
            className="size-3.5 flex-none"
            icon={icon}
            strokeWidth={2}
          />
          <span className="truncate">{label}</span>
        </motion.span>
      </AnimatePresence>
    </span>
  );
};

export const InterruptedReply = ({
  reason = "stopped",
  text,
  onContinue,
  className,
}: InterruptedReplyProps) => {
  const [pending, setPending] = useState(false);
  const [failure, setFailure] = useState<string | null>(null);
  const busy = pending;
  const phase: Phase = busy ? "continuing" : "interrupted";

  const mounted = useRef(true);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);

  const fail = (caught: unknown) => {
    setFailure(
      errorText(caught instanceof Error ? caught : String(caught)) || "Could not continue."
    );
  };

  const run = () => {
    if (!onContinue || busy) {
      return;
    }
    setFailure(null);
    let result: void | Promise<void>;
    try {
      result = onContinue();
    } catch (error) {
      fail(error);
      return;
    }
    if (!(result instanceof Promise)) {
      return;
    }
    setPending(true);
    result.then(
      () => {
        if (mounted.current) {
          setPending(false);
        }
      },
      (error: unknown) => {
        if (mounted.current) {
          setPending(false);
          fail(error);
        }
      }
    );
  };

  const reply = text;
  const label = (() => {
    // While it continues the button says so; the line keeps the reason.
    if (failure && !busy) {
      return "Could not continue";
    }
    return LABEL[reason];
  })();
  const icon = failure && !busy ? Alert02Icon : ICON[reason];
  const detail = failure ?? "";

  return (
    <MarkContext.Provider value={phase}>
      <div
        aria-busy={busy ? true : undefined}
        className={cn(
          THEME_VARS,
          "flex w-full max-w-full min-w-0 flex-col gap-2 text-card-foreground",
          className
        )}
        data-reason={reason}
        data-slot="interrupted-reply"
        data-state={phase}
      >
        {reply ? <PlainReply text={reply} /> : null}

        <div
          className={cn(
            "flex min-w-0 animate-in flex-col duration-200 ease-out fade-in-0 fill-mode-both slide-in-from-bottom-1 motion-reduce:animate-none"
          )}
          data-slot="interrupted-reply-notice"
        >
          <div className="flex min-w-0 items-center gap-3">
            <output aria-live="polite" className="contents">
              <StatusLine
                className={cn(failure && "text-(--interrupted-reply-error)")}
                icon={icon}
                label={label}
              />
            </output>
            {onContinue ? (
              <button
                aria-disabled={busy ? true : undefined}
                className={cn(PILL_CLASS, busy && "pointer-events-none opacity-80")}
                data-slot="interrupted-reply-continue"
                disabled={busy}
                onClick={run}
                type="button"
              >
                <MorphLabel busy={busy} label={busy ? "Continuing" : "Continue"} />
              </button>
            ) : null}
          </div>
          <div
            className={cn(
              "grid transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none",
              detail ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
            )}
            inert={!detail}
          >
            <p
              className={cn(
                "m-0 min-h-0 overflow-hidden pl-5 text-xs leading-4 text-pretty text-muted-foreground"
              )}
              data-slot="interrupted-reply-detail"
              role={failure ? "alert" : undefined}
            >
              <span className="line-clamp-2 pt-0.5" title={detail || undefined}>
                {detail}
              </span>
            </p>
          </div>
        </div>
      </div>
    </MarkContext.Provider>
  );
};