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

95.45% Statements 42/44
90% Branches 63/70
90% Functions 18/20
95% Lines 38/40

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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372                                                                                                                              3x 4x                                                                   3x                 3x                       3x 5x                                       3x           3x 17x         3x       17x 17x                                                           4x           5x                                                                                     1x                     3x 19x 19x       19x   19x   9x   19x 19x 18x     19x 19x   19x 15x               19x 19x   19x 17x   19x               19x           4x                   3x                   10x             19x                                                                                                
import {
  FilterOption,
  ResourceCollection,
  SegmentedFilter,
  collectionSection,
  useCollectionFilters,
} from "@/components/collection";
import {
  ASSURANCE_STATUS,
  StatusBadge,
  encodeResourceId,
} from "@/components/detail";
import {
  AgentAssurance,
  AssuranceRun,
  AssuranceStatus,
  FleetAssurance,
  PendingDataset,
} from "@/objects/Evaluation";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import {
  BadgeCheck,
  Bot,
  CheckCircle2,
  Clock,
  FlaskConical,
  Loader2,
  XCircle,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import {
  ScoreBadge,
  experimentHref,
  formatCost,
  formatSpread,
  formatTimestamp,
} from "./components";
import { STATUS_HINT, STATUS_LABEL, needsAttention } from "./assuranceStatus";
import EvaluateAgentModal from "./EvaluateAgentModal";
import { QualitySummary } from "./RiskReturn";
 
/**
 * Governance → Evaluation → Assurance: for every agent, whether the version
 * in force has evaluation evidence behind it.
 *
 * A score is only evidence about something if you can say which version was
 * scored. Every run records the revision of each agent it evaluated, so this
 * can tell "the agent in production was evaluated" apart from "an older
 * version was", "it never was" and "its latest run regressed" — the question
 * an assurance review asks first.
 *
 * Each agent also carries its average and its risk over those runs (see
 * `RiskReturn.tsx`): two agents that both pass can differ in how often an
 * answer falls short. CHAINR Bot lists every gold dataset, the ones the
 * platform benchmark has still to run included.
 */
 
/** One dataset's verdict on the version in force: its score against the
 *  dataset's pass mark. */
const DatasetVerdict: React.FC<{ run: AssuranceRun }> = ({ run }) => (
  <Link
    to={experimentHref(run.experiment_id)}
    title={`${run.experiment_name} — pass mark ${run.pass_mark.toFixed(2)}${
      run.answer_sd != null && run.answers
        ? ` · answers spread ${formatSpread(run.answer_sd)} over ${run.answers}`
        : ""
    }${
      run.refreshing
        ? " · a run for this release is under way; this result is from an earlier one"
        : ""
    }`}
    className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] hover:underline ${
      run.passed
        ? "border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-300"
        : "border-red-200 dark:border-red-800 text-red-700 dark:text-red-300"
    }`}
  >
    {run.refreshing ? (
      <Loader2 className="size-3 animate-spin" aria-label="Updating" />
    ) : run.passed ? (
      <CheckCircle2 className="size-3" aria-hidden="true" />
    ) : (
      <XCircle className="size-3" aria-hidden="true" />
    )}
    <span className="truncate max-w-40">{run.dataset_name ?? "Dataset"}</span>
    <span className="font-mono tabular-nums">
      {run.mean_score != null ? run.mean_score.toFixed(2) : "—"}
      <span className="text-gray-400 dark:text-gray-500">
        /{run.pass_mark.toFixed(2)}
      </span>
    </span>
  </Link>
);
 
const PENDING_LABEL: Record<PendingDataset["status"], string> = {
  running: "Running now",
  queued: "Queued",
  interrupted: "Interrupted, runs again",
  failed: "Last run failed",
  next_round: "Next month's run",
  off: "Not run here",
};
 
const PENDING_HINT: Record<PendingDataset["status"], string> = {
  running: "The platform benchmark is running it now.",
  queued: "The platform benchmark runs it next, one dataset at a time.",
  interrupted:
    "A deploy or restart cut its last run short. That says nothing about the agent, so it runs again shortly.",
  failed: "Its last benchmark run failed. It is tried once more, then again next month.",
  next_round:
    "Run this month already. The platform benchmark measures each target at most once a month, on the code then live, so the change since is measured in next month's round.",
  off: "The platform benchmark runs on CHAIN-R's deployed environments only.",
};
 
/** A gold dataset the platform benchmark has still to report on. */
const PendingVerdict: React.FC<{ pending: PendingDataset }> = ({ pending }) => (
  <span
    title={[PENDING_HINT[pending.status], pending.error].filter(Boolean).join(" ")}
    className={`inline-flex items-center gap-1 rounded-full border border-dashed px-2 py-0.5 text-[11px] ${
      pending.status === "failed"
        ? "border-red-200 dark:border-red-800 text-red-600 dark:text-red-300"
        : "border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400"
    }`}
  >
    {pending.status === "running" ? (
      <Loader2 className="size-3 animate-spin" aria-hidden="true" />
    ) : (
      <Clock className="size-3" aria-hidden="true" />
    )}
    <span className="truncate max-w-40">{pending.dataset_name}</span>
    <span>· {PENDING_LABEL[pending.status]}</span>
  </span>
);
 
type Filter = "all" | "attention" | AssuranceStatus;
 
const FILTER_OPTIONS: FilterOption<Filter>[] = [
  { value: "all", label: "All" },
  { value: "attention", label: "Needs attention" },
  { value: "current", label: "Passing" },
];
 
const agentHref = (id: string) =>
  APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
    ROUTE_PARAMS.AGENT.id,
    encodeResourceId(id),
  );
 
const AssuranceRow: React.FC<{
  row: AgentAssurance;
  onEvaluate: (row: AgentAssurance) => void;
}> = ({ row, onEvaluate }) => {
  const run = row.current_version_run ?? row.latest_run;
  return (
    <div className="flex flex-col sm:flex-row sm:items-center gap-3 px-4 py-3 border-b border-gray-100 dark:border-gray-700 last:border-0">
      <div className="flex items-center gap-3 min-w-0 flex-1">
        <Bot className="size-4 text-gray-400 shrink-0" />
        <div className="min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <Link
              to={agentHref(row.agent_id)}
              className="text-sm font-medium text-gray-900 dark:text-gray-100 hover:underline truncate"
            >
              {row.agent_name}
            </Link>
            {row.current_version != null && (
              <span className="text-[10px] font-mono text-gray-400">
                v{row.current_version} in force
              </span>
            )}
            <StatusBadge
              status={row.status}
              scale={ASSURANCE_STATUS}
              label={STATUS_LABEL[row.status]}
            />
          </div>
          <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
            {STATUS_HINT[row.status]}
          </p>
          {((row.datasets?.length ?? 0) > 0 ||
            (row.pending_datasets?.length ?? 0) > 0) && (
            <div className="mt-1.5 flex flex-wrap gap-1.5">
              {(row.datasets ?? []).map((run) => (
                <DatasetVerdict
                  key={`${run.batch_id}:${run.dataset_id ?? ""}`}
                  run={run}
                />
              ))}
              {(row.pending_datasets ?? []).map((pending) => (
                <PendingVerdict key={pending.dataset_id} pending={pending} />
              ))}
            </div>
          )}
        </div>
      </div>
      {run ? (
        <div className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400 shrink-0">
          {!row.quality && <ScoreBadge value={run.mean_score} />}
          <div className="min-w-0">
            {row.quality && (
              <QualitySummary quality={row.quality} className="mb-1" />
            )}
            {row.cost_per_answer_usd != null && (
              <div
                className="tabular-nums"
                title="What one answer cost in these runs, grading left out — each dataset weighted equally"
              >
                {formatCost(row.cost_per_answer_usd)} per answer
              </div>
            )}
            <div>
            <Link
              to={experimentHref(run.experiment_id)}
              className="font-medium text-gray-700 dark:text-gray-300 hover:underline"
            >
              {run.experiment_name}
            </Link>
            <div>
              {run.evaluated_version != null
                ? `evaluated v${run.evaluated_version}`
                : "version not recorded"}
              {run.created_at ? ` · ${formatTimestamp(run.created_at)}` : ""}
              {row.runs > 1 ? ` · ${row.runs} runs` : ""}
            </div>
            </div>
          </div>
        </div>
      ) : (
        <span className="text-xs text-gray-400 italic shrink-0">No runs</span>
      )}
      <button
        type="button"
        onClick={() => onEvaluate(row)}
        aria-label={`Evaluate ${row.agent_name}`}
        className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 shrink-0"
      >
        <FlaskConical className="size-3.5" />
        Evaluate
      </button>
    </div>
  );
};
 
export const AssuranceContent: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const collection = useCollectionFilters<{ status: Filter }>({
    defaults: { status: "all" },
    view: "list",
  });
  const { filters, setFilter, matches } = collection;
 
  const { data, isLoading } = useQuery<FleetAssurance | null>({
    queryKey: [QUERY_KEYS.GET.EVALUATION_ASSURANCE],
    queryFn: () => getApiHandler().evaluation_router.assurance(),
  });
  const agents: AgentAssurance[] = useMemo(() => data?.agents ?? [], [data]);
  const builtIn: AgentAssurance[] = useMemo(
    () => data?.built_in ?? [],
    [data],
  );
  const summary = data?.summary;
  const [evaluating, setEvaluating] = useState<AgentAssurance | null>(null);
 
  const keep = useMemo(
    () => (row: AgentAssurance) =>
      (filters.status === "all" ||
        (filters.status === "attention"
          ? needsAttention(row.status)
          : row.status === filters.status)) &&
      matches(row.agent_name, row.latest_run?.experiment_name),
    [filters.status, matches],
  );
  const visible = useMemo(() => agents.filter(keep), [agents, keep]);
  const visibleBuiltIn = useMemo(() => builtIn.filter(keep), [builtIn, keep]);
 
  const renderRow = (row: AgentAssurance) => (
    <AssuranceRow row={row} onEvaluate={setEvaluating} />
  );
  const empty = {
    Icon: BadgeCheck,
    title: "No agents to assure yet.",
    hint: "Create an agent, then press Evaluate on it — its evidence shows here.",
  };
  // CHAINR Bot apart, judged on the platform benchmark: the counts above
  // stay the workspace's own agents.
  const body =
    builtIn.length > 0
      ? {
          sections: [
            collectionSection<AgentAssurance>({
              label: "Built-in",
              items: visibleBuiltIn,
              itemKey: (row) => row.agent_id,
              renderRow,
              loading: isLoading,
              skeletonCount: 1,
              hideWhenEmpty: true,
              empty: { Icon: BadgeCheck, title: "Nothing built in matches." },
            }),
            collectionSection<AgentAssurance>({
              label: "Your agents",
              items: visible,
              itemKey: (row) => row.agent_id,
              renderRow,
              loading: isLoading,
              empty,
              emptyFilteredTitle: "No agents match.",
            }),
          ],
        }
      : {
          items: visible,
          itemKey: (row: AgentAssurance) => row.agent_id,
          loading: isLoading,
          renderRow,
          empty,
          emptyFilteredTitle: "No agents match.",
        };
 
  return (
    <>
    <ResourceCollection<AgentAssurance>
      description="Which version of each agent has evidence behind it. Every evaluation run records the revision of each agent it ran, so an agent changed since its last run — or never run at all — shows here, and each dataset it ran is scored against that dataset's pass mark. Beside each agent: its average score, ± how far a typical answer lands from it, and the risk that implies — two agents with one average are not equally safe when one of them sometimes fails outright. Press Evaluate to run an agent on the gold datasets. A regressed run is also sent to Reviews for a decision. A policy rule with “Require evaluation evidence” refuses exactly the agents not marked Passing. CHAINR Bot is benchmarked by CHAIN-R on every gold dataset at most once a month, on the release then live; the datasets still to run are shown as such."
      stats={[
        { label: "Agents", value: summary?.total ?? 0, loading: isLoading },
        { label: "Passing", value: summary?.current ?? 0, loading: isLoading },
        {
          label: "Below pass mark",
          value: summary?.failing ?? 0,
          loading: isLoading,
        },
        {
          label: "Changed since",
          value: summary?.outdated ?? 0,
          loading: isLoading,
        },
        { label: "Never", value: summary?.never ?? 0, loading: isLoading },
        { label: "Regressed", value: summary?.regressed ?? 0, loading: isLoading },
      ]}
      shown={visible.length}
      search={{
        value: collection.search,
        onChange: collection.setSearch,
        placeholder: "Search agents or evaluations…",
      }}
      filters={
        <SegmentedFilter
          value={filters.status}
          onChange={(value) => setFilter("status", value)}
          options={FILTER_OPTIONS}
        />
      }
      {...collection.toolbarProps}
      {...body}
    />
    {evaluating && (
      <EvaluateAgentModal
        agentId={evaluating.agent_id}
        agentName={evaluating.agent_name}
        onClose={() => setEvaluating(null)}
      />
    )}
    </>
  );
};
 
export default AssuranceContent;