Skip to content

The platform for continuously improving AI agents.

5.8 KB
Raw Blame
import type { ReactNode, Ref } from "react";

import { Button } from "@/components/ui/button";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { Icon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";

const kinds = {
  Benchmark: Icon.evaluations,
  Capability: Icon.capability,
  Dataset: Icon.dataset,
  "Dataset version": Icon.dataset,
  "Evaluation run": Icon.evaluations,
  Experiment: Icon.ai,
  Model: Icon.inferenceTitle,
  Step: Icon.gitBranch,
  "Training run": Icon.finetuning,
};

type CitationKind = keyof typeof kinds;
type CitationRange = { start: number; end: number; entity: { href: string } };
export type CitationTarget =
  | { kind: CitationKind; href: string }
  | { kind: CitationKind; onOpen: () => void; title?: string };
export type ResolveCitation = (href: string) => CitationTarget | undefined;
const citationFace = "rounded-sm border-border/70";

export const entityCitation: ResolveCitation = (href) => {
  if (!href.startsWith("/") || href.startsWith("//") || /[\\\s]/.test(href)) return;
  const base = "https://overmind.invalid";
  const url = new URL(href, base);
  if (url.origin !== base) return;
  const { pathname, searchParams } = url;
  const routes = [
    [/^\/datasets\/[^/]+\/?$/, searchParams.has("cell") ? "Dataset version" : "Dataset"],
    [/^\/evaluations\/runs\/[^/]+\/?$/, "Evaluation run"],
    [/^\/capabilities\/[^/]+\/?$/, "Capability"],
    [/^\/experiments\/[^/]+\/?$/, "Experiment"],
    [/^\/inference\/[^/]+\/?$/, "Model"],
  ] as const;
  const kind = routes.find(([path]) => path.test(pathname))?.[1];
  if (kind) return { href, kind };
  if (/^\/evaluations\/?$/.test(pathname) && searchParams.get("evalSet"))
    return { href, kind: "Benchmark" };
  if (/^\/training\/?$/.test(pathname) && searchParams.get("groupId"))
    return { href, kind: "Training run" };
};

export function ChatInlineCitation({
  target,
  children,
}: {
  target: CitationTarget;
  children: ReactNode;
}) {
  const Glyph = kinds[target.kind];
  const label = (
    <>
      <Glyph aria-hidden className="size-3 shrink-0 text-muted-foreground" />
      <span className="min-w-0 truncate">{children}</span>
    </>
  );
  const className = cn(
    citationFace,
    "mx-0.5 inline-flex max-w-full gap-1 px-1.5 align-baseline text-xs leading-4"
  );

  return (
    <HoverCard closeDelay={150} openDelay={200}>
      <HoverCardTrigger asChild>
        {"href" in target ? (
          <Button
            asChild
            className={className}
            data-slot="chat-inline-citation"
            size="xs"
            variant="secondary"
          >
            <a href={target.href}>{label}</a>
          </Button>
        ) : (
          <Button
            className={className}
            data-slot="chat-inline-citation"
            onClick={target.onOpen}
            size="xs"
            type="button"
            variant="secondary"
          >
            {label}
          </Button>
        )}
      </HoverCardTrigger>
      <HoverCardContent
        className="flex max-w-[calc(100vw-1.5rem)] flex-col gap-1 p-3 text-xs"
        sideOffset={4}
      >
        <span className="text-muted-foreground">{target.kind}</span>
        <span className="break-words font-medium">
          {"title" in target ? (target.title ?? children) : children}
        </span>
      </HoverCardContent>
    </HoverCard>
  );
}

function* citationLinks(text: string) {
  for (const match of text.matchAll(/(?<![\\!])\[((?:\\.|[^[\]\\\n])+)\]\(([^\s()]+)\)/g)) {
    yield {
      end: match.index + match[0].length,
      href: match[2],
      label: match[1].replace(/\\([\\[\]])/g, "$1"),
      start: match.index,
    };
  }
}

function draftCitationKind(href: string): CitationKind | undefined {
  if (href.startsWith("#node=")) return "Step";
  if (href.startsWith("#cell=")) return "Dataset version";
  return entityCitation(href)?.kind;
}

export function readCitationDraft(source: string) {
  const ranges: CitationRange[] = [];
  let text = "";
  let cursor = 0;
  for (const { start, end, href, label } of citationLinks(source)) {
    if (!draftCitationKind(href)) continue;
    text += source.slice(cursor, start);
    ranges.push({ end: text.length + label.length, entity: { href }, start: text.length });
    text += label;
    cursor = end;
  }
  return { ranges, text: text + source.slice(cursor) };
}

export function ChatCitationDraft({
  className,
  ranges,
  text,
  ref,
}: {
  className?: string;
  ranges: CitationRange[];
  text: string;
  ref: Ref<HTMLDivElement>;
}) {
  const nodes: ReactNode[] = [];
  let cursor = 0;
  for (const { start, end, entity } of ranges) {
    const kind = draftCitationKind(entity.href);
    const Glyph = kind ? kinds[kind] : Icon.link;
    const label = text.slice(start, end);
    nodes.push(
      text.slice(cursor, start),
      <span
        // The padding and negative margins cancel so the mirror still follows the textarea's wrapping.
        className="-mx-1 box-decoration-clone rounded-sm bg-control px-1 py-1 outline outline-border/70 -outline-offset-1"
        data-slot="chat-inline-citation"
        key={start}
      >
        {label.startsWith("@") ? (
          <span className="relative">
            <span className="invisible">@</span>
            <Glyph className="absolute top-1/2 -left-0.5 size-2.5 -translate-y-1/2 text-muted-foreground" />
          </span>
        ) : null}
        {label.startsWith("@") ? label.slice(1) : label}
      </span>
    );
    cursor = end;
  }
  return (
    <div
      aria-hidden
      className={cn(
        className,
        "pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words text-foreground",
        !text && "invisible"
      )}
      ref={ref}
    >
      {nodes}
      {text.slice(cursor)}
      <br />
    </div>
  );
}