All files / src/components/diff/GenerationDetails GenerationDetails.tsx

92.5% Statements 37/40
86.56% Branches 58/67
100% Functions 11/11
97.14% Lines 34/35

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                                    104x   104x 12x 12x       104x 12x   104x 31x 19x 19x 19x                                                                               104x           31x   31x   16x       31x       31x 31x 31x 31x   31x 21x   31x   31x 22x     31x   31x                                                                             12x                                               7x     7x 7x   7x               7x                                                     9x                                          
import { makerLabel } from "@/objects/modelOrigin";
import {
  GENERATION_FLOW_LABELS,
  GenerationRef,
  GenerationRun,
  ProducedResource,
} from "@/objects/History";
import { RESOURCE_TYPE_LABELS } from "@/objects/Activity";
import resourceHref from "@/routes/resourceHref";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, Boxes, Cpu, Sparkles, User } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
import { parseServerDate } from "@/util/time";
 
/** Argument keys that restate what the surrounding UI already shows. */
const UNINTERESTING_ARGUMENT_KEYS = new Set(["ai_model_id"]);
 
const formatArgument = (value: unknown): string => {
  Iif (value == null) return "—";
  Eif (typeof value === "string") return value;
  return JSON.stringify(value, null, 2);
};
 
const humanise = (key: string): string =>
  key.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase());
 
const formatTimestamp = (iso?: string | null): string | null => {
  if (!iso) return null;
  const date = parseServerDate(iso);
  Iif (Number.isNaN(date.getTime())) return null;
  return `${date.toLocaleDateString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
  })} ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
};
 
export interface GenerationDetailsProps {
  /** The invocation to resolve, via `GET /app/generations/{id}`. */
  generationId: string;
  /**
   * Header facts already to hand — a history row carries an inlined
   * `GenerationRef`, so the flow and model can render before the request for
   * the arguments lands. Omit it and the header waits for the fetch.
   */
  summary?: GenerationRef | null;
  /**
   * `compact` — flow, model, arguments, warnings. For a history row, where
   * the actor and timestamp are already on the row above it.
   *
   * `full` — adds who invoked it, when, and the other resources it produced.
   * For a resource's own provenance panel, which is the only place those
   * questions get asked.
   */
  variant?: "compact" | "full";
  /** Left out of the produced list — the resource already on screen. */
  excludeResourceId?: string | null;
}
 
/**
 * What produced something: the flow, the model, and the exact arguments the
 * user supplied.
 *
 * Keyed on the id rather than on a `GenerationRef`, because the two callers
 * reach it from different directions. A history row already holds the ref and
 * passes it as `summary` so its header paints immediately; a resource holds
 * only its own `generation_id` and has nothing to pass. Either way the
 * arguments come from the same request, which only fires when someone asks to
 * see them.
 */
const GenerationDetails: React.FC<GenerationDetailsProps> = ({
  generationId,
  summary = null,
  variant = "compact",
  excludeResourceId = null,
}) => {
  const { getApiHandler } = useApiHandler();
 
  const { data, isLoading, isError } = useQuery<GenerationRun | null>({
    queryKey: [QUERY_KEYS.GET.GENERATION, generationId],
    queryFn: () => getApiHandler().generation_router.get(generationId),
  });
  // Bound to an explicitly typed const: the pinned TypeScript cannot infer
  // react-query v5's return type, so `data` arrives as `any` otherwise.
  const run: GenerationRun | null = data ?? null;
 
  // The header prefers what it was handed so it does not blank while loading,
  // then falls back to the fetched run.
  const flow = summary?.flow ?? run?.flow;
  const status = summary?.status ?? run?.status;
  const provider = summary?.provider ?? run?.provider;
  const modelName = summary?.model_name ?? run?.model_name;
 
  const args: [string, unknown][] = Object.entries(run?.arguments ?? {}).filter(
    ([key, value]) => !UNINTERESTING_ARGUMENT_KEYS.has(key) && value != null,
  );
  const warnings: string[] = run?.warnings ?? [];
 
  const produced: ProducedResource[] = (run?.produced ?? []).filter(
    (item) => item.resource_id !== excludeResourceId,
  );
 
  const invokedAt = formatTimestamp(run?.created_at ?? summary?.created_at);
 
  return (
    <div className="mt-2 rounded-lg border border-violet-200 dark:border-violet-800 bg-violet-50/60 dark:bg-violet-950/20 px-3 py-2.5 space-y-2">
      <div className="flex items-center gap-1.5 text-[11px] font-semibold text-violet-800 dark:text-violet-300">
        <Sparkles className="size-3 shrink-0" />
        {flow ? (GENERATION_FLOW_LABELS[flow] ?? flow) : "Generative invocation"}
        {status === "failed" && (
          <span className="text-red-600 dark:text-red-400">· failed</span>
        )}
      </div>
 
      {(modelName || provider) && (
        <div className="flex items-center gap-1.5 text-[11px] text-gray-600 dark:text-gray-400">
          <Cpu className="size-3 shrink-0" />
          {[provider ? makerLabel(provider, modelName) : null, modelName]
            .filter(Boolean)
            .join(" · ")}
        </div>
      )}
 
      {variant === "full" && (run?.actor_name || invokedAt) && (
        <div className="flex items-center gap-1.5 text-[11px] text-gray-600 dark:text-gray-400">
          <User className="size-3 shrink-0" />
          {[run?.actor_name ?? "Unknown user", invokedAt]
            .filter(Boolean)
            .join(" · ")}
        </div>
      )}
 
      {isLoading ? (
        <div className="animate-pulse h-8 rounded bg-violet-100 dark:bg-violet-900/40" />
      ) : isError ? (
        // A run is scoped to whoever invoked it, so a teammate's resource
        // reports its provenance without being able to open the arguments.
        <p className="text-[11px] text-gray-500 dark:text-gray-500 italic">
          The arguments for this invocation are not available to you.
        </p>
      ) : args.length > 0 ? (
        <dl className="space-y-1.5">
          {args.map(([key, value]) => (
            <div key={key}>
              <dt className="text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-500">
                {humanise(key)}
              </dt>
              <dd className="text-[11px] text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words">
                {formatArgument(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p className="text-[11px] text-gray-500 dark:text-gray-500 italic">
          No arguments recorded for this invocation.
        </p>
      )}
 
      {variant === "full" && produced.length > 0 && (
        <div>
          <p className="text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-500 mb-1">
            Also created
          </p>
          <ul className="space-y-0.5">
            {produced.map((item) => {
              const label =
                RESOURCE_TYPE_LABELS[
                  item.resource_type as keyof typeof RESOURCE_TYPE_LABELS
                ] ?? item.resource_type;
              const name = item.name || "Unnamed";
              const href = resourceHref(item.resource_type, item.resource_id);
              const body = (
                <>
                  <Boxes className="size-3 shrink-0 text-gray-400 dark:text-gray-500" />
                  <span className="truncate">{name}</span>
                  <span className="text-gray-400 dark:text-gray-500 shrink-0">
                    {label}
                  </span>
                </>
              );
              return (
                <li key={`${item.resource_type}-${item.resource_id}`}>
                  {href ? (
                    <Link
                      to={href}
                      className="flex items-center gap-1.5 text-[11px] text-gray-700 dark:text-gray-300 hover:text-violet-700 dark:hover:text-violet-300 hover:underline"
                    >
                      {body}
                    </Link>
                  ) : (
                    // Deleted since, or a type with no detail page. It still
                    // belongs on the list — what a run produced is a fact
                    // about the run, not about what survives.
                    <span className="flex items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-500">
                      {body}
                    </span>
                  )}
                </li>
              );
            })}
          </ul>
        </div>
      )}
 
      {warnings.length > 0 && (
        <ul className="space-y-1">
          {warnings.map((warning: string, i: number) => (
            <li
              key={i}
              className="flex items-start gap-1.5 text-[11px] text-amber-700 dark:text-amber-400"
            >
              <AlertTriangle className="size-3 mt-px shrink-0" />
              <span>{warning}</span>
            </li>
          ))}
        </ul>
      )}
 
      {run?.error && (
        <p className="text-[11px] text-red-600 dark:text-red-400">
          {run.error}
        </p>
      )}
    </div>
  );
};
 
export default GenerationDetails;