All files / src/components/decisions AddToDatasetModal.tsx

96.29% Statements 26/27
66.66% Branches 8/12
90.9% Functions 10/11
95.83% Lines 23/24

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                            3x               3x               3x         4x 4x 4x 4x   4x   2x       4x 6x   4x   1x         1x 1x 1x                             1x 1x 1x       4x                   1x                                             1x     3x                                                        
import { Modal, ModalActions, encodeResourceId } from "@/components/detail";
import { DecisionVerdict } from "@/objects/Decision";
import { TestSuite } from "@/objects/Evaluation";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { 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 { Database } from "lucide-react";
import React, { useState } from "react";
import toast from "react-hot-toast";
import { Link } from "react-router-dom";
 
/** What the case keeps of the answer, by verdict. */
const WHAT_IT_BECOMES: Record<DecisionVerdict, string> = {
  accepted: "The answer becomes the case's reference answer.",
  edited: "Your correction becomes the case's reference answer.",
  rejected:
    "The answer becomes an example graded 0, so the judge learns what not to accept.",
};
 
const FIELD =
  "mt-1 w-full rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-1 focus:ring-gray-400";
 
/**
 * Add a turn to an evaluation dataset as a case — the flywheel: the
 * question, the conversation before it, and what its verdict says a right
 * answer is. Personal data is redacted on the server unless turned off.
 * Only datasets the person can change are offered (never a gold one).
 */
export const AddToDatasetModal: React.FC<{
  invocationId: string;
  verdict: DecisionVerdict;
  onClose: () => void;
}> = ({ invocationId, verdict, onClose }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [suiteId, setSuiteId] = useState("");
  const [redact, setRedact] = useState(true);
 
  const { data } = useQuery<TestSuite[]>({
    queryKey: [QUERY_KEYS.GET.TEST_SUITES],
    queryFn: () => getApiHandler().evaluation_router.listTestSuites(),
  });
  // Bound to an explicit type: the pinned TypeScript cannot infer react-query
  // v5's return type (docs/guides/frontend-components.md).
  const all: TestSuite[] = data ?? [];
  const datasets = all.filter((d) => !d.is_system);
 
  const add = useMutation({
    mutationFn: () =>
      getApiHandler().decision_router.addToDataset(invocationId, {
        test_suite_id: suiteId,
        redact_pii: redact,
      }),
    onSuccess: (created) => {
      const removed = Object.values(created.redacted).reduce((a, b) => a + b, 0);
      const dataset = datasets.find((d) => d.id === suiteId);
      toast.success(
        <span>
          Added to{" "}
          <Link
            to={APP_ROUTES.USER.GOVERNANCE.EVALUATION.DATASETS.id.replace(
              ROUTE_PARAMS.DATASET.id,
              encodeResourceId(suiteId),
            )}
            className="underline"
          >
            {dataset?.name ?? "the dataset"}
          </Link>
          {removed > 0 ? `, ${removed} personal value${removed === 1 ? "" : "s"} redacted` : ""}.
        </span>,
      );
      void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.DECISION] });
      void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.TEST_SUITES] });
      onClose();
    },
  });
 
  return (
    <Modal
      title="Add to a dataset"
      icon={Database}
      busy={add.isPending}
      onClose={onClose}
      description={`The question, and the conversation before it, become a case. ${WHAT_IT_BECOMES[verdict]}`}
      footer={
        <ModalActions
          onCancel={onClose}
          onConfirm={() => add.mutate()}
          confirmLabel="Add case"
          loadingLabel="Adding…"
          loading={add.isPending}
          disabled={!suiteId}
        >
          {add.isError && (
            <span className="text-xs text-red-600 dark:text-red-400">
              {errorDetail(add.error, "Could not add the case.")}
            </span>
          )}
        </ModalActions>
      }
    >
      <div className="space-y-4">
        {datasets.length === 0 ? (
          <p className="text-sm text-gray-500 dark:text-gray-400">
            There is no dataset here you can add to yet. Create one under
            Governance → Evaluation → Datasets.
          </p>
        ) : (
          <label className="block">
            <span className="text-xs text-gray-500 dark:text-gray-400">Dataset</span>
            <select value={suiteId} onChange={(e) => setSuiteId(e.target.value)} className={FIELD}>
              <option value="">Choose a dataset…</option>
              {datasets.map((d) => (
                <option key={d.id} value={d.id}>
                  {d.name}
                </option>
              ))}
            </select>
          </label>
        )}
        <label className="flex items-start gap-2 text-sm text-gray-700 dark:text-gray-200">
          <input
            type="checkbox"
            checked={redact}
            onChange={(e) => setRedact(e.target.checked)}
            className="mt-0.5"
          />
          <span>
            Redact personal data
            <span className="block text-xs text-gray-500 dark:text-gray-400">
              Names after a title, contact details, identifiers and card
              numbers are replaced with placeholders before the case is saved.
            </span>
          </span>
        </label>
      </div>
    </Modal>
  );
};
 
export default AddToDatasetModal;