Skip to content

The platform for continuously improving AI agents.

5.2 KB
Raw Blame
import { useState } from "react";

import { FileDiff } from "@/components/ai-components/file-diff";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import type { ChatEvalSetDefinition, ChatEvalSetDraft } from "@/openapi";
import { CriteriaCard, type Criterion, saveBlocker } from "./criteria-card";

export type BenchmarkReviewStatus = "pending" | "approved" | "rejected" | "cancelled";

type BenchmarkReviewProps = {
  draft: ChatEvalSetDraft;
  status: BenchmarkReviewStatus;
  disabled?: boolean;
  onDecide: (approved: boolean, text: string, criteria?: Criterion[]) => Promise<void>;
};

const STATUS_WORD: Record<BenchmarkReviewStatus, string> = {
  approved: "Saved",
  cancelled: "Cancelled",
  pending: "Awaiting review",
  rejected: "Rejected",
};

// The benchmark as one file, so an amendment reads as a diff of it.
const benchmarkFile = ({
  name,
  description,
  criteria,
}: Pick<ChatEvalSetDefinition, "name" | "description"> & { criteria: Criterion[] }) =>
  [
    `name: ${name}`,
    ...(description ? [`description: ${description}`] : []),
    ...criteria.flatMap((criterion) => [
      "",
      `## ${criterion.name} · ${criterion.type === "deterministic" ? "python" : (criterion.output ?? "llm")}`,
      ...criterion.source.trimEnd().split("\n"),
      ...(criterion.options ?? []).map((option) => `- ${option.label}: ${option.score}`),
    ]),
  ].join("\n");

export const BenchmarkReview = ({ draft, status, disabled, onDecide }: BenchmarkReviewProps) => {
  const [criteria, setCriteria] = useState<Criterion[]>(draft.criteria);
  const [rejecting, setRejecting] = useState(false);
  const [reason, setReason] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const pending = status === "pending";
  const editable = pending && !disabled && !sending;
  // A decided review shows what was saved, not what was being edited.
  const shown = pending ? criteria : draft.criteria;
  const blocker = pending ? saveBlocker(draft.name, criteria) : null;
  const amendment = draft.current !== null;

  const handleDecide = async (approved: boolean) => {
    setSending(true);
    setError(null);
    try {
      await onDecide(
        approved,
        approved ? "Approved" : reason.trim() || "Rejected",
        approved ? criteria : undefined
      );
    } catch {
      setError(approved ? "Could not save the benchmark." : "Could not reject the draft.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section
      aria-label={`${amendment ? "Benchmark amendment" : "Benchmark draft"}: ${draft.name}`}
      className="flex flex-col gap-2 text-xs"
      data-slot="benchmark-review"
      data-status={status}
    >
      <div className="flex items-center justify-between gap-3 text-muted-foreground">
        <span>{amendment ? "Benchmark amendment" : "Benchmark draft"}</span>
        <span>{STATUS_WORD[status]}</span>
      </div>
      <p className="leading-5 wrap-anywhere">{draft.rationale}</p>
      <CriteriaCard
        className="max-h-96"
        criteria={shown}
        description={draft.description || undefined}
        footer={
          pending ? (
            <>
              <p
                aria-live="polite"
                className="min-w-0 basis-full wrap-anywhere text-xs text-destructive empty:hidden"
              >
                {error ?? blocker}
              </p>
              {rejecting && (
                <Textarea
                  aria-label="Reason for rejecting"
                  className="min-h-14 basis-full text-xs md:text-xs"
                  disabled={!editable}
                  onChange={(event) => setReason(event.target.value)}
                  placeholder="Reason (optional)"
                  value={reason}
                />
              )}
              <Button
                disabled={!editable}
                onClick={() => (rejecting ? void handleDecide(false) : setRejecting(true))}
                size="xs"
                variant="secondary"
              >
                {rejecting ? "Confirm reject" : "Reject"}
              </Button>
              {rejecting ? (
                <Button
                  disabled={!editable}
                  onClick={() => setRejecting(false)}
                  size="xs"
                  variant="secondary"
                >
                  Back
                </Button>
              ) : (
                <Button
                  disabled={!editable || blocker !== null}
                  onClick={() => void handleDecide(true)}
                  size="xs"
                >
                  {sending && <Spinner size="sm" />}
                  {amendment ? "Apply amendment" : "Save benchmark"}
                </Button>
              )}
            </>
          ) : undefined
        }
        name={draft.name}
        onChange={editable ? setCriteria : undefined}
      />
      {draft.current && (
        <FileDiff
          after={benchmarkFile({ ...draft, criteria: shown })}
          before={benchmarkFile(draft.current)}
          file={`${draft.name}.benchmark`}
        />
      )}
    </section>
  );
};