All files / src/apps/user/pages/evaluation Reports.tsx

94.44% Statements 34/36
89.58% Branches 43/48
87.5% Functions 14/16
94.44% Lines 34/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309                                                                                          1x               1x                 1x 5x   1x       168x                   1x 28x 28x 28x 28x 28x   28x               28x     11x   28x   28x   12x   28x   28x   14x   28x         28x     28x   28x                                                   1x       3x                 1x     112x                   1x           112x                                                   56x                                                         5x 5x                                                                                                                                                  
/**
 * Cross-evaluation reporting.
 *
 * Every other evaluation screen looks at one evaluation or one dataset. This one
 * looks across all of them, which is the thing that was impossible while
 * batches lived as a JSON array inside each experiment's config: a question
 * like "which batches scored below 0.7 this month" had no query to answer it.
 *
 * Every filter here is applied by the backend in SQL. The page holds the
 * filter state and nothing else — it deliberately does not fetch everything
 * and narrow it in the browser, because that is the shape the table exists to
 * replace.
 */
 
import {
  BatchReportRow,
  BatchReportTotals,
  EvaluationScorer,
  ScorerInfo,
  TestSuite,
} from "@/objects/Evaluation";
import { useScorerCatalogue } from "@/hooks/useScorerCatalogue";
import { QUERY_KEYS, INCLUDE_SYSTEM } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { BarChart3, FlaskConical } from "lucide-react";
import React, { useState } from "react";
import { Link } from "react-router-dom";
import {
  EmptyBlock,
  Field,
  RegressionBadge,
  ScoreBadge,
  SectionCard,
  Select,
  Skeleton,
  datasetHref,
  experimentHref,
  formatDuration,
  formatScore,
  formatTimestamp,
  formatTokens,
} from "./components";
 
/** Windows worth offering. Each is a `days` value the backend cuts on. */
const WINDOWS: { label: string; days: number }[] = [
  { label: "Last 7 days", days: 7 },
  { label: "Last 30 days", days: 30 },
  { label: "Last 90 days", days: 90 },
  { label: "Last year", days: 365 },
];
 
/** Score ceilings, for finding the batches worth looking at first. */
const SCORE_FILTERS: { label: string; max?: number }[] = [
  { label: "Any score" },
  { label: "Below 0.9", max: 0.9 },
  { label: "Below 0.7", max: 0.7 },
  { label: "Below 0.5", max: 0.5 },
];
 
/** A run belongs to an evaluation, and asked a dataset. Both link, the
 *  dataset only while it still exists. */
const rowDatasetHref = (row: BatchReportRow): string | null =>
  row.dataset_id ? datasetHref(row.dataset_id) : null;
 
const Stat: React.FC<{ label: string; value: React.ReactNode }> = ({
  label,
  value,
}) => (
  <div className="px-3 py-2">
    <div className="text-[10px] uppercase tracking-wide font-medium text-gray-400 dark:text-gray-500">
      {label}
    </div>
    <div className="text-sm font-mono tabular-nums text-gray-900 dark:text-gray-100">
      {value}
    </div>
  </div>
);
 
const Reports: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const [days, setDays] = useState(30);
  const [maxScore, setMaxScore] = useState<number | undefined>(undefined);
  const [scorer, setScorer] = useState<EvaluationScorer | "">("");
  const [datasetId, setDatasetId] = useState("");
 
  const filters = {
    days,
    ...(maxScore !== undefined ? { max_mean_score: maxScore } : {}),
    ...(scorer ? { scorer } : {}),
    ...(datasetId ? { dataset_id: datasetId } : {}),
  };
 
  // Gold datasets included: a run on one is a run like any other here.
  const { data: datasetData } = useQuery<TestSuite[]>({
    queryKey: [QUERY_KEYS.GET.TEST_SUITES, INCLUDE_SYSTEM],
    queryFn: () =>
      getApiHandler().evaluation_router.listTestSuites({ includeSystem: true }),
  });
  const datasets: TestSuite[] = datasetData ?? [];
 
  const { data: totalsData } = useQuery<BatchReportTotals | null>({
    queryKey: [QUERY_KEYS.GET.BATCH_REPORT_SUMMARY, days],
    queryFn: () => getApiHandler().evaluation_router.reportSummary({ days }),
  });
  const totals: BatchReportTotals | null = totalsData ?? null;
 
  const { data: rowData, isLoading } = useQuery<BatchReportRow[]>({
    queryKey: [QUERY_KEYS.GET.BATCH_REPORT, days, maxScore, scorer, datasetId],
    queryFn: () => getApiHandler().evaluation_router.reportBatches(filters),
  });
  const rows: BatchReportRow[] = rowData ?? [];
 
  // Every scorer, superseded ones included: this filters historical runs,
  // and a run graded by a scorer no longer offered is exactly the run
  // somebody is looking for when they filter by it.
  const { all: scorers } = useScorerCatalogue();
  // Bound explicitly: the pinned TypeScript cannot infer react-query v5's
  // return type through the hook, so the map callback lands as an implicit any.
  const scorerOptions: ScorerInfo[] = scorers;
 
  return (
    <div className="space-y-5">
      <SectionCard
        icon={BarChart3}
        title="Across every experiment"
        subtitle="aggregated over each completed run in the window"
      >
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 divide-x divide-y sm:divide-y-0 divide-gray-100 dark:divide-gray-700">
          <Stat label="Runs" value={totals?.batches ?? "—"} />
          <Stat label="Experiments" value={totals?.experiments ?? "—"} />
          <Stat label="Mean score" value={formatScore(totals?.mean_score)} />
          <Stat label="Cases" value={totals?.cases ?? "—"} />
          <Stat label="Errors" value={totals?.errors ?? "—"} />
          <Stat label="Tokens" value={formatTokens(totals?.total_tokens)} />
        </div>
      </SectionCard>
 
      <SectionCard
        icon={FlaskConical}
        title="Completed runs"
        subtitle="newest first — filtered by the backend, not in the browser"
      >
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-3 mb-4">
          <Field label="Dataset">
            <Select
              value={datasetId}
              onChange={(e) => setDatasetId(e.target.value)}
            >
              <option value="">Any dataset</option>
              {datasets.map((d) => (
                <option key={d.id} value={d.id}>
                  {d.name}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Window">
            <Select
              value={String(days)}
              onChange={(e) => setDays(Number(e.target.value))}
            >
              {WINDOWS.map((w) => (
                <option key={w.days} value={w.days}>
                  {w.label}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Score">
            <Select
              value={maxScore === undefined ? "" : String(maxScore)}
              onChange={(e) =>
                setMaxScore(
                  e.target.value === "" ? undefined : Number(e.target.value),
                )
              }
            >
              {SCORE_FILTERS.map((f) => (
                <option key={f.label} value={f.max ?? ""}>
                  {f.label}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Scorer">
            <Select
              value={scorer}
              onChange={(e) =>
                setScorer(e.target.value as EvaluationScorer | "")
              }
            >
              <option value="">Any scorer</option>
              {scorerOptions.map((s) => (
                <option key={s.kind} value={s.kind}>
                  {s.label}
                </option>
              ))}
            </Select>
          </Field>
        </div>
 
        {isLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-10 w-full" />
            ))}
          </div>
        ) : rows.length === 0 ? (
          <EmptyBlock
            icon={BarChart3}
            message="No completed runs match."
            hint="Widen the window, or run an experiment to produce one."
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="text-gray-400 dark:text-gray-500">
                <tr className="text-left">
                  <th className="font-medium py-1.5 pr-3">Experiment</th>
                  <th className="font-medium py-1.5 pr-3">Dataset</th>
                  <th className="font-medium py-1.5 pr-3">Run</th>
                  <th className="font-medium py-1.5 pr-3">Verdict</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Score</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Passed</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Cases</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Errors</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Tokens</th>
                  <th className="font-medium py-1.5 pr-3 text-right">Took</th>
                  <th className="font-medium py-1.5 text-right">Finished</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                {rows.map((row) => {
                  const dataset = rowDatasetHref(row);
                  return (
                    <tr key={row.batch_id}>
                      <td className="py-1.5 pr-3">
                        <Link
                          to={experimentHref(row.experiment_id)}
                          className="text-gray-700 dark:text-gray-300 hover:underline"
                        >
                          {row.experiment_name}
                        </Link>
                      </td>
                      <td className="py-1.5 pr-3 text-gray-500 dark:text-gray-400">
                        {dataset ? (
                          <Link to={dataset} className="hover:underline">
                            {row.dataset_name ?? "Dataset"}
                          </Link>
                        ) : (
                          <span className="italic">deleted</span>
                        )}
                      </td>
                      <td className="py-1.5 pr-3 text-gray-500 dark:text-gray-400">
                        {row.label ?? "—"}
                        {row.variants > 1 && (
                          <span className="ml-1.5 text-gray-400 dark:text-gray-500">
                            · {row.variants} variants
                          </span>
                        )}
                      </td>
                      <td className="py-1.5 pr-3">
                        <RegressionBadge
                          verdict={row.regression_verdict}
                          size="xs"
                        />
                      </td>
                      <td className="py-1.5 pr-3 text-right">
                        <ScoreBadge value={row.mean_score} />
                      </td>
                      <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-500 dark:text-gray-400">
                        {formatScore(row.pass_rate)}
                      </td>
                      <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-500 dark:text-gray-400">
                        {row.total_cases ?? "—"}
                      </td>
                      <td
                        className={`py-1.5 pr-3 text-right font-mono tabular-nums ${
                          row.errors
                            ? "text-red-600 dark:text-red-400"
                            : "text-gray-400 dark:text-gray-500"
                        }`}
                      >
                        {row.errors ?? "—"}
                      </td>
                      <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-500 dark:text-gray-400">
                        {formatTokens(row.total_tokens)}
                      </td>
                      <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-500 dark:text-gray-400">
                        {formatDuration(row.duration_ms)}
                      </td>
                      <td className="py-1.5 text-right text-gray-400 dark:text-gray-500">
                        {formatTimestamp(row.finished_at ?? row.created_at)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </div>
  );
};
 
export default Reports;