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

97.91% Statements 47/48
81.57% Branches 31/38
96% Functions 24/25
97.67% Lines 42/43

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                                                    5x   4x 8x 8x     5x         12x                                   5x       1x   2x                                             5x         7x 7x 7x   7x   7x     2x     7x 7x 7x 5x     7x 4x       7x 2x 2x 1x 2x     7x   1x       1x     1x             7x 7x 20x 9x   7x                                       1x 1x                                                         8x       1x                   4x       1x                                      
/**
 * Evaluate an agent, as it is configured, on chosen datasets — one step from
 * Assurance or the agent's page to evidence about it.
 *
 * Evaluating an agent used to mean opening a dataset, creating an experiment,
 * adding the agent as a variant and running it — a path nothing pointed to.
 * Here the datasets are picked (the gold datasets, ticked by default) and
 * svc-core does the rest (`POST /evaluations/agents/{id}/evaluate`): one
 * experiment per dataset, found again next time so its runs accumulate and
 * each is compared with the last, owned where the agent's evidence is read so
 * the result counts on Assurance.
 */
 
import { Modal, ModalActions } from "@/components/detail";
import { isSystemManaged } from "@/objects/Doc";
import { EvaluateAgentStarted, TestSuite } from "@/objects/Evaluation";
import { INCLUDE_SYSTEM, QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { BadgeCheck } from "lucide-react";
import React, { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { ErrorNote, experimentHref } from "./components";
 
/** The datasets offered: gold ones first (ticked), then the user's own. */
export const datasetGroups = (
  suites: TestSuite[],
): { gold: TestSuite[]; own: TestSuite[] } => ({
  gold: suites.filter((s) => isSystemManaged(s)),
  own: suites.filter((s) => !isSystemManaged(s) && (s.case_count ?? 0) > 0),
});
 
const DatasetOption: React.FC<{
  suite: TestSuite;
  checked: boolean;
  onToggle: () => void;
}> = ({ suite, checked, onToggle }) => (
  <label className="flex items-center gap-2.5 px-3 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer">
    <input
      type="checkbox"
      checked={checked}
      onChange={onToggle}
      className="rounded border-gray-300 dark:border-gray-600"
    />
    <span className="text-sm text-gray-800 dark:text-gray-200 flex-1 min-w-0 truncate">
      {suite.name}
    </span>
    {suite.case_count != null && (
      <span className="text-xs text-gray-400 shrink-0">
        {suite.case_count} question{suite.case_count === 1 ? "" : "s"}
      </span>
    )}
  </label>
);
 
const Results: React.FC<{
  results: EvaluateAgentStarted[];
  names: Map<string, string>;
}> = ({ results, names }) => (
  <ul className="divide-y divide-gray-100 dark:divide-gray-700 rounded-lg border border-gray-200 dark:border-gray-700">
    {results.map((row) => (
      <li
        key={row.experiment_id}
        className="flex items-center justify-between gap-3 px-3 py-2 text-sm"
      >
        <span className="text-gray-800 dark:text-gray-200 truncate">
          {names.get(row.dataset_id) ?? "Dataset"}
        </span>
        <span className="flex items-center gap-3 shrink-0 text-xs">
          <span className="text-gray-500 dark:text-gray-400">
            {row.status === "running" ? "Already running" : "Started"}
          </span>
          <Link
            to={experimentHref(row.experiment_id)}
            className="font-medium text-indigo-600 dark:text-indigo-400 hover:underline"
          >
            Open
          </Link>
        </span>
      </li>
    ))}
  </ul>
);
 
const EvaluateAgentModal: React.FC<{
  agentId: string;
  agentName: string;
  onClose: () => void;
}> = ({ agentId, agentName, onClose }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [error, setError] = useState<string | null>(null);
  // Null until the user changes it: the gold datasets, once they load.
  const [picked, setPicked] = useState<Set<string> | null>(null);
 
  const { data, isLoading } = useQuery<TestSuite[]>({
    queryKey: [QUERY_KEYS.GET.TEST_SUITES, INCLUDE_SYSTEM],
    queryFn: () =>
      getApiHandler().evaluation_router.listTestSuites({ includeSystem: true }),
  });
  // Bound to a typed const: TypeScript 5.0 cannot infer useQuery's data.
  const suites: TestSuite[] = useMemo(() => data ?? [], [data]);
  const { gold, own } = useMemo(() => datasetGroups(suites), [suites]);
  const selected = useMemo(
    () => picked ?? new Set(gold.map((s) => s.id)),
    [picked, gold],
  );
  const names = useMemo(
    () => new Map<string, string>(suites.map((s) => [s.id, s.name])),
    [suites],
  );
 
  const toggle = (id: string) => {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setPicked(next);
  };
 
  const evaluate = useMutation({
    mutationFn: () =>
      getApiHandler().evaluation_router.evaluateAgent(agentId, {
        dataset_ids: [...selected],
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.EVALUATION_ASSURANCE],
      });
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.EXPERIMENTS],
      });
    },
    onError: (e) => setError(errorDetail(e, "Could not start the evaluation.")),
  });
 
  const done = evaluate.isSuccess;
  const questions = suites
    .filter((s: TestSuite) => selected.has(s.id))
    .reduce((sum: number, s: TestSuite) => sum + (s.case_count ?? 0), 0);
 
  return (
    <Modal
      title={`Evaluate ${agentName}`}
      icon={BadgeCheck}
      size="lg"
      busy={evaluate.isPending}
      onClose={onClose}
      description={`Runs ${agentName}, exactly as it is configured, on every question in each dataset you pick, and grades the answers with the LLM judge. Each dataset gets one experiment, reused next time, so you can see what moved after a change. The results count on Assurance.`}
      footer={
        done ? (
          <ModalActions
            onCancel={onClose}
            cancelLabel="Close"
            onConfirm={onClose}
            confirmLabel="Done"
          />
        ) : (
          <ModalActions
            onCancel={onClose}
            onConfirm={() => {
              setError(null);
              evaluate.mutate();
            }}
            confirmLabel={`Evaluate on ${selected.size} dataset${selected.size === 1 ? "" : "s"}`}
            loadingLabel="Starting…"
            loading={evaluate.isPending}
            disabled={selected.size === 0 || evaluate.isPending}
          />
        )
      }
    >
      {done ? (
        <div className="space-y-3">
          <p className="text-sm text-gray-600 dark:text-gray-300">
            Running in the background. Each run takes a few minutes; open one to
            watch it.
          </p>
          <Results results={evaluate.data ?? []} names={names} />
        </div>
      ) : (
        <div className="space-y-4">
          {isLoading ? (
            <p className="text-sm text-gray-500">Loading datasets…</p>
          ) : (
            <>
              <fieldset>
                <legend className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400 mb-1">
                  Gold datasets
                </legend>
                {gold.map((suite) => (
                  <DatasetOption
                    key={suite.id}
                    suite={suite}
                    checked={selected.has(suite.id)}
                    onToggle={() => toggle(suite.id)}
                  />
                ))}
              </fieldset>
              {own.length > 0 && (
                <fieldset>
                  <legend className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400 mb-1">
                    Your datasets
                  </legend>
                  {own.map((suite) => (
                    <DatasetOption
                      key={suite.id}
                      suite={suite}
                      checked={selected.has(suite.id)}
                      onToggle={() => toggle(suite.id)}
                    />
                  ))}
                </fieldset>
              )}
              <p className="text-xs text-gray-500 dark:text-gray-400">
                {questions} question{questions === 1 ? "" : "s"} in all; each
                answer costs one agent turn and one judge call, charged to you.
              </p>
            </>
          )}
          {error && <ErrorNote message={error} />}
        </div>
      )}
    </Modal>
  );
};
 
export default EvaluateAgentModal;