Skip to content

The platform for continuously improving AI agents.

12.7 KB
Raw Blame
import { Fragment, type ReactNode, useState } from "react";

import type { JsonValue } from "@bufbuild/protobuf";
import { useQuery } from "@tanstack/react-query";

import { Badge } from "@/components/ui/badge";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { Skeleton } from "@/components/ui/skeleton";
import type { SpanEvent, SpanRow } from "@/hooks/use-traces";
import { traceClient } from "@/lib/otel-rpc/connect";
import { errorMessage } from "@/lib/otel-rpc/error";
import {
  formatJsonText,
  formatMetricValue,
  formatTime,
  severityVariant,
  structJson,
  valueJson,
} from "@/lib/otel-rpc/format";
import type {
  SpanEvent as ApiSpanEvent,
  LogRecord,
  MetricPoint,
} from "@/lib/otel-rpc/gen/v1/trace_pb";
import type { Expectation } from "@/lib/otel-rpc/genai";
import { parseExpectations } from "@/lib/otel-rpc/genai";
import { plainSpanNotes, type SpanNote } from "@/lib/otel-rpc/span-notes";

type Scope = "span" | "trace";

export function useSpanSideData(traceId: string, projectId: string) {
  const headers = { "X-Project-Id": projectId };
  const enabled = Boolean(traceId && projectId);
  const events = useQuery({
    enabled,
    queryFn: () => traceClient.listEvents({ pageSize: 200, traceId }, { headers }),
    queryKey: ["collector-trace-events", projectId, traceId],
  });
  const logs = useQuery({
    enabled,
    queryFn: () => traceClient.listLogs({ pageSize: 200, traceId }, { headers }),
    queryKey: ["collector-trace-logs", projectId, traceId],
  });
  const metrics = useQuery({
    enabled,
    queryFn: () => traceClient.listMetrics({ pageSize: 200, traceId }, { headers }),
    queryKey: ["collector-trace-metrics", projectId, traceId],
  });
  return { events, logs, metrics };
}

export function expectationList(span: SpanRow): Expectation[] {
  return parseExpectations(span.spanAttributes as Parameters<typeof parseExpectations>[0]);
}

export function spanNoteBundle(span: SpanRow) {
  return plainSpanNotes(span.spanAttributes, span.events);
}

export function ExpectationsPanel({ expectations }: { expectations: Expectation[] }) {
  if (expectations.length === 0) {
    return (
      <EmptyState
        description="This span has no declared expectations."
        icon={Icon.list}
        size="compact"
        title="No expectations"
      />
    );
  }
  return (
    <div className="grid gap-2">
      {expectations.map((item, index) => (
        <div
          className="grid gap-2 rounded-md border border-border bg-card p-3"
          key={item.id ?? `${item.type}-${index}`}
        >
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="neutral">{item.type}</Badge>
            {item.scope ? (
              <span className="text-xs text-muted-foreground">scope: {item.scope}</span>
            ) : null}
            {item.gate ? <Badge variant="info">Gate</Badge> : null}
            {item.id ? (
              <span className="ml-auto font-mono text-xs text-muted-foreground">{item.id}</span>
            ) : null}
          </div>
          <pre className="overflow-auto rounded-sm border border-border/70 bg-code-surface p-2.5 font-mono text-xs break-words whitespace-pre-wrap text-code-fg">
            {formatNote(item.value)}
          </pre>
        </div>
      ))}
    </div>
  );
}

export function FeedbackPanel({ notes }: { notes: SpanNote[] }) {
  if (notes.length === 0) {
    return (
      <EmptyState
        description="This span has no recorded feedback."
        icon={Icon.list}
        size="compact"
        title="No feedback"
      />
    );
  }
  return <NoteList notes={notes} />;
}

export function RecordedScores({ notes }: { notes: SpanNote[] }) {
  if (notes.length === 0) return null;
  return (
    <div className="px-3 py-2">
      <h3 className="mb-2 text-xs text-muted-foreground">Recorded scores</h3>
      <NoteList notes={notes} />
    </div>
  );
}

export function LogsPanel({
  error,
  isPending,
  logs,
  selectedSpanId,
  spanNameById,
}: {
  error: unknown;
  isPending: boolean;
  logs: LogRecord[];
  selectedSpanId: string;
  spanNameById: Map<string, string>;
}) {
  return (
    <ScopedList
      emptySpan="No logs on this span."
      emptyTrace="No logs on this trace."
      error={error}
      isPending={isPending}
      items={logs}
      renderItem={(log, scope) => {
        const body = formatJsonText(valueJson(log.body));
        return (
          <div className="grid gap-2 rounded-md border border-border bg-card p-3">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div className="flex min-w-0 flex-wrap items-center gap-2">
                <Badge variant={severityVariant(log.severityNumber)}>
                  {log.severityText || "Log"}
                </Badge>
                {scope === "trace" ? (
                  <SpanScopeBadge spanId={log.spanId} spanNameById={spanNameById} />
                ) : null}
              </div>
              <span className="shrink-0 font-mono text-xs text-muted-foreground">
                {formatTime(log.timeNs)}
              </span>
            </div>
            <pre className="overflow-auto rounded-sm border border-border/70 bg-code-surface px-2.5 py-2 font-mono text-xs break-words whitespace-pre-wrap text-code-fg">
              {body || "(empty body)"}
            </pre>
            <AttributeDump attributes={structJson(log.attributes)} />
          </div>
        );
      }}
      selectedSpanId={selectedSpanId}
      spanIdOf={(log) => log.spanId}
    />
  );
}

export function MetricsPanel({
  error,
  isPending,
  points,
  selectedSpanId,
  spanNameById,
}: {
  error: unknown;
  isPending: boolean;
  points: MetricPoint[];
  selectedSpanId: string;
  spanNameById: Map<string, string>;
}) {
  return (
    <ScopedList
      emptySpan="No metrics on this span."
      emptyTrace="No metrics on this trace."
      error={error}
      isPending={isPending}
      items={points}
      renderItem={(point, scope) => (
        <div className="grid gap-2 rounded-md border border-border bg-card p-3">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="flex min-w-0 flex-wrap items-center gap-2">
              <span className="font-mono text-xs font-medium text-foreground">
                {point.metricName}
              </span>
              <Badge variant="neutral">{point.metricType}</Badge>
              {point.unit ? <Badge variant="info">{point.unit}</Badge> : null}
              {scope === "trace" ? (
                <SpanScopeBadge spanId={point.spanId} spanNameById={spanNameById} />
              ) : null}
            </div>
            <div className="flex shrink-0 items-baseline gap-3">
              <span className="font-mono text-xs font-medium text-foreground">
                {formatMetricValue(point)}
              </span>
              <span className="font-mono text-xs text-muted-foreground">
                {formatTime(point.timeNs)}
              </span>
            </div>
          </div>
          {point.description ? (
            <p className="text-xs text-muted-foreground">{point.description}</p>
          ) : null}
          <AttributeDump attributes={structJson(point.attributes)} />
        </div>
      )}
      selectedSpanId={selectedSpanId}
      spanIdOf={(point) => point.spanId}
    />
  );
}

export type ShownEvent = SpanEvent & { spanId: string; spanName: string };

export function mergeTraceEvents(apiEvents: ApiSpanEvent[], spans: SpanRow[]): ShownEvent[] {
  const embeddedSpanIds = new Set(
    spans.filter((span) => span.events.length > 0).map((span) => span.spanId)
  );
  const merged: ShownEvent[] = [];
  for (const span of spans) {
    for (const event of span.events) {
      merged.push({ ...event, spanId: span.spanId, spanName: span.name });
    }
  }
  for (const event of apiEvents) {
    if (embeddedSpanIds.has(event.spanId)) continue;
    const time = event.timeNs > 0n ? Number(event.timeNs) : undefined;
    merged.push({
      attributes: event.attributes,
      name: event.name,
      spanId: event.spanId,
      spanName: event.spanName,
      timeUnixNano: time,
    });
  }
  merged.sort((left, right) => (right.timeUnixNano ?? 0) - (left.timeUnixNano ?? 0));
  return merged;
}

function ScopedList<T>({
  emptySpan,
  emptyTrace,
  error,
  isPending,
  items,
  renderItem,
  selectedSpanId,
  spanIdOf,
}: {
  emptySpan: string;
  emptyTrace: string;
  error: unknown;
  isPending: boolean;
  items: T[];
  renderItem: (item: T, scope: Scope) => ReactNode;
  selectedSpanId: string;
  spanIdOf: (item: T) => string | undefined;
}) {
  const [scope, setScope] = useState<Scope | null>(null);
  if (isPending) return <TabSkeleton />;
  if (error) return <p className="text-sm text-destructive">{errorMessage(error)}</p>;
  const spanItems = items.filter((item) => spanIdOf(item) === selectedSpanId);
  const active: Scope =
    scope ?? (spanItems.length > 0 ? "span" : items.length > 0 ? "trace" : "span");
  const visible = active === "span" ? spanItems : items;
  return (
    <div className="grid gap-3">
      <ScopeToggle
        onChange={setScope}
        scope={active}
        spanCount={spanItems.length}
        traceCount={items.length}
      />
      {visible.length === 0 ? (
        <EmptyState
          description={active === "span" ? emptySpan : emptyTrace}
          icon={Icon.list}
          size="compact"
          title={active === "span" ? "Nothing on this span" : "Nothing on this trace"}
        />
      ) : (
        <div className="grid gap-3">
          {visible.map((item, index) => (
            <Fragment key={index}>{renderItem(item, active)}</Fragment>
          ))}
        </div>
      )}
    </div>
  );
}

export function ScopeToggle({
  onChange,
  scope,
  spanCount,
  traceCount,
}: {
  onChange: (scope: Scope) => void;
  scope: Scope;
  spanCount: number;
  traceCount: number;
}) {
  return (
    <div className="inline-flex w-fit items-center rounded-md border border-border bg-background p-0.5 text-xs">
      <button
        aria-pressed={scope === "span"}
        className={`rounded-sm px-2.5 py-1 ${
          scope === "span"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
        onClick={() => onChange("span")}
        type="button"
      >
        Selected span ({spanCount})
      </button>
      <button
        aria-pressed={scope === "trace"}
        className={`rounded-sm px-2.5 py-1 ${
          scope === "trace"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
        onClick={() => onChange("trace")}
        type="button"
      >
        Entire trace ({traceCount})
      </button>
    </div>
  );
}

function SpanScopeBadge({
  spanId,
  spanNameById,
}: {
  spanId: string | undefined;
  spanNameById: Map<string, string>;
}) {
  if (!spanId) return <Badge variant="neutral">Trace-level</Badge>;
  const label = spanNameById.get(spanId) || spanId.slice(0, 8);
  return (
    <Badge className="max-w-44 truncate font-mono" title={spanId} variant="neutral">
      {label}
    </Badge>
  );
}

function NoteList({ notes }: { notes: SpanNote[] }) {
  return (
    <dl className="divide-y divide-border/70 rounded-md border border-border bg-card">
      {notes.map((note) => (
        <div
          className="grid gap-1 px-3 py-3 sm:grid-cols-[minmax(9rem,14rem)_minmax(0,1fr)] sm:gap-3"
          key={note.key}
        >
          <dt className="truncate font-mono text-xs text-muted-foreground">{note.key}</dt>
          <dd className="min-w-0 font-mono text-xs break-words whitespace-pre-wrap text-foreground">
            {formatNote(note.value)}
          </dd>
        </div>
      ))}
    </dl>
  );
}

function AttributeDump({ attributes }: { attributes: Record<string, unknown> | undefined }) {
  const entries = Object.entries(attributes ?? {});
  if (entries.length === 0) return null;
  return (
    <dl className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] gap-x-3 gap-y-1 text-xs">
      {entries.map(([key, value]) => (
        <div className="contents" key={key}>
          <dt className="truncate font-mono text-muted-foreground">{key}</dt>
          <dd className="min-w-0 font-mono break-words whitespace-pre-wrap text-foreground">
            {formatNote(value as JsonValue)}
          </dd>
        </div>
      ))}
    </dl>
  );
}

function TabSkeleton() {
  return (
    <div className="grid gap-2">
      <Skeleton className="h-8 w-52" />
      <Skeleton className="h-20 w-full" />
      <Skeleton className="h-20 w-full" />
    </div>
  );
}

function formatNote(value: JsonValue | unknown): string {
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
    return String(value);
  if (value === null || value === undefined) return "null";
  return JSON.stringify(value, null, 2);
}