Skip to content

The platform for continuously improving AI agents.

9.2 KB
Raw Blame
// Adapted from AI SDK Agents quality-trend and eval-run-history; see NOTICE.md.
import { useState } from "react";

export interface ExecutionPoint {
  id: string;
  label: string;
  x: number;
  value: number | null;
}
export interface ExecutionMetric {
  id: string;
  label: string;
  points: ExecutionPoint[];
  unit?: "percent";
  direction?: "higher" | "lower";
  baseline?: number;
  baselineLabel?: string;
  xLabel?: string;
}

export function ExecutionTrend({
  metrics,
  history = false,
  title,
}: {
  metrics: ExecutionMetric[];
  history?: boolean;
  title?: string;
}) {
  const [selected, setSelected] = useState("");
  const [hovered, setHovered] = useState<string | null>(null);
  const metric = metrics.find((item) => item.id === selected) ?? metrics[0];
  const points =
    metric?.points.filter(
      (point) => point.value != null && Number.isFinite(point.value) && Number.isFinite(point.x)
    ) ?? [];
  const focus = points.find((point) => point.id === hovered) ?? points.at(-1);
  const baseline =
    metric?.baseline != null && Number.isFinite(metric.baseline) ? metric.baseline : undefined;
  const values = points.map((point) => point.value!);
  if (baseline !== undefined) values.push(baseline);
  const min = Math.min(...values);
  const max = Math.max(...values);
  const start = Math.min(...points.map((point) => point.x));
  const end = Math.max(...points.map((point) => point.x));
  const x = (point: ExecutionPoint) =>
    24 + (end === start ? 0.5 : (point.x - start) / (end - start)) * 452;
  const y = (point: ExecutionPoint) =>
    108 - (max === min ? 0.5 : (point.value! - min) / (max - min)) * 88;
  const format = (value: number, item = metric) =>
    item?.unit === "percent"
      ? `${(value * 100).toFixed(1)}%`
      : new Intl.NumberFormat(undefined, { maximumSignificantDigits: 4 }).format(value);
  const difference = focus && baseline !== undefined ? focus.value! - baseline : undefined;
  const delta =
    difference === undefined
      ? undefined
      : `${difference > 0 ? "+" : ""}${metric?.unit === "percent" ? `${(difference * 100).toFixed(1)} pp` : format(difference)}`;
  return (
    <section
      aria-label={title ?? (history ? "Evaluation history" : "Training metrics")}
      className="space-y-4"
    >
      <div aria-live="polite" className="flex items-center gap-3 py-1">
        <strong className="text-2xl font-medium tabular-nums text-foreground">
          {focus ? format(focus.value!) : "—"}
        </strong>
        <span className="text-xs text-muted-foreground">
          <span className="block font-medium text-foreground">{metric?.label}</span>
          <span className="block mt-0.5">{focus ? focus.label : "Not measured"}</span>
          {delta && (
            <span className="block mt-1">
              {delta} vs {metric.baselineLabel ?? "baseline"} ({format(baseline!)})
            </span>
          )}
          {metric?.direction && (
            <span className="block mt-1">
              {metric.direction === "higher" ? "Higher is better" : "Lower is better"}
            </span>
          )}
        </span>
      </div>
      {points.length > 0 && (
        <div className="space-y-2">
          <div className="text-xs text-muted-foreground">
            {metric.label}
            {metric.unit === "percent" ? " (%)" : ""}
          </div>
          <div className="flex gap-2">
            <div
              aria-label="Y axis"
              className="flex w-14 shrink-0 flex-col justify-between py-5 text-right text-xs tabular-nums text-muted-foreground"
            >
              <span>{format(max)}</span>
              <span>{format((max + min) / 2)}</span>
              <span>{format(min)}</span>
            </div>
            <div className="min-w-0 flex-1">
              <svg
                aria-label={`${metric.label} trend. Use arrow keys to inspect recorded points.`}
                className="h-36 w-full text-cat-3 outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
                onKeyDown={(event) => {
                  if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
                  event.preventDefault();
                  const index = points.findIndex((point) => point.id === focus?.id);
                  const next =
                    event.key === "Home"
                      ? 0
                      : event.key === "End"
                        ? points.length - 1
                        : Math.max(
                            0,
                            Math.min(
                              points.length - 1,
                              index + (event.key === "ArrowLeft" ? -1 : 1)
                            )
                          );
                  setHovered(points[next].id);
                }}
                onPointerLeave={() => setHovered(null)}
                onPointerMove={(event) => {
                  const bounds = event.currentTarget.getBoundingClientRect();
                  const position = ((event.clientX - bounds.left) / bounds.width) * 500;
                  const nearest = points.reduce((best, point) =>
                    Math.abs(x(point) - position) < Math.abs(x(best) - position) ? point : best
                  );
                  setHovered(nearest.id);
                }}
                preserveAspectRatio="none"
                role="img"
                // biome-ignore lint/a11y/noNoninteractiveTabindex: arrow keys inspect the recorded chart points
                tabIndex={0}
                viewBox="0 0 500 128"
              >
                <title>{metric.label}</title>
                {[20, 64, 108].map((row) => (
                  <path
                    className="text-border"
                    d={`M24 ${row}H476`}
                    key={row}
                    stroke="currentColor"
                    strokeDasharray="2 4"
                  />
                ))}
                {baseline !== undefined && (
                  <path
                    className="text-muted-foreground"
                    d={`M24 ${y({ id: "baseline", label: "Baseline", value: baseline, x: start })}H476`}
                    stroke="currentColor"
                    strokeDasharray="5 4"
                  />
                )}
                <polyline
                  fill="none"
                  points={points.map((point) => `${x(point)},${y(point)}`).join(" ")}
                  stroke="currentColor"
                  strokeWidth="2"
                />
                {focus && <circle cx={x(focus)} cy={y(focus)} fill="currentColor" r="4" />}
              </svg>
              <div
                aria-label="X axis"
                className="flex justify-between gap-3 px-3 text-xs text-muted-foreground"
              >
                <span>{history ? points[0]?.label : start}</span>
                <span>{history ? points.at(-1)?.label : end}</span>
              </div>
            </div>
          </div>
          <div className="text-center text-xs text-muted-foreground">
            {metric.xLabel ?? (history ? "Compared models" : "Training step")}
          </div>
          {baseline !== undefined && (
            <p className="text-xs text-muted-foreground">
              Dashed line: {metric.baselineLabel ?? "Baseline"} · {format(baseline)}
            </p>
          )}
        </div>
      )}
      <div aria-label="Metrics" className="space-y-1">
        {metrics.map((item) => {
          const latest = item.points
            .filter((point) => point.value != null && Number.isFinite(point.value))
            .at(-1);
          return (
            <button
              aria-label={item.label}
              aria-pressed={metric.id === item.id}
              className={`flex w-full items-center justify-between gap-3 rounded-sm px-2 py-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring ${metric.id === item.id ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-wash-subtle"}`}
              key={item.id}
              onClick={() => {
                setSelected(item.id);
                setHovered(null);
              }}
              type="button"
            >
              <span>{item.label}</span>
              <span className="tabular-nums text-foreground">
                {latest ? format(latest.value!, item) : "—"}
              </span>
            </button>
          );
        })}
      </div>
      {history && (
        <ol aria-label="Compared runs" className="space-y-1">
          {[...(metric?.points ?? [])].reverse().map((point) => (
            <li key={point.id}>
              <button
                className="flex w-full items-center justify-between gap-3 rounded-sm px-2 py-2 text-left text-sm hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
                onClick={() => setHovered(point.id)}
                onFocus={() => setHovered(point.id)}
                onPointerEnter={() => setHovered(point.id)}
                type="button"
              >
                <span className="truncate">{point.label}</span>
                <span className="tabular-nums">
                  {point.value == null ? "Not measured" : format(point.value)}
                </span>
              </button>
            </li>
          ))}
        </ol>
      )}
    </section>
  );
}