Skip to content

The platform for continuously improving AI agents.

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

import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Icon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";
import type { Cell, DatasetAnalytics, DatasetAnalyticsCheck } from "@/openapi";
import { Field } from "./field";

const alerting = (check: DatasetAnalyticsCheck) =>
  check.status === "error" || check.status === "warning";

function alertsOf(report: DatasetAnalytics) {
  return report.checks
    .filter(alerting)
    .sort((a, b) => Number(b.status === "error") - Number(a.status === "error"));
}

/** The version's warnings and errors, then how many checks did not run. */
export function CheckChips({ report }: { report: DatasetAnalytics }) {
  const alerts = alertsOf(report);
  const unchecked = report.checks.filter((check) => check.status === "not_checked").length;
  return (
    <span className="flex min-w-0 flex-wrap items-center gap-1">
      {alerts.slice(0, 2).map((check) => (
        <Badge
          key={check.id}
          size="chip"
          title={check.summary}
          variant={check.status === "error" ? "error" : "warning"}
        >
          {check.title}
        </Badge>
      ))}
      {alerts.length > 2 && (
        <Badge size="chip" variant="warning">
          +{alerts.length - 2}
        </Badge>
      )}
      {unchecked > 0 && (
        <Badge size="chip" variant="neutral">
          {unchecked} not checked
        </Badge>
      )}
    </span>
  );
}

/** For each imbalanced question: what always answering its majority label scores. */
function Imbalance({ check, report }: { check: DatasetAnalyticsCheck; report: DatasetAnalytics }) {
  const ids = (check.metrics as { families?: string[] } | null)?.families ?? [];
  const families = report.families.filter(
    (family) =>
      ids.includes(family.id) &&
      family.majorityBaseline != null &&
      family.counts?.length === family.labels.length
  );
  return families.map((family) => {
    const counts = family.counts!;
    const majority = counts.indexOf(Math.max(...counts));
    const minority = counts.indexOf(Math.min(...counts));
    return (
      <p className="leading-relaxed" key={family.id}>
        <span className="text-foreground">{family.question}</span> Predicting “
        {family.labels[majority]}” for every row scores{" "}
        {(family.majorityBaseline! * 100).toFixed(2)}% accuracy and misses all{" "}
        {counts[minority].toLocaleString()} “{family.labels[minority]}”{" "}
        {counts[minority] === 1 ? "row" : "rows"}.
      </p>
    );
  });
}

function CheckList({ title, checks }: { title: string; checks: DatasetAnalyticsCheck[] }) {
  const [open, setOpen] = useState(false);
  if (!checks.length) return null;
  return (
    <section>
      <button
        aria-expanded={open}
        className="flex items-center gap-1 text-muted-foreground hover:text-foreground"
        onClick={() => setOpen(!open)}
        type="button"
      >
        <Icon.chevronRight className={cn("size-3", open && "rotate-90")} />
        {checks.length} {title}
      </button>
      {open && (
        <dl className="mt-1 divide-y divide-border/60 border-y border-border/60">
          {checks.map((check) => (
            <div className="grid gap-1 py-1.5 sm:grid-cols-[11rem_minmax(0,1fr)]" key={check.id}>
              <dt className="text-foreground">{check.title}</dt>
              <dd className="break-words text-muted-foreground">{check.summary}</dd>
            </div>
          ))}
        </dl>
      )}
    </section>
  );
}

/** Every check measured on the version: findings first, then what passed and what did not run. */
export function CellChecks({ report }: { report: DatasetAnalytics }) {
  const alerts = alertsOf(report);
  return (
    <div aria-label="Checks" className="nodrag nowheel space-y-3 px-3 pb-3 text-xs">
      {alerts.map((check) => (
        <section className="space-y-1" key={check.id}>
          <h3
            className={cn(
              "flex items-center gap-1.5",
              check.status === "error" ? "text-destructive" : "text-warning"
            )}
          >
            <Icon.warning className="size-3 shrink-0" />
            {check.id === "targets.class_balance"
              ? "Accuracy alone is misleading here"
              : check.title}
          </h3>
          {check.id === "targets.class_balance" ? (
            <Imbalance check={check} report={report} />
          ) : (
            <p className="break-words leading-relaxed">{check.summary}</p>
          )}
        </section>
      ))}
      <CheckList checks={report.checks.filter((check) => check.status === "pass")} title="passed" />
      <CheckList
        checks={report.checks.filter((check) => check.status === "not_checked")}
        title="not checked"
      />
      <p className="text-muted-foreground" title={report.fingerprint}>
        {report.rowsScanned?.toLocaleString()} rows scanned · checks v{report.version}
      </p>
    </div>
  );
}

export interface CapabilityChoice {
  capability_id: string;
  name: string;
  score: number;
}

/** The dataset's capability, a warning when the version's rows do not match it, and a
 *  switch to another capability, ranked by how well the rows match it. */
export function CapabilityField({
  cell,
  current,
  name,
  ranked,
  onChange,
}: {
  cell: Cell;
  current: string | null;
  name: string;
  ranked: CapabilityChoice[];
  /** Absent while the dataset is busy or frozen. */
  onChange?: (capability: string | null) => void;
}) {
  const report = (cell.capabilityReport ?? {}) as { ok?: boolean; reason?: string };
  const mismatch = !!current && report.ok === false;
  const others = ranked.filter((choice) => choice.capability_id !== current);
  const value = (
    <>
      {mismatch && <Icon.warning className="size-3 shrink-0" />}
      <span className="truncate">
        {current ? (mismatch ? `Does not match ${name}` : name) : "None"}
      </span>
    </>
  );
  if (!onChange || (!current && !others.length))
    return (
      <Field
        label="Capability"
        title={mismatch ? report.reason : undefined}
        tone={mismatch ? "text-warning" : current ? "text-foreground" : "text-muted-foreground"}
      >
        {value}
      </Field>
    );
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          aria-label="Change capability"
          className="nodrag inline-flex rounded-sm focus-visible:outline focus-visible:outline-ring"
          title={mismatch ? report.reason : undefined}
          type="button"
        >
          <Field
            label="Capability"
            tone={mismatch ? "text-warning" : current ? "text-foreground" : "text-muted-foreground"}
          >
            {value}
            <Icon.chevronDown className="size-3 shrink-0 text-muted-foreground" />
          </Field>
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-64">
        {others.map((choice) => (
          <DropdownMenuItem
            key={choice.capability_id}
            onSelect={() => onChange(choice.capability_id)}
          >
            <span className="min-w-0 flex-1 truncate">{choice.name}</span>
            <span className="font-mono text-muted-foreground tabular-nums">
              {Math.round(choice.score * 100)}%
            </span>
          </DropdownMenuItem>
        ))}
        {current && (
          <>
            {others.length > 0 && <DropdownMenuSeparator />}
            <DropdownMenuItem onSelect={() => onChange(null)}>
              <Icon.capabilityOff className="size-4" />
              Remove capability
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}