Skip to content

The platform for continuously improving AI agents.

7.4 KB
Raw Blame
import { useState } from "react";

import { ArtifactPanel } from "@/components/ai-components/artifact-panel";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Icon } from "@/components/ui/icons";
import { StatusBadge } from "@/lib/job-status";
import { ComparisonReport, comparisonEvidence } from "./comparison-report";
import type { ExperimentBlock, ExperimentScope, NodeReceipt } from "./document";
import { EvaluationResult } from "./evaluation-result";
import { trainingWork } from "./node-overview-data";
import { TrainingEvidence } from "./training-evidence";

export function VariantReport({
  block,
  scopes,
  onInspect,
}: {
  block: ExperimentBlock;
  scopes: ExperimentScope[];
  onInspect: () => void;
}) {
  const labels = block.config.labels as Record<string, string> | undefined;
  return (
    <Card className="space-y-2 rounded-md p-3">
      <div className="flex h-6 items-center gap-2">
        <Icon.gitBranch className="size-3.5 text-cat-6" />
        <h3 className="min-w-0 flex-1 text-xs font-medium">Candidate results</h3>
        <Button aria-label="Inspect candidates" onClick={onInspect} size="icon-xs" variant="ghost">
          <Icon.expand />
        </Button>
      </div>
      <p className="text-xs text-muted-foreground">
        {scopes.filter((scope) => scope.state === "completed").length} of {scopes.length} completed
      </p>
      {scopes.slice(0, 4).map((scope) => (
        <button
          className="flex min-h-8 w-full items-center justify-between gap-2 rounded-sm px-1 text-left text-xs hover:bg-muted"
          key={scope.id}
          onClick={onInspect}
          type="button"
        >
          <span className="truncate">
            {labels?.[scope.variant] ?? `Candidate ${scope.index + 1}`}
          </span>
          <StatusBadge fallback="queued" status={scope.state} />
        </button>
      ))}
      {scopes.length > 4 && (
        <Button onClick={onInspect} size="xs" variant="secondary">
          Inspect all {scopes.length} candidates
        </Button>
      )}
    </Card>
  );
}

export function NodeResults({
  block,
  receipts,
  scopes,
  projectId,
  onClose,
}: {
  block: ExperimentBlock;
  receipts: NodeReceipt[];
  scopes: ExperimentScope[];
  projectId: string;
  onClose: () => void;
}) {
  const [chosen, setChosen] = useState<string>();
  const [view, setView] = useState("output");
  const scope = scopes.find((item) => item.id === chosen) ?? scopes.at(-1);
  const attempts = block.kind === "map" ? (scope?.nodes ?? []) : receipts;
  const current = attempts.filter((receipt) => receipt.current !== false);
  const evaluations = [
    ...new Set(
      current.flatMap((receipt) =>
        Object.values(receipt.outputs).flatMap((output) =>
          typeof output.evaluation === "string" ? [output.evaluation] : []
        )
      )
    ),
  ];
  const [evaluation, setEvaluation] = useState<string>();
  const evaluationId = evaluations.includes(evaluation ?? "") ? evaluation : evaluations[0];
  const comparisons = current.flatMap((receipt) => {
    const evidence = comparisonEvidence(receipt);
    return evidence ? [{ evidence, id: receipt.action }] : [];
  });
  const training = attempts.filter((receipt) => trainingWork({ ...receipt, current: true }));
  const labels = block.config.labels as Record<string, string> | undefined;
  return (
    <ArtifactPanel
      icon={<Icon.chart />}
      onClose={onClose}
      onViewChange={setView}
      title={`${block.title} · Results`}
      view={view}
      views={[
        { id: "output", label: "Results" },
        { id: "checks", label: "Checks" },
        { id: "history", label: "Evidence" },
      ]}
    >
      <div className="space-y-3 p-3">
        {scopes.length > 0 && (
          <label className="flex items-center gap-2 text-xs">
            Candidate
            <select
              aria-label="Candidate result"
              className="h-8 min-w-0 flex-1 rounded-sm border border-border bg-card px-2"
              onChange={(event) => setChosen(event.target.value)}
              value={scope?.id}
            >
              {scopes.map((item) => (
                <option key={item.id} value={item.id}>
                  {labels?.[item.variant] ?? `Candidate ${item.index + 1}`} · {item.state}
                </option>
              ))}
            </select>
          </label>
        )}
        {scope?.error && <Alert variant="warning">{scope.error}</Alert>}
        {view === "output" && (
          <>
            {comparisons.map(({ evidence, id }) => (
              <ComparisonReport evidence={evidence} expanded key={id} />
            ))}
            {evaluations.length > 1 && (
              <select
                aria-label="Evaluation evidence"
                className="h-8 w-full rounded-sm border border-border bg-card px-2 text-xs"
                onChange={(event) => setEvaluation(event.target.value)}
                value={evaluationId}
              >
                {evaluations.map((id) => (
                  <option key={id} value={id}>
                    Evaluation {id.slice(0, 8)}
                  </option>
                ))}
              </select>
            )}
            {evaluationId && <EvaluationResult id={evaluationId} projectId={projectId} />}
            {!evaluations.length && !training.length && !comparisons.length && (
              <p className="text-xs text-muted-foreground">
                No measured results have been retained for this attempt.
              </p>
            )}
          </>
        )}
        {training.length > 0 && (
          <TrainingEvidence attempts={training} view={view as "output" | "checks" | "history"} />
        )}
        {view === "checks" && !training.length && (
          <p className="text-xs text-muted-foreground">
            Evaluation checks and coverage are included in the recorded results.
          </p>
        )}
        {view === "history" && (
          <>
            {scope && (
              <details open>
                <summary className="cursor-pointer text-xs">Candidate parameters</summary>
                <pre className="mt-2 overflow-auto text-xs">
                  {JSON.stringify(scope.parameters, null, 2)}
                </pre>
              </details>
            )}
            {attempts.map((receipt) => (
              <details className="text-xs" key={receipt.action}>
                <summary className="cursor-pointer py-2">
                  {scope?.document?.nodes.find((node) => node.id === receipt.node)?.title ??
                    block.title}{" "}
                  · {receipt.state}
                  {receipt.reused_from ? " · Reused" : ""}
                </summary>
                <pre className="overflow-auto whitespace-pre-wrap break-all">
                  {JSON.stringify(
                    {
                      arguments: receipt.arguments,
                      completed: receipt.completed_at,
                      identity: receipt.identity,
                      outputs: receipt.outputs,
                      result: receipt.result,
                      reused_from: receipt.reused_from,
                      revision: receipt.revision,
                      started: receipt.started_at,
                    },
                    null,
                    2
                  )}
                </pre>
              </details>
            ))}
          </>
        )}
      </div>
    </ArtifactPanel>
  );
}