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

78.49% Statements 73/93
70.78% Branches 63/89
73.17% Functions 30/41
78.02% Lines 71/91

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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507                                                                                                            2x           2x       5x   9x 9x 4x       4x   5x       2x 6x   11x 4x       2x             16x       16x   16x                                                                             2x                                         36x 36x 36x                                             4x   4x                                           16x                   15x           1x                               1x   2x                                                                 2x                                   32x 32x 32x 32x 32x   32x   6x     32x   32x   6x       32x 32x   47x   32x 5x           32x 4x   3x 3x   1x   32x 1x   1x 1x           32x 5x 5x 5x     32x 6x 6x 6x 6x     32x 32x   32x                                 5x                                 24x           18x     6x                                                       36x                             5x                                           17x                                                                                
/**
 * Add a whole comparison to an experiment in one step.
 *
 * "Which model is best on this dataset?", "which temperature?", "does the
 * repository help?" — pick a preset, fill in what it varies, and it writes one
 * ordinary variant per value. The form is drawn from the backend's preset
 * catalogue: it holds no list of presets, only one control per parameter
 * *type*, so a new preset needs no change here.
 *
 * Nothing is written until the preview has been read: the preview says which
 * variants would be made and what a run of the experiment would then cost,
 * because a sweep is the easiest way to spend a lot without meaning to.
 */
 
import { isSystemManaged } from "@/objects/Doc";
import { modelMaker } from "@/objects/modelOrigin";
import { Modal, ModalActions } from "@/components/detail";
import { Agent } from "@/objects/Agent";
import {
  EvaluationTarget,
  MODEL_EFFORT_LEVELS,
  PresetCatalogue,
  PresetInfo,
  PresetParam,
  PresetResult,
} from "@/objects/Evaluation";
import { KnowledgeRepository } from "@/objects/Knowledge";
import {
  Model,
  isSelectableModel,
  modelDisplayName,
  selectableModels,
} from "@/objects/Model";
import { AvailableTool } from "@/objects/Tool";
import { formatUsd } from "@/components/cost/format";
import type { Swarm } from "@/objects/Swarm";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQuery } from "@tanstack/react-query";
import { ChevronLeft, Layers } from "lucide-react";
import React, { useState } from "react";
import {
  CheckList,
  ErrorNote,
  Field,
  Select,
  Skeleton,
  TargetPicker,
  effectiveModel,
  inputCls,
} from "./components";
 
/** What each parameter type starts as, so a preset opens ready to preview. */
const DEFAULTS: Partial<Record<PresetParam["type"], unknown>> = {
  temperatures: "0, 0.5, 1",
  effort_levels: ["low", "medium", "high"],
};
 
/** Temperatures are typed as "0, 0.5, 1"; everything else is sent as held. */
const toRequest = (
  preset: PresetInfo,
  values: Record<string, unknown>,
): Record<string, unknown> =>
  Object.fromEntries(
    preset.params.map((param) => {
      const value = values[param.key];
      if (param.type === "temperatures") {
        const numbers = String(value ?? "")
          .split(/[\s,]+/)
          .filter(Boolean)
          .map(Number);
        return [param.key, numbers];
      }
      return [param.key, value];
    }),
  );
 
const initialValues = (preset: PresetInfo): Record<string, unknown> =>
  Object.fromEntries(
    preset.params
      .filter((param) => DEFAULTS[param.type] !== undefined)
      .map((param) => [param.key, DEFAULTS[param.type]]),
  );
 
/** "Runs on" for a sweep: a model, or an agent on its own model or another. */
const BaseControl: React.FC<{
  value: EvaluationTarget | null;
  onChange: (value: EvaluationTarget | null) => void;
  models: Model[];
  agents: Agent[];
  dimension: string;
}> = ({ value, onChange, models, agents, dimension }) => {
  const model = effectiveModel(value, models, agents);
  // Said here, before a preview is asked for: a sweep over a control the
  // model drops would make identical variants.
  const drops =
    (dimension === "temperature" && model?.supports_temperature === false) ||
    (dimension === "effort" && model?.supports_effort === false);
  return (
    <div className="space-y-2">
      <TargetPicker
        value={value}
        onChange={onChange}
        models={models}
        agents={agents}
      />
      {value?.agent_id && (
        <Select
          aria-label="Agent's model"
          value={value.model_id ?? ""}
          onChange={(e) =>
            onChange({ ...value, model_id: e.target.value || null })
          }
        >
          <option value="">Agent&apos;s own model</option>
          {selectableModels(models, value.model_id).map((m) => (
            <option key={m.id} value={m.id}>
              {modelMaker(m)} ·{" "}
              {modelDisplayName(m)}
              {m.is_available ? "" : " (not available here)"}
            </option>
          ))}
        </Select>
      )}
      {drops && model && (
        <p className="text-xs text-amber-600 dark:text-amber-400">
          {modelDisplayName(model)} does not take{" "}
          {dimension === "temperature" ? "a temperature" : "an effort level"} —
          every variant would be the same. Choose another model
          {value?.agent_id ? ", or run the agent on one" : ""}.
        </p>
      )}
    </div>
  );
};
 
/** One parameter's control, chosen by its type. */
const ParamControl: React.FC<{
  param: PresetParam;
  value: unknown;
  onChange: (value: unknown) => void;
  dimension: string;
  models: Model[];
  agents: Agent[];
  repositories: KnowledgeRepository[];
  tools: AvailableTool[];
  swarms: { id: string; name: string }[];
}> = ({
  param,
  value,
  onChange,
  dimension,
  models,
  agents,
  repositories,
  tools,
  swarms,
}) => {
  const list = (value as string[] | undefined) ?? [];
  const chatModels = models.filter(isSelectableModel);
  switch (param.type) {
    case "models":
      return (
        <CheckList
          options={chatModels.map((m) => ({
            value: m.id,
            label: `${modelMaker(m)} · ${modelDisplayName(m)}`,
          }))}
          selected={list}
          onChange={onChange}
          emptyHint="No models are available."
        />
      );
    case "agents":
      return (
        <CheckList
          options={agents.map((a) => ({ value: a.id, label: a.name }))}
          selected={list}
          onChange={onChange}
          emptyHint="You have no agents yet."
        />
      );
    case "swarms":
      return (
        <CheckList
          options={swarms.map((s) => ({ value: s.id, label: s.name }))}
          selected={list}
          onChange={onChange}
          emptyHint="This workspace has no swarms yet."
        />
      );
    case "agent":
      return (
        <Select
          aria-label={param.label}
          value={(value as string) ?? ""}
          onChange={(e) => onChange(e.target.value || undefined)}
        >
          <option value="">Select an agent…</option>
          {agents.map((a) => (
            <option key={a.id} value={a.id}>
              {a.name}
            </option>
          ))}
        </Select>
      );
    case "base":
      return (
        <BaseControl
          value={(value as EvaluationTarget) ?? null}
          onChange={onChange}
          models={chatModels}
          agents={agents}
          dimension={dimension}
        />
      );
    case "temperatures":
      return (
        <input
          aria-label={param.label}
          className={`${inputCls} font-mono`}
          placeholder="0, 0.5, 1"
          value={(value as string) ?? ""}
          onChange={(e) => onChange(e.target.value)}
        />
      );
    case "effort_levels":
      return (
        <CheckList
          options={MODEL_EFFORT_LEVELS.map((level) => ({
            value: level,
            label: level,
          }))}
          selected={list}
          onChange={onChange}
          emptyHint=""
        />
      );
    case "repositories":
      return (
        <CheckList
          options={repositories.map((r) => ({
            value: r.id,
            label: isSystemManaged(r) ? `${r.name} · built-in` : r.name,
          }))}
          selected={list}
          onChange={onChange}
          emptyHint="You have no knowledge repositories yet."
        />
      );
    case "tools":
      return (
        <CheckList
          options={tools.map((t) => ({ value: t.name, label: t.name }))}
          selected={list}
          onChange={onChange}
          emptyHint="Could not load the built-in tools."
        />
      );
    case "prompt":
      return (
        <textarea
          aria-label={param.label}
          rows={4}
          className={`${inputCls} resize-y font-mono`}
          value={(value as string) ?? ""}
          onChange={(e) => onChange(e.target.value)}
        />
      );
    default:
      return null;
  }
};
 
const PresetModal: React.FC<{
  experimentId: string;
  models: Model[];
  agents: Agent[];
  repositories: KnowledgeRepository[];
  tools: AvailableTool[];
  onClose: () => void;
  /** Called once variants have been written. */
  onApplied: () => void;
}> = ({
  experimentId,
  models,
  agents,
  repositories,
  tools,
  onClose,
  onApplied,
}) => {
  const { getApiHandler } = useApiHandler();
  const [presetKey, setPresetKey] = useState<string | null>(null);
  const [values, setValues] = useState<Record<string, unknown>>({});
  const [preview, setPreview] = useState<PresetResult | null>(null);
  const [error, setError] = useState<string | null>(null);
 
  const { data: swarmData } = useQuery<Swarm[]>({
    queryKey: [QUERY_KEYS.GET.SWARMS],
    queryFn: () => getApiHandler().swarm_router.list(),
    staleTime: 60_000,
  });
  const swarms: Swarm[] = swarmData ?? [];
 
  const { data, isLoading } = useQuery<PresetCatalogue>({
    queryKey: [QUERY_KEYS.GET.VARIANT_PRESETS],
    queryFn: () => getApiHandler().evaluation_router.listPresets(),
    staleTime: Infinity,
  });
  // Typed explicitly: this TypeScript cannot infer useQuery's data.
  const catalogue: PresetCatalogue | undefined = data;
  const presets: PresetInfo[] = catalogue?.presets ?? [];
  const preset: PresetInfo | null =
    presets.find((p: PresetInfo) => p.key === presetKey) ?? null;
 
  const request = (dryRun: boolean) =>
    getApiHandler().evaluation_router.applyPreset(
      experimentId,
      preset!.key,
      toRequest(preset!, values),
      dryRun,
    );
  const previewMutation = useMutation({
    mutationFn: () => request(true),
    onSuccess: (result) => {
      setError(null);
      setPreview(result);
    },
    onError: (e) => setError(errorDetail(e, "This preset could not be applied.")),
  });
  const applyMutation = useMutation({
    mutationFn: () => request(false),
    onSuccess: () => {
      onApplied();
      onClose();
    },
    onError: (e) => setError(errorDetail(e, "The variants could not be added.")),
  });
 
  // Any change invalidates the preview: what is written must be what was read.
  const setValue = (key: string, value: unknown) => {
    setValues((v) => ({ ...v, [key]: value }));
    setPreview(null);
    setError(null);
  };
 
  const choose = (next: PresetInfo) => {
    setPresetKey(next.key);
    setValues(initialValues(next));
    setPreview(null);
    setError(null);
  };
 
  const busy = previewMutation.isPending || applyMutation.isPending;
  const calls = preview?.calls;
 
  return (
    <Modal
      title={preset ? preset.label : "Add variants from a preset"}
      icon={Layers}
      size="lg"
      busy={busy}
      onClose={onClose}
      description={
        preset
          ? preset.summary
          : "One question, several answers to try: each preset writes one ordinary variant per value — editable and deletable like any other."
      }
      footer={
        preset && (
          <ModalActions
            onCancel={onClose}
            onConfirm={() =>
              preview ? applyMutation.mutate() : previewMutation.mutate()
            }
            confirmLabel={
              preview
                ? `Add ${preview.variants.length} variant${preview.variants.length === 1 ? "" : "s"}`
                : "Preview"
            }
            loadingLabel={preview ? "Adding…" : "Checking…"}
            loading={busy}
          />
        )
      }
    >
      {!preset ? (
        isLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-14 w-full" />
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {presets.map((p: PresetInfo) => (
              <button
                key={p.key}
                type="button"
                onClick={() => choose(p)}
                className="text-left rounded-lg border border-gray-200 dark:border-gray-700 p-3 hover:border-gray-400 dark:hover:border-gray-500 transition-colors"
              >
                <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                  {p.label}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                  {p.summary}
                </div>
              </button>
            ))}
          </div>
        )
      ) : (
        <div className="space-y-4">
          <button
            type="button"
            onClick={() => {
              setPresetKey(null);
              setPreview(null);
              setError(null);
            }}
            className="inline-flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
          >
            <ChevronLeft className="size-3" />
            All presets
          </button>
          {preset.params.map((param: PresetParam) => (
            <Field
              key={param.key}
              label={param.label}
              hint={
                [
                  param.hint,
                  param.min_items ? `at least ${param.min_items}` : "",
                ]
                  .filter(Boolean)
                  .join(" — ") || undefined
              }
            >
              <ParamControl
                param={param}
                value={values[param.key]}
                onChange={(value) => setValue(param.key, value)}
                dimension={preset.dimension}
                models={models}
                agents={agents}
                repositories={repositories}
                tools={tools}
                swarms={swarms}
              />
            </Field>
          ))}
 
          {preview && calls && (
            <div
              role="status"
              className="rounded-lg border border-gray-200 dark:border-gray-700 p-3 space-y-2"
            >
              <div className="text-xs font-medium text-gray-800 dark:text-gray-200">
                Adds {calls.new_variants} variant
                {calls.new_variants === 1 ? "" : "s"}:
              </div>
              <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-0.5">
                {preview.variants.map((v) => (
                  <li key={v.name}>{v.name}</li>
                ))}
              </ul>
              <p className="text-xs text-gray-500 dark:text-gray-400">
                A run of the experiment will then make{" "}
                <span className="font-medium text-gray-800 dark:text-gray-200">
                  {calls.answers_per_run} answers
                </span>{" "}
                ({calls.variants_after} variants × {calls.cases} cases)
                {calls.judge_calls_per_run > 0 && (
                  <>
                    {" "}
                    and{" "}
                    <span className="font-medium text-gray-800 dark:text-gray-200">
                      {calls.judge_calls_per_run} judge calls
                    </span>
                  </>
                )}
                , each counted against your usage.
              </p>
              {calls.swarm_budget_per_run_usd ? (
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Each swarm answers every case as a whole run: together they may
                  spend up to{" "}
                  <span className="font-medium text-gray-800 dark:text-gray-200">
                    {formatUsd(calls.swarm_budget_per_run_usd)}
                  </span>{" "}
                  a run of the experiment.
                </p>
              ) : null}
            </div>
          )}
          {error && <ErrorNote message={error} />}
        </div>
      )}
    </Modal>
  );
};
 
export default PresetModal;