Skip to content

The platform for continuously improving AI agents.

17.0 KB
Raw Blame
// Adapted from AI SDK Agents chat-thread; source access recorded in NOTICE.md.

import type { CSSProperties, ReactNode } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";

import type { ChatStatus } from "ai";

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

const AlertCircleIcon = AppIcon.warning;
const ArrowDown02Icon = AppIcon.arrowDown;
export interface ChatThreadMessageInfo {
  last: boolean;
  streaming: boolean;
}

export interface ChatThreadClassNames {
  root?: string;
  scroller?: string;
  content?: string;
  turn?: string;
  error?: string;
  jump?: string;
}

interface ThreadMessage {
  id: string;
  role: string;
}

export interface ChatThreadProps<Message extends ThreadMessage> {
  messages: readonly Message[];
  status?: ChatStatus;
  error?: Error | string | null;
  onRetry?: () => void;
  id?: string;
  renderMessage: (message: Message, info: ChatThreadMessageInfo) => ReactNode;
  empty?: ReactNode;
  onScrolledChange?: (scrolled: boolean) => void;
  jumpLabel?: string;
  label?: string;
  className?: string;
  classNames?: ChatThreadClassNames;
  style?: CSSProperties;
}

const PAD_TOP_PX = 24;
const PAD_BOTTOM_PX = 32;
const STICK_PX = 8;
const AWAY_PX = 96;
const AUTO_SCROLL_MS = 1000;
const FOLD_OVER_PX = 320;
const FOLD_TO_PX = 216;
const LIVE_TURNS = 3;

const THEME_VARS =
  "[--chat-thread-bubble:var(--accent)] [--chat-thread-error:var(--destructive)] [--chat-thread-done:var(--success)]";

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

const ENTER_CLASS =
  "animate-in duration-300 ease-[cubic-bezier(0.19,1,0.22,1)] fill-mode-both fade-in-0 slide-in-from-bottom-2 motion-reduce:animate-none";

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

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

const Icon = ({ className, icon }: { className?: string; icon: IconSvgElement }) => (
  <ComponentIcon aria-hidden="true" className={className} icon={icon} strokeWidth={2} />
);

export const ChatThreadUserMessage = ({
  className,
  text,
  renderText,
}: {
  className?: string;
  text: string;
  renderText?: (text: string) => ReactNode;
}) => {
  const body = useRef<HTMLDivElement>(null);
  const [folds, setFolds] = useState(false);
  const [open, setOpen] = useState(false);

  // biome-ignore lint/correctness/useExhaustiveDependencies: text changes invalidate the measured DOM height.
  useLayoutEffect(() => {
    const node = body.current;
    if (node) {
      setFolds(node.scrollHeight > FOLD_OVER_PX);
    }
  }, [text]);

  const folded = folds && !open;

  return (
    <div className="flex min-w-0 flex-col items-end gap-1.5">
      {text ? (
        <div
          className={cn(
            "max-w-[min(85%,36rem)] min-w-0 bg-(--chat-thread-bubble) px-3.5 py-2 text-card-foreground",
            className
          )}
          data-slot="chat-thread-user"
        >
          <div
            className={cn(
              "min-w-0",
              folded &&
                "overflow-hidden [mask-image:linear-gradient(to_bottom,black_calc(100%-3rem),transparent)]"
            )}
            ref={body}
            style={folded ? { maxHeight: FOLD_TO_PX } : undefined}
          >
            {renderText ? renderText(text) : <Markdown text={text} />}
          </div>
          {folds ? (
            <button
              aria-expanded={open}
              className={cn(
                "relative mt-1 cursor-pointer rounded-sm border-0 bg-transparent p-0 text-xs leading-5 font-medium text-card-foreground bg-control px-2 py-1 transition-[text-decoration-color] duration-150 ease-out after:absolute after:-inset-2 after:content-[''] hover:bg-control-hover motion-reduce:transition-none",
                FOCUS_CLASS
              )}
              onClick={() => {
                setOpen(!open);
              }}
              type="button"
            >
              {open ? "Show less" : "Show more"}
            </button>
          ) : null}
        </div>
      ) : null}
    </div>
  );
};

function Row<Message extends ThreadMessage>({
  animate,
  last,
  message,
  renderMessage,
  streaming,
}: {
  animate: boolean;
  last: boolean;
  message: Message;
  renderMessage: ChatThreadProps<Message>["renderMessage"];
  streaming: boolean;
}) {
  const body = renderMessage(message, { last, streaming });
  if (body == null || body === false) return null;
  return (
    <div
      className={cn("min-w-0", animate && message.role === "user" && ENTER_CLASS)}
      data-message-id={message.id}
      data-role={message.role}
      data-slot="chat-thread-message"
    >
      {body}
    </div>
  );
}

function turnsOf<Message extends ThreadMessage>(messages: readonly Message[]) {
  const turns: { id: string; messages: Message[] }[] = [];
  for (const message of messages) {
    const current = turns.at(-1);
    if (message.role === "user" || !current) turns.push({ id: message.id, messages: [message] });
    else current.messages.push(message);
  }
  return turns;
}

interface Track {
  baseline: ReadonlySet<string>;
  epoch: number;
  key: string;
  lastUser: string | undefined;
  anchor: string | null;
}

export function ChatThread<Message extends ThreadMessage>({
  messages,
  status = "ready",
  error,
  onRetry,
  id,
  renderMessage,
  empty,
  onScrolledChange,
  jumpLabel = "Jump to latest",
  label = "Conversation",
  className,
  classNames,
  style,
}: ChatThreadProps<Message>) {
  const scroller = useRef<HTMLDivElement>(null);
  const content = useRef<HTMLDivElement>(null);
  const follow = useRef(true);
  const auto = useRef<ReturnType<typeof setTimeout> | null>(null);
  const scrolled = useRef(false);
  const report = useRef(onScrolledChange);
  const [away, setAway] = useState(false);

  useEffect(() => {
    report.current = onScrolledChange;
  });

  const lastUserAt = messages.reduce(
    (last, message, index) => (message.role === "user" ? index : last),
    -1
  );
  const lastUser = lastUserAt === -1 ? undefined : messages[lastUserAt]?.id;
  const key = id ?? messages.at(0)?.id ?? "";
  const [track, setTrack] = useState<Track>(() => ({
    anchor: null,
    baseline: new Set(messages.map((message) => message.id)),
    epoch: 0,
    key,
    lastUser,
  }));
  if (track.key !== key) {
    // With no id to go by, a first message in an empty chat is a send.
    const started = id === undefined && track.key === "" && messages.length <= 2;
    setTrack(
      started
        ? { ...track, anchor: lastUser ?? null, key, lastUser }
        : {
            anchor: null,
            baseline: new Set(messages.map((message) => message.id)),
            epoch: track.epoch + 1,
            key,
            lastUser,
          }
    );
  } else if (track.lastUser !== lastUser) {
    const sent =
      lastUser !== undefined && !track.baseline.has(lastUser) && lastUserAt >= messages.length - 2;
    setTrack({ ...track, anchor: sent ? lastUser : track.anchor, lastUser });
  }

  const measure = useCallback(() => {
    const node = scroller.current;
    if (!node) {
      return 0;
    }
    const gap = node.scrollHeight - node.scrollTop - node.clientHeight;
    // Not while the thread is scrolling itself: the way back would flash.
    setAway(gap > AWAY_PX && auto.current === null);
    const under = node.scrollTop > 0;
    if (under !== scrolled.current) {
      scrolled.current = under;
      report.current?.(under);
    }
    return gap;
  }, []);

  const endAuto = useCallback(() => {
    if (auto.current !== null) {
      clearTimeout(auto.current);
      auto.current = null;
    }
  }, []);

  const startAuto = useCallback(() => {
    endAuto();
    auto.current = setTimeout(() => {
      auto.current = null;
      measure();
    }, AUTO_SCROLL_MS);
  }, [endAuto, measure]);

  // The view's height, for the space kept under a question that was just asked.
  useLayoutEffect(() => {
    const node = scroller.current;
    const inner = content.current;
    if (!node || !inner) {
      return;
    }
    const measureContent = () => {
      node.style.setProperty("--chat-thread-view", `${node.clientHeight}px`);
      if (follow.current) {
        node.scrollTop = node.scrollHeight;
      }
      measure();
    };
    measureContent();
    const observer = new ResizeObserver(measureContent);
    observer.observe(node);
    observer.observe(inner);
    return () => {
      observer.disconnect();
      endAuto();
    };
  }, [endAuto, measure]);

  // biome-ignore lint/correctness/useExhaustiveDependencies: a thread identity change must reset the scroll position.
  useLayoutEffect(() => {
    const node = scroller.current;
    if (!node) {
      return;
    }
    endAuto();
    follow.current = true;
    node.scrollTop = node.scrollHeight;
    measure();
  }, [endAuto, measure, track.epoch]);

  // A question that was just asked moves to the top, and the reply is written
  // into the space under it. Nothing the person is reading moves after that.
  useLayoutEffect(() => {
    const node = scroller.current;
    if (!node || track.anchor === null) {
      return;
    }
    const turn = [...node.querySelectorAll<HTMLElement>("[data-turn]")].find(
      (item) => item.dataset.turn === track.anchor
    );
    if (!turn) {
      return;
    }
    follow.current = false;
    startAuto();
    node.scrollTo({
      behavior: prefersLessMotion() ? "auto" : "smooth",
      top: turn.offsetTop - PAD_TOP_PX,
    });
  }, [startAuto, track.anchor]);

  const onScroll = () => {
    const gap = measure();
    // Reaching the end by hand asks to follow along. Leaving it stops that.
    if (auto.current === null) {
      follow.current = gap <= STICK_PX;
    }
  };

  const toEnd = () => {
    const node = scroller.current;
    if (!node) {
      return;
    }
    follow.current = true;
    if (prefersLessMotion()) {
      node.scrollTop = node.scrollHeight;
      return;
    }
    startAuto();
    node.scrollTo({ behavior: "smooth", top: node.scrollHeight });
  };

  const turns = turnsOf(messages);

  // Older turns are laid out only when scrolled to. Each is measured once
  // first, so the space it holds is its real height and nothing shifts.
  const [sizes, setSizes] = useState<ReadonlyMap<string, number>>(() => new Map());
  const settled = Math.max(0, turns.length - LIVE_TURNS);
  // biome-ignore lint/correctness/useExhaustiveDependencies: the thread epoch invalidates cached turn heights.
  useLayoutEffect(() => {
    const node = content.current;
    if (!node || settled === 0) {
      return;
    }
    const found: [string, number][] = [];
    for (const element of node.querySelectorAll<HTMLElement>(
      "[data-slot=chat-thread-turn]:not([data-settled])"
    )) {
      const turnId = element.dataset.turn;
      if (turnId && element.dataset.settle === "true") {
        found.push([turnId, element.offsetHeight]);
      }
    }
    if (found.length > 0) {
      setSizes((current) => new Map([...current, ...found]));
    }
  }, [settled, track.epoch]);
  const lastMessage = messages.at(-1);
  const busy = status === "submitted" || status === "streaming";
  const failed = status === "error" || Boolean(error);
  const waiting =
    !failed &&
    (status === "submitted" || (status === "streaming" && lastMessage?.role !== "assistant"));
  const isEmpty = messages.length === 0 && !waiting && !failed;

  const tail = (
    <>
      {waiting ? (
        <div
          aria-label="Thinking"
          className="flex h-6 items-center"
          data-slot="chat-thread-waiting"
          role="status"
        >
          <span className="size-2.5 animate-pulse rounded-sm bg-foreground/70 motion-reduce:animate-none" />
        </div>
      ) : null}
      {failed ? (
        <div
          className={cn(
            "flex min-w-0 items-start gap-2 text-xs leading-5",
            ENTER_CLASS,
            classNames?.error
          )}
          data-slot="chat-thread-error"
          role="alert"
        >
          <span className="inline-flex h-5 flex-none items-center">
            <Icon className="size-4 text-(--chat-thread-error)" icon={AlertCircleIcon} />
          </span>
          <span className="min-w-0 [overflow-wrap:anywhere] text-card-foreground">
            {errorText(error)}
          </span>
          {onRetry ? (
            <button
              className={cn(
                "relative flex-none cursor-pointer rounded-sm border-0 bg-transparent p-0 font-medium text-card-foreground bg-control px-2 py-1 transition-[text-decoration-color,scale] duration-150 ease-out after:absolute after:-inset-2 after:content-[''] hover:bg-control-hover active:scale-[0.97] motion-reduce:transition-none",
                FOCUS_CLASS
              )}
              data-slot="chat-thread-retry"
              onClick={onRetry}
              type="button"
            >
              Retry
            </button>
          ) : null}
        </div>
      ) : null}
    </>
  );

  return (
    <div
      className={cn(
        THEME_VARS,
        "relative flex min-h-0 min-w-0 flex-1 flex-col",
        className,
        classNames?.root
      )}
      data-slot="chat-thread"
      data-status={status}
      style={style}
    >
      <div
        aria-label={label}
        className={cn(
          "relative flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto overscroll-contain scroll-fade-y outline-none [scrollbar-gutter:stable_both-edges] ",
          classNames?.scroller
        )}
        data-slot="chat-thread-scroller"
        onKeyDown={endAuto}
        onPointerDown={endAuto}
        onScroll={onScroll}
        onScrollEnd={() => {
          endAuto();
          measure();
        }}
        onTouchStart={endAuto}
        onWheel={endAuto}
        ref={scroller}
        role="region"
        // biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard users need to scroll the conversation.
        tabIndex={0}
      >
        <div
          aria-busy={busy}
          aria-relevant="additions"
          className={cn(
            "mx-auto flex w-full max-w-[46rem] flex-col gap-8 px-4 pt-6 pb-8",
            isEmpty && "flex-1 justify-center",
            classNames?.content
          )}
          data-slot="chat-thread-content"
          ref={content}
          role="log"
        >
          {isEmpty ? empty : null}
          {turns.map((turn, index) => {
            const newest = index === turns.length - 1;
            const held = newest && turn.id === track.anchor;
            const size = index < settled ? sizes.get(turn.id) : undefined;
            const sizeStyle =
              size === undefined ? undefined : { containIntrinsicSize: `auto ${size}px` };
            return (
              <div
                className={cn(
                  "flex min-w-0 flex-col gap-4",
                  size !== undefined && "[content-visibility:auto]",
                  classNames?.turn
                )}
                data-settle={index < settled ? "true" : undefined}
                data-settled={size === undefined ? undefined : "true"}
                data-slot="chat-thread-turn"
                data-turn={turn.id}
                key={turn.id}
                style={
                  held
                    ? {
                        minHeight: `calc(var(--chat-thread-view) - ${PAD_TOP_PX + PAD_BOTTOM_PX}px)`,
                      }
                    : sizeStyle
                }
              >
                {turn.messages.map((message) => {
                  const last = message === lastMessage;
                  return (
                    <Row
                      animate={!track.baseline.has(message.id)}
                      key={message.id}
                      last={last}
                      message={message}
                      renderMessage={renderMessage}
                      streaming={last && status === "streaming"}
                    />
                  );
                })}
                {newest ? tail : null}
              </div>
            );
          })}
          {turns.length === 0 && !isEmpty ? (
            <div className="flex flex-col gap-4">{tail}</div>
          ) : null}
        </div>
      </div>

      <button
        aria-label={jumpLabel}
        className={cn(
          "absolute bottom-3 left-1/2 z-10 inline-flex size-8 -translate-x-1/2 cursor-pointer items-center justify-center rounded-sm border-0 bg-card p-0 text-card-foreground  transition-[opacity,scale,translate] ease-out active:scale-[0.96] motion-reduce:transition-none",
          away
            ? "translate-y-0 scale-100 opacity-100 duration-200"
            : "pointer-events-none translate-y-1 scale-95 opacity-0 duration-100",
          FOCUS_CLASS,
          classNames?.jump
        )}
        data-slot="chat-thread-jump"
        inert={!away}
        onClick={toEnd}
        title={jumpLabel}
        type="button"
      >
        <Icon className="size-4" icon={ArrowDown02Icon} />
      </button>
    </div>
  );
}