Skip to content

The platform for continuously improving AI agents.

14.0 KB
Raw Blame
import { useMemo, useState } from "react";

import { useMutation, useQueryClient } from "@tanstack/react-query";

import apiClient from "@/client";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Dialog, DialogContent, DialogFooter, DialogTitle } from "@/components/ui/dialog";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { ListToolbar } from "@/components/ui/list-toolbar";
import { SearchInput } from "@/components/ui/search-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { LoadingState } from "@/components/ui/spinner";
import {
  useAllEvalRunsQuery,
  useEvalMatrixQuery,
  useEvalSetsQuery,
  useProjectCapabilitiesQuery,
} from "@/hooks/use-evaluations";
import { useGuestGate } from "@/hooks/use-guest-gate";
import { errorMessage } from "@/lib/notify";
import { cn } from "@/lib/utils";
import type { EvalRun, EvalSet } from "@/openapi";
import { CriteriaCard, type Criterion, saveBlocker } from "./criteria-card";
import { asRunSummary } from "./run-comparison";

const SAME_SETUP = [
  "dataset",
  "cell",
  "capabilityId",
  "judgeModel",
  "mode",
  "sampling",
  "maxItems",
] as const;

/** The newest completed run of a benchmark, and the one before it that used the same data and rubric. */
export function benchmarkHistory(runs: EvalRun[], setId: string) {
  const completed = runs
    .filter((run) => run.evalSet === setId && run.status === "completed")
    .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
  const [latest, ...older] = completed;
  const previous =
    latest &&
    older.find(
      (run) =>
        SAME_SETUP.every((key) => run[key] === latest[key]) &&
        JSON.stringify(run.matrix) === JSON.stringify(latest.matrix)
    );
  return { latest, previous };
}

const percent = (value: number | null | undefined) =>
  value == null || !Number.isFinite(value) ? "—" : `${(value * 100).toFixed(1)}%`;
const mean = (run: EvalRun | undefined, name: string) => {
  const value = asRunSummary(run?.summary).metrics?.[name]?.mean;
  return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const tone = (delta: number) =>
  delta > 0 ? "text-success" : delta < 0 ? "text-destructive" : "text-muted-foreground";

function BenchmarkCard({
  capability,
  criteria,
  linked,
  onEdit,
  runs,
  runsState,
  set,
}: {
  capability?: string;
  criteria: Criterion[];
  linked: boolean;
  onEdit: () => void;
  runs: EvalRun[];
  runsState: "loading" | "error" | "ready";
  set: EvalSet;
}) {
  const { latest, previous } = benchmarkHistory(runs, set.id);
  const summary = asRunSummary(latest?.summary);
  const before = asRunSummary(previous?.summary).score;
  const delta = summary.score != null && before != null ? summary.score - before : null;
  const names = latest ? Object.keys(summary.metrics ?? {}) : criteria.map((c) => c.name);
  const status =
    runsState === "loading"
      ? "Loading scores…"
      : runsState === "error"
        ? "Scores unavailable"
        : !latest
          ? "No completed runs"
          : delta == null
            ? "No comparable previous run"
            : delta === 0
              ? "Unchanged from previous run"
              : `${delta > 0 ? "+" : ""}${(delta * 100).toFixed(1)} points from previous run`;
  return (
    <Card className="flex max-h-80 flex-col gap-3 overflow-hidden p-3 transition-colors hover:border-muted-foreground">
      <div className="flex items-center gap-2">
        <span className="rounded-sm bg-muted p-1">
          <Icon.checkbox className="size-4 text-muted-foreground" />
        </span>
        <h3 className="min-w-0 flex-1 truncate text-sm font-medium">
          {set.name}
          {capability && (
            <span className="ml-2 font-normal text-muted-foreground">{capability}</span>
          )}
        </h3>
      </div>
      <div className="flex items-center justify-between rounded-sm bg-muted px-2 py-1.5 text-xs">
        <span className="truncate">{latest?.modelName || latest?.name || "Latest run"}</span>
        <span className="tabular-nums">{percent(summary.score)}</span>
      </div>
      <p className={cn("text-xs text-muted-foreground", delta != null && tone(delta))}>{status}</p>
      <div className="min-h-0 flex-1 overflow-y-auto scroll-fade-y text-xs">
        <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_3rem_3rem] gap-2 pb-1 text-muted-foreground">
          <span>Criteria</span>
          <span>○ Before ● Now</span>
          <span className="text-right">Score</span>
          <span className="text-right">Δ pp</span>
        </div>
        {names.map((name) => {
          const now = mean(latest, name);
          const was = mean(previous, name);
          const change = now != null && was != null ? now - was : null;
          return (
            <div
              className="grid h-7 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_3rem_3rem] items-center gap-2"
              key={name}
            >
              <span className="truncate">{name}</span>
              <span className={cn("relative h-2.5", change != null && tone(change))}>
                <span className="absolute inset-x-0 top-1/2 h-px bg-border" />
                {was != null && now != null && (
                  <span
                    className="absolute top-1/2 h-px bg-current"
                    style={{
                      left: `${Math.min(was, now) * 100}%`,
                      width: `${Math.abs(now - was) * 100}%`,
                    }}
                  />
                )}
                {was != null && (
                  <span
                    className="absolute top-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-xs bg-muted-foreground"
                    style={{ left: `${was * 100}%` }}
                  />
                )}
                {now != null && (
                  <span
                    className="absolute top-1/2 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-xs border border-card bg-current text-foreground"
                    style={{ left: `${now * 100}%` }}
                  />
                )}
              </span>
              <span className="text-right tabular-nums">{percent(now)}</span>
              <span className={cn("text-right tabular-nums", change != null && tone(change))}>
                {change == null
                  ? "—"
                  : change === 0
                    ? "="
                    : `${change > 0 ? "+" : ""}${(change * 100).toFixed(1)}`}
              </span>
            </div>
          );
        })}
      </div>
      <div className="flex items-center justify-between gap-2 border-t border-border/70 pt-3 text-xs text-muted-foreground">
        <span className="truncate">
          {latest?.completedAt
            ? `${latest.completedAt.toLocaleDateString()} · ${summary.scored ?? 0} scored`
            : `${criteria.length} criteria`}
          {linked && " · Follows online evaluations"}
        </span>
        {!linked && (
          <Button onClick={onEdit} size="xs" variant="secondary">
            Edit
          </Button>
        )}
      </div>
    </Card>
  );
}

function BenchmarkEditor({
  onClose,
  projectId,
  set,
}: {
  onClose: () => void;
  projectId: string;
  set?: EvalSet;
}) {
  const queryClient = useQueryClient();
  const [name, setName] = useState(set?.name ?? "");
  const [criteria, setCriteria] = useState<Criterion[]>(
    (set?.criteria as Criterion[] | null) ?? []
  );
  const save = useMutation({
    mutationFn: () => {
      const body = {
        criteria: criteria.map((c) => ({ ...c, name: c.name.trim() })),
        name: name.trim(),
      };
      return set
        ? apiClient.evalSets.evalSetsPartialUpdate({ id: set.id, patchedEvalSetRequest: body })
        : apiClient.evalSets.evalSetsCreate({ evalSetRequest: { ...body, project: projectId } });
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["eval-sets"] });
      onClose();
    },
  });
  const blocker = saveBlocker(name, criteria);
  return (
    <Dialog onOpenChange={(open) => !open && onClose()} open>
      <DialogContent size={criteria.some((c) => c.type === "deterministic") ? "md" : "sm"}>
        <DialogTitle className="sr-only">{set ? "Edit benchmark" : "Create benchmark"}</DialogTitle>
        <div aria-busy={save.isPending} inert={save.isPending}>
          <CriteriaCard
            criteria={criteria}
            name={name}
            onChange={setCriteria}
            onNameChange={setName}
          />
        </div>
        <DialogFooter className="items-center">
          <p aria-live="polite" className="mr-auto text-xs text-muted-foreground">
            {save.error ? errorMessage(save.error, "Could not save benchmark.") : blocker}
          </p>
          <Button onClick={onClose} size="xs" variant="secondary">
            Cancel
          </Button>
          <Button disabled={!!blocker || save.isPending} onClick={() => save.mutate()} size="xs">
            {save.isPending ? "Saving…" : "Save benchmark"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

/** Offline benchmarks: each one's criteria and how its latest run compares with the one before. */
export function BenchmarkLibrary({ projectId }: { projectId: string }) {
  const guard = useGuestGate();
  const sets = useEvalSetsQuery(projectId);
  const matrix = useEvalMatrixQuery(projectId);
  const capabilities = useProjectCapabilitiesQuery(projectId);
  const capabilityName = useMemo(
    () => new Map((capabilities.data?.results ?? []).map((c) => [c.id, c.name || c.slug])),
    [capabilities.data]
  );
  const runs = useAllEvalRunsQuery(projectId);
  const [search, setSearch] = useState("");
  const [type, setType] = useState("all");
  const [status, setStatus] = useState("all");
  const [editing, setEditing] = useState<EvalSet | "new" | null>(null);

  const rowsById = useMemo(
    () => new Map((matrix.data ?? []).map((row) => [row.id, row])),
    [matrix.data]
  );
  const benchmarks = (sets.data?.results ?? [])
    .filter((set) => set.project === projectId)
    .map((set) => {
      const linked = set.criteria == null;
      const criteria: Criterion[] = linked
        ? (set.rows ?? []).flatMap((id) => {
            const row = rowsById.get(id);
            return row ? [{ name: row.name, source: row.source, type: row.type }] : [];
          })
        : (set.criteria as Criterion[]);
      return { criteria, linked, set };
    })
    .filter(({ criteria, set }) => {
      const q = search.trim().toLowerCase();
      const text = [set.name, set.description, ...criteria.flatMap((c) => [c.name, c.source])].join(
        " "
      );
      return (
        (!q || text.toLowerCase().includes(q)) &&
        (type === "all" || criteria.some((c) => c.type === type)) &&
        (status === "all" || (status === "active") === !!set.isActive)
      );
    });
  const filtered = !!search || type !== "all" || status !== "all";

  return (
    <div className="flex min-h-0 flex-1 flex-col gap-3">
      <ListToolbar
        filters={
          <>
            <Select onValueChange={setType} value={type}>
              <SelectTrigger aria-label="Criterion type" className="w-[150px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All types</SelectItem>
                <SelectItem value="llm">Judge</SelectItem>
                <SelectItem value="deterministic">Deterministic</SelectItem>
              </SelectContent>
            </Select>
            <Select onValueChange={setStatus} value={status}>
              <SelectTrigger aria-label="Benchmark status" className="w-[140px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All statuses</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="inactive">Inactive</SelectItem>
              </SelectContent>
            </Select>
          </>
        }
        hasActiveFilters={filtered}
        onClearFilters={() => {
          setSearch("");
          setType("all");
          setStatus("all");
        }}
        primary={
          <Button onClick={guard(() => setEditing("new"))}>
            <Icon.add />
            Create benchmark
          </Button>
        }
        search={
          <SearchInput
            className="min-w-0 flex-1"
            label="Search benchmarks"
            onChange={(e) => setSearch(e.target.value)}
            onClear={() => setSearch("")}
            placeholder="Search benchmarks…"
            value={search}
          />
        }
      />
      {sets.isLoading ? (
        <LoadingState label="Loading benchmarks" />
      ) : sets.error ? (
        <p className="text-sm text-destructive" role="alert">
          Benchmarks could not be loaded.
        </p>
      ) : !benchmarks.length ? (
        <EmptyState
          icon={Icon.evaluations}
          size="section"
          title={filtered ? "No matching benchmarks" : "No benchmarks yet"}
        />
      ) : (
        <div className="min-h-0 flex-1 overflow-y-auto scroll-fade-y">
          <div className="grid gap-4 lg:grid-cols-2 2xl:grid-cols-3">
            {benchmarks.map(({ criteria, linked, set }) => (
              <BenchmarkCard
                capability={set.capability ? capabilityName.get(set.capability) : undefined}
                criteria={criteria}
                key={set.id}
                linked={linked}
                onEdit={guard(() => setEditing(set))}
                runs={runs.data?.results ?? []}
                runsState={runs.isLoading ? "loading" : runs.error ? "error" : "ready"}
                set={set}
              />
            ))}
          </div>
        </div>
      )}
      {editing && (
        <BenchmarkEditor
          onClose={() => setEditing(null)}
          projectId={projectId}
          set={editing === "new" ? undefined : editing}
        />
      )}
    </div>
  );
}