Skip to content

The platform for continuously improving AI agents.

21.4 KB
Raw Blame
import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";

import {
  formatCompactCount,
  formatDurationMs,
  formatMeasuredCost,
  formatPercent,
  formatScore,
} from "@/components/otel/graph/graph-layout";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { errorMessage } from "@/lib/otel-rpc/error";
import { formatTime } from "@/lib/otel-rpc/format";
import { useConsoleProjectId } from "@/lib/otel-rpc/project";
import { pathDetailQuery } from "@/lib/otel-rpc/queries";

interface PathInspectorProps {
  pathId: string;
  onClose: () => void;
}

export function PathInspector({ pathId, onClose }: PathInspectorProps) {
  const projectId = useConsoleProjectId();
  const detailQuery = useQuery(pathDetailQuery(pathId, 100));

  if (detailQuery.isPending) {
    return (
      <aside className="obs-metrics flex h-full w-[420px] shrink-0 flex-col border-l border-border bg-card">
        <div className="flex items-center justify-between border-b border-border px-3.5 py-3">
          <Skeleton className="h-5 w-48" />
          <Button aria-label="Close inspector" onClick={onClose} size="icon-xs" variant="ghost">
            <Icon.close className="size-3.5" />
          </Button>
        </div>
        <div className="space-y-3 p-3.5">
          <Skeleton className="h-20 w-full" />
          <Skeleton className="h-9 w-full" />
          <Skeleton className="h-44 w-full" />
        </div>
      </aside>
    );
  }

  const detail = detailQuery.data;
  const path = detail?.path;
  if (detailQuery.isError || !detail || !path) {
    return (
      <aside className="obs-metrics flex h-full w-[420px] shrink-0 flex-col border-l border-border bg-card">
        <div className="flex items-center justify-between border-b border-border px-3.5 py-3">
          <span className="text-sm font-medium text-foreground">Path inspector</span>
          <Button aria-label="Close inspector" onClick={onClose} size="icon-xs" variant="ghost">
            <Icon.close className="size-3.5" />
          </Button>
        </div>
        <div className="p-4 text-xs text-destructive">
          {detailQuery.isError
            ? errorMessage(detailQuery.error)
            : "Path detail could not be loaded."}
        </div>
      </aside>
    );
  }

  const traceCountNum = Number(path.traceCount);
  const errorRate = traceCountNum > 0 ? Number(path.errorCount) / traceCountNum : 0;
  const hasErrors = path.errorCount > 0n;
  const codeCtx = detail.codeContext;

  return (
    <aside className="obs-metrics flex h-full w-[420px] shrink-0 flex-col border-l border-border bg-card">
      {/* Header */}
      <div className="border-b border-border px-3.5 py-3">
        <div className="flex items-start justify-between gap-2">
          <div className="min-w-0 flex-1">
            <div className="mb-1 flex flex-wrap items-center gap-1.5">
              <span className="rounded-sm border border-border bg-background px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
                {path.pathId.slice(0, 12)}
              </span>
              {path.hasLoops && (
                <Badge className="h-5 gap-1 px-1.5 text-xs" variant="warning">
                  <Icon.circle className="size-2.5" />
                  {path.loopCount} loop{path.loopCount === 1 ? "" : "s"}
                </Badge>
              )}
              {path.maxDepth > 0 && (
                <Badge className="h-5 px-1.5 text-xs" variant="neutral">
                  depth {path.maxDepth}
                </Badge>
              )}
              {path.avgEvalScore !== undefined && (
                <Badge className="h-5 px-1.5 text-xs" variant="success">
                  eval {formatScore(path.avgEvalScore)}
                </Badge>
              )}
            </div>
            <h2
              className="line-clamp-2 font-mono text-xs font-medium leading-relaxed text-foreground"
              title={path.collapsedSignature}
            >
              {path.collapsedSignature}
            </h2>
          </div>
          <Button
            aria-label="Close path inspector"
            onClick={onClose}
            size="icon-xs"
            variant="ghost"
          >
            <Icon.close className="size-3.5" />
          </Button>
        </div>

        {/* Share bar */}
        <div className="mt-2.5">
          <div className="mb-1 flex items-center justify-between text-xs">
            <span className="text-muted-foreground">Share of traces</span>
            <span className="font-mono font-medium text-foreground">
              {formatPercent(detail.shareOfTraces)} ({formatCompactCount(path.traceCount)})
            </span>
          </div>
          <div className="h-1.5 w-full overflow-hidden rounded-sm bg-background">
            <div
              className="h-full bg-info"
              style={{ width: `${Math.min(100, Math.max(2, detail.shareOfTraces * 100))}%` }}
            />
          </div>
        </div>

        {/* KPI grid */}
        <div className="mt-2.5 grid grid-cols-3 gap-1.5">
          <MetricTile
            label="Traces"
            sub={hasErrors ? `${formatPercent(errorRate)} err` : "0 errors"}
            subClass={hasErrors ? "text-destructive" : "text-muted-foreground"}
            value={formatCompactCount(path.traceCount)}
          />
          <MetricTile
            label="Avg / P95"
            sub={`p95 ${formatDurationMs(path.p95DurationMs)}`}
            value={formatDurationMs(path.avgDurationMs)}
          />
          <MetricTile
            label="Tokens / Cost"
            sub={formatMeasuredCost(path.totalCostUsd)}
            value={path.totalTokens > 0n ? formatCompactCount(path.totalTokens) : "—"}
          />
        </div>
      </div>

      {/* 4 Inspector Tabs */}
      <Tabs className="flex min-h-0 flex-1 flex-col" defaultValue="traces">
        <div className="border-b border-border px-3 py-2">
          <TabsList className="grid h-8 w-full grid-cols-4 bg-background p-0.5">
            <TabsTrigger className="h-7 px-1 text-xs" value="traces">
              Traces ({detail.traces.length})
            </TabsTrigger>
            <TabsTrigger className="h-7 px-1 text-xs" value="llm">
              LLM ({detail.llmCalls.length})
            </TabsTrigger>
            <TabsTrigger className="h-7 px-1 text-xs" value="tools">
              Tools ({detail.toolCalls.length})
            </TabsTrigger>
            <TabsTrigger className="h-7 px-1 text-xs" value="evals">
              Evals ({detail.evals.length})
            </TabsTrigger>
          </TabsList>
        </div>

        {/* Tab 1: Traces */}
        <TabsContent className="min-h-0 flex-1 overflow-y-auto p-3" value="traces">
          {detail.traces.length === 0 ? (
            <EmptyNote text="No traces recorded on this path." />
          ) : (
            <div className="space-y-1.5">
              {detail.traces.map((trace) => {
                const isErr = trace.statusCode === 2;
                return (
                  <Link
                    className="group block rounded-sm border border-border bg-background p-2.5 transition-colors hover:border-foreground/50 hover:bg-wash-subtle"
                    key={trace.traceId}
                    params={{ traceId: trace.traceId }}
                    search={{ projectId }}
                    to="/observability/$traceId"
                  >
                    <div className="flex items-center justify-between gap-2">
                      <div className="flex min-w-0 items-center gap-1.5">
                        <Badge className="h-4.5 px-1 text-xs" variant={isErr ? "error" : "success"}>
                          {isErr ? "ERR" : "OK"}
                        </Badge>
                        <span className="truncate font-mono text-xs font-medium text-foreground">
                          {trace.traceId.slice(0, 16)}
                        </span>
                        <Icon.circle className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
                      </div>
                      <span className="shrink-0 font-mono text-xs text-foreground">
                        {formatDurationMs(trace.durationMs)}
                      </span>
                    </div>

                    <div className="mt-1 flex items-center justify-between gap-2 text-xs text-muted-foreground">
                      <span className="truncate font-mono">{trace.serviceName}</span>
                      <span className="shrink-0 font-mono text-xs">
                        {formatTime(trace.startTimeNs)}
                      </span>
                    </div>

                    <div className="mt-1.5 flex flex-wrap items-center gap-1.5 font-mono text-xs text-muted-foreground">
                      <span>{formatCompactCount(trace.spanCount)} spans</span>
                      <span>·</span>
                      <span>{formatCompactCount(trace.llmCalls)} llm</span>
                      <span>·</span>
                      <span>{formatCompactCount(trace.toolCalls)} tool</span>
                      {trace.totalTokens > 0n && (
                        <>
                          <span>·</span>
                          <span>{formatCompactCount(trace.totalTokens)} tok</span>
                        </>
                      )}
                      {trace.costUsd > 0 && (
                        <>
                          <span>·</span>
                          <span>{formatMeasuredCost(trace.costUsd)}</span>
                        </>
                      )}
                    </div>

                    {(trace.outputLabel || trace.evalSummary) && (
                      <div className="mt-1.5 flex flex-wrap items-center gap-1.5">
                        {trace.outputLabel && (
                          <span className="rounded-sm border border-border bg-border px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
                            out: {trace.outputLabel}
                          </span>
                        )}
                        {trace.evalSummary && (
                          <span className="rounded-sm border border-border bg-card px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
                            evals: {formatCompactCount(trace.evalSummary.count)}
                            {trace.evalSummary.avgScore !== undefined
                              ? ` · avg ${formatScore(trace.evalSummary.avgScore)}`
                              : ""}
                          </span>
                        )}
                      </div>
                    )}
                  </Link>
                );
              })}
            </div>
          )}
        </TabsContent>

        {/* Tab 2: LLM Calls */}
        <TabsContent className="min-h-0 flex-1 overflow-y-auto p-3" value="llm">
          {detail.llmCalls.length === 0 ? (
            <EmptyNote text="No LLM calls recorded on this path." />
          ) : (
            <div className="space-y-2">
              {detail.llmCalls.map((call, index) => (
                <div
                  className="rounded-sm border border-border bg-background p-2.5"
                  key={`${call.nodeId}-${call.model ?? "unknown"}-${index}`}
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0">
                      <div className="flex items-center gap-1.5">
                        <Icon.circle className="size-3 shrink-0 text-info" />
                        <span className="truncate font-mono text-xs font-medium text-foreground">
                          {call.label}
                        </span>
                      </div>
                      <div className="mt-0.5 truncate font-mono text-xs text-info">
                        {call.model ?? "model unknown"}
                      </div>
                    </div>
                    <div className="flex shrink-0 items-center gap-1">
                      <Badge className="h-5 px-1.5 text-xs" variant="neutral">
                        {formatCompactCount(call.callCount)} calls
                      </Badge>
                      {call.errorCount > 0n && (
                        <Badge className="h-5 px-1.5 text-xs" variant="error">
                          {formatCompactCount(call.errorCount)} err
                        </Badge>
                      )}
                    </div>
                  </div>

                  <div className="mt-2 grid grid-cols-3 gap-1.5 border-t border-border/60 pt-2 font-mono text-xs">
                    <div>
                      <div className="text-xs text-muted-foreground">Avg latency</div>
                      <div className="text-foreground">{formatDurationMs(call.avgDurationMs)}</div>
                    </div>
                    <div>
                      <div className="text-xs text-muted-foreground">Avg in / out</div>
                      <div className="text-foreground">
                        {call.avgInputTokens !== undefined ? Math.round(call.avgInputTokens) : "—"}{" "}
                        /{" "}
                        {call.avgOutputTokens !== undefined
                          ? Math.round(call.avgOutputTokens)
                          : "—"}
                      </div>
                    </div>
                    <div>
                      <div className="text-xs text-muted-foreground">Cost</div>
                      <div className="text-foreground">{formatMeasuredCost(call.totalCostUsd)}</div>
                    </div>
                  </div>

                  {call.finishReasons.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-1">
                      {call.finishReasons.map((reason) => (
                        <span
                          className="rounded-sm border border-border bg-card px-1.5 py-0.5 font-mono text-xs text-muted-foreground"
                          key={reason}
                        >
                          {reason}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </TabsContent>

        {/* Tab 3: Tools & Codebase Context */}
        <TabsContent className="min-h-0 flex-1 overflow-y-auto p-3" value="tools">
          <div className="space-y-4">
            <section>
              <div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-foreground">
                <Icon.settings className="size-3.5 text-muted-foreground" />
                Tool calls ({detail.toolCalls.length})
              </div>
              {detail.toolCalls.length === 0 ? (
                <EmptyNote text="No tool calls recorded on this path." />
              ) : (
                <div className="space-y-1.5">
                  {detail.toolCalls.map((tool) => (
                    <div
                      className="flex items-center justify-between gap-2 rounded-sm border border-border bg-background px-2.5 py-2"
                      key={tool.nodeId}
                    >
                      <div className="min-w-0">
                        <div className="truncate font-mono text-xs font-medium text-foreground">
                          {tool.toolName}
                        </div>
                        <div className="font-mono text-xs text-muted-foreground">
                          avg {formatDurationMs(tool.avgDurationMs)}
                        </div>
                      </div>
                      <div className="flex shrink-0 items-center gap-1.5">
                        <Badge className="h-5 px-1.5 text-xs" variant="neutral">
                          {formatCompactCount(tool.callCount)} calls
                        </Badge>
                        {tool.errorCount > 0n && (
                          <Badge className="h-5 px-1.5 text-xs" variant="error">
                            <Icon.warning className="size-2.5" />
                            {formatCompactCount(tool.errorCount)}
                          </Badge>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </section>

            <section className="border-t border-border pt-3">
              <div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-foreground">
                <Icon.circle className="size-3.5 text-muted-foreground" />
                Path codebase context
              </div>
              {codeCtx ? (
                <div className="space-y-2.5">
                  <ContextChipGroup items={codeCtx.services} label="Services" />
                  <ContextChipGroup items={codeCtx.models} label="Models" />
                  <ContextChipGroup items={codeCtx.tools} label="Tools" />
                  <ContextChipGroup items={codeCtx.capabilities} label="Capabilities" />
                  <ContextChipGroup items={codeCtx.files} label="Code files" />
                  <ContextChipGroup items={codeCtx.functions} label="Functions" />
                  {codeCtx.services.length === 0 &&
                    codeCtx.models.length === 0 &&
                    codeCtx.tools.length === 0 &&
                    codeCtx.capabilities.length === 0 &&
                    codeCtx.files.length === 0 &&
                    codeCtx.functions.length === 0 && (
                      <EmptyNote text="No codebase metadata recorded on this path." />
                    )}
                </div>
              ) : (
                <EmptyNote text="No codebase metadata recorded on this path." />
              )}
            </section>
          </div>
        </TabsContent>

        {/* Tab 4: Evals */}
        <TabsContent className="min-h-0 flex-1 overflow-y-auto p-3" value="evals">
          {detail.evals.length === 0 ? (
            <EmptyNote text="No evals recorded on this path" />
          ) : (
            <div className="space-y-2">
              {detail.evals.map((ev) => (
                <div
                  className="rounded-sm border border-border bg-background p-2.5"
                  key={`${ev.kind}-${ev.name}`}
                >
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex min-w-0 items-center gap-1.5">
                      <Badge
                        className="h-5 px-1.5 text-xs "
                        variant={
                          ev.kind === "score"
                            ? "info"
                            : ev.kind === "expectation"
                              ? "warning"
                              : "neutral"
                        }
                      >
                        {ev.kind}
                      </Badge>
                      <span className="truncate font-mono text-xs font-medium text-foreground">
                        {ev.name}
                      </span>
                    </div>
                    <span className="shrink-0 font-mono text-xs font-semibold text-foreground">
                      {formatScore(ev.avgScore)}
                    </span>
                  </div>

                  <div className="mt-2 flex items-center gap-3 font-mono text-xs text-muted-foreground">
                    <span>{formatCompactCount(ev.count)} samples</span>
                    {ev.passedCount > 0n && (
                      <span className="inline-flex items-center gap-1 text-success">
                        <Icon.circle className="size-3" />
                        {formatCompactCount(ev.passedCount)} passed
                      </span>
                    )}
                    {ev.failedCount > 0n && (
                      <span className="inline-flex items-center gap-1 text-destructive">
                        <Icon.circle className="size-3" />
                        {formatCompactCount(ev.failedCount)} failed
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </aside>
  );
}

function MetricTile({
  label,
  value,
  sub,
  subClass = "text-muted-foreground",
}: {
  label: string;
  value: string;
  sub: string;
  subClass?: string;
}) {
  return (
    <div className="rounded-sm border border-border bg-background px-2 py-1.5">
      <div className="text-xs text-muted-foreground">{label}</div>
      <div className="mt-0.5 font-mono text-xs font-semibold text-foreground">{value}</div>
      <div className={`truncate font-mono text-xs ${subClass}`}>{sub}</div>
    </div>
  );
}

function ContextChipGroup({ label, items }: { label: string; items: string[] }) {
  if (items.length === 0) return null;
  return (
    <div>
      <div className="mb-1 text-xs font-medium   text-muted-foreground">
        {label} ({items.length})
      </div>
      <div className="flex flex-wrap gap-1">
        {items.map((item) => (
          <span
            className="max-w-full truncate rounded-sm border border-border bg-background px-1.5 py-0.5 font-mono text-xs text-foreground"
            key={item}
            title={item}
          >
            {item}
          </span>
        ))}
      </div>
    </div>
  );
}

function EmptyNote({ text }: { text: string }) {
  return (
    <div className="rounded-sm border border-dashed border-border bg-background/60 px-3 py-6 text-center text-xs text-muted-foreground">
      {text}
    </div>
  );
}