Skip to content

The platform for continuously improving AI agents.

23.4 KB
Raw Blame
import { memo, useEffect, useMemo, useState } from "react";

import {
  Background,
  BackgroundVariant,
  BaseEdge,
  Controls,
  type Edge,
  EdgeLabelRenderer,
  type EdgeProps,
  getSmoothStepPath,
  Handle,
  MarkerType,
  MiniMap,
  type Node,
  type NodeProps,
  Position,
  ReactFlow,
  ReactFlowProvider,
  useReactFlow,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";

import {
  collapsePathSteps,
  formatCompactCount,
  formatDurationMs,
  getNodeKindStyle,
  layoutExecutionGraph,
  NODE_HEIGHT,
  NODE_WIDTH,
} from "@/components/otel/graph/graph-layout";
import { Icon } from "@/components/ui/icons";
import type { GraphEdge, GraphNode, GraphPath } from "@/lib/otel-rpc/gen/v1/graph_pb";

interface ExecutionNodeData extends Record<string, unknown> {
  node: GraphNode;
  inSelectedPath: boolean;
  dimmed: boolean;
  isFilterTarget: boolean;
  stepOrders: number[];
}

interface ExecutionEdgeData extends Record<string, unknown> {
  edge: GraphEdge;
  inSelectedPath: boolean;
  dimmed: boolean;
  isSelfLoop: boolean;
  isBackEdge: boolean;
  curveSlot: number;
  hovered: boolean;
}

type ExecutionFlowNode = Node<ExecutionNodeData, "execution">;
type ExecutionFlowEdge = Edge<ExecutionEdgeData, "execution">;

function NodeKindIcon({ kind, className }: { kind: string; className?: string }) {
  switch (kind.toLowerCase()) {
    case "agent":
      return <Icon.circle className={className} />;
    case "llm":
      return <Icon.circle className={className} />;
    case "tool":
      return <Icon.settings className={className} />;
    case "chain":
      return <Icon.circle className={className} />;
    case "retrieval":
      return <Icon.circle className={className} />;
    case "output":
      return <Icon.circle className={className} />;
    default:
      return <Icon.circle className={className} />;
  }
}

const ExecutionNode = memo(function ExecutionNode({ data }: NodeProps<ExecutionFlowNode>) {
  const { node, inSelectedPath, dimmed, isFilterTarget, stepOrders } = data;
  const style = getNodeKindStyle(node.kind);
  const hasErrors = node.errorCount > 0n;
  const stepBadge =
    stepOrders.length === 0
      ? null
      : stepOrders.length <= 3
        ? stepOrders.map((n) => `#${n}`).join(", ")
        : `#${stepOrders[0]}, #${stepOrders[1]} +${stepOrders.length - 2}`;

  return (
    <div
      className={[
        "obs-metrics relative flex flex-col justify-between rounded-sm border bg-card px-2.5 py-2 transition-opacity duration-150",
        inSelectedPath
          ? "border-primary bg-wash-raised ring-1 ring-primary/60"
          : isFilterTarget
            ? "border-warning bg-wash-subtle ring-1 ring-warning/50"
            : "border-border hover:border-foreground/50",
        dimmed ? "opacity-[0.16]" : "opacity-100",
      ].join(" ")}
      style={{
        borderLeftColor: inSelectedPath ? "var(--foreground)" : style.accent,
        borderLeftWidth: 3,
        height: NODE_HEIGHT,
        width: NODE_WIDTH,
      }}
      title={`${node.nodeId}\n${node.traceCount} traces · ${node.spanCount} spans · avg ${formatDurationMs(node.avgDurationMs)}`}
    >
      <Handle
        className="!h-2 !w-2 !rounded-sm !border !border-border !bg-background"
        position={Position.Left}
        type="target"
      />
      <Handle
        className="!h-2 !w-2 !rounded-sm !border !border-border !bg-background"
        position={Position.Right}
        type="source"
      />

      {stepBadge && (
        <span className="absolute -top-2.5 right-1.5 rounded-sm border border-primary/80 bg-primary px-1.5 py-0.5 font-mono text-xs font-semibold leading-none text-primary-foreground">
          {stepBadge}
        </span>
      )}

      <div className="flex items-center justify-between gap-1.5">
        <span
          className={`inline-flex items-center gap-1 rounded-sm border px-1.5 py-0.5 font-mono text-xs font-medium leading-none  ${style.pillClass}`}
        >
          <NodeKindIcon className="size-2.5 shrink-0" kind={node.kind} />
          {style.label}
        </span>
        <div className="flex items-center gap-1">
          {node.isEntry && (
            <span className="rounded-sm border border-info/40 bg-info/10 px-1 py-0.5 font-mono text-xs leading-none text-info">
              IN
            </span>
          )}
          {node.isExit && (
            <span className="rounded-sm border border-border bg-border px-1 py-0.5 font-mono text-xs leading-none text-muted-foreground">
              OUT
            </span>
          )}
          {node.hasSelfLoop && (
            <span
              className="inline-flex items-center gap-0.5 rounded-sm border border-warning/40 bg-warning/12 px-1 py-0.5 font-mono text-xs leading-none text-warning"
              title="Self-loop observed on this node"
            >
              <Icon.circle className="size-2.5" />
            </span>
          )}
          {hasErrors && (
            <span
              className="inline-flex items-center gap-0.5 rounded-sm border border-destructive/40 bg-destructive/12 px-1 py-0.5 font-mono text-xs leading-none text-destructive"
              title={`${node.errorCount} error spans`}
            >
              <Icon.warning className="size-2.5" />
              {formatCompactCount(node.errorCount)}
            </span>
          )}
        </div>
      </div>

      <div className="truncate font-mono text-xs font-medium text-foreground">{node.label}</div>

      <div className="flex items-center justify-between gap-2 font-mono text-xs text-muted-foreground">
        <span>
          {formatCompactCount(node.traceCount)}t · {formatCompactCount(node.spanCount)}s
        </span>
        <span>{formatDurationMs(node.avgDurationMs)}</span>
      </div>
    </div>
  );
});

const ExecutionEdge = memo(function ExecutionEdge({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  markerEnd,
  data,
}: EdgeProps<ExecutionFlowEdge>) {
  if (!data) return null;
  const { edge, inSelectedPath, dimmed, isSelfLoop, isBackEdge, curveSlot, hovered } = data;

  let edgePath = "";
  let labelX = (sourceX + targetX) / 2;
  let labelY = (sourceY + targetY) / 2;

  if (isSelfLoop) {
    // Source handle is on the right center, target handle is on the left center of the same node.
    // Draw a crisp symmetric loop arch above the top edge of the node.
    const nodeCenterX = (sourceX + targetX) / 2;
    const topY = sourceY - NODE_HEIGHT / 2;
    const startX = nodeCenterX + NODE_WIDTH * 0.2;
    const endX = nodeCenterX - NODE_WIDTH * 0.2;
    const archHeight = 52;
    edgePath = `M ${startX} ${topY} C ${startX + 26} ${topY - archHeight}, ${endX - 26} ${topY - archHeight}, ${endX} ${topY}`;
    labelX = nodeCenterX;
    labelY = topY - archHeight + 6;
  } else if (isBackEdge) {
    // Draw an unmistakable curved return arc looping beneath (or above for alternating slots)
    // so cycles never collide with forward flow edges.
    const horizontalSpan = Math.abs(sourceX - targetX);
    const verticalLift = Math.min(200, Math.max(66, horizontalSpan * 0.24) + curveSlot * 24);
    const goAbove = curveSlot % 2 === 1;
    const baseY = goAbove ? Math.min(sourceY, targetY) : Math.max(sourceY, targetY);
    const controlY = goAbove ? baseY - verticalLift : baseY + verticalLift;
    const c1x = sourceX + 34;
    const c2x = targetX - 34;
    edgePath = `M ${sourceX} ${sourceY} C ${c1x} ${controlY}, ${c2x} ${controlY}, ${targetX} ${targetY}`;
    labelX = (sourceX + targetX) / 2;
    labelY = goAbove ? baseY - verticalLift * 0.74 : baseY + verticalLift * 0.74;
  } else {
    const [path, lx, ly] = getSmoothStepPath({
      borderRadius: 6,
      offset: 18,
      sourcePosition,
      sourceX,
      sourceY,
      targetPosition,
      targetX,
      targetY,
    });
    edgePath = path;
    labelX = lx;
    labelY = ly;
  }

  const isLoopStyle = isSelfLoop || isBackEdge || edge.isLoop;
  const isChild = edge.kind === "child";
  const isOutput = edge.kind === "output";

  let stroke = "var(--foreground)";
  if (inSelectedPath) {
    stroke = isLoopStyle
      ? "var(--foreground)"
      : isOutput
        ? "var(--foreground)"
        : "var(--foreground)";
  } else if (isLoopStyle) {
    stroke = hovered ? "var(--foreground)" : "var(--foreground)";
  } else if (isOutput) {
    stroke = hovered ? "var(--foreground)" : "var(--foreground)";
  } else if (isChild) {
    stroke = hovered ? "var(--foreground)" : "var(--foreground)";
  } else if (hovered) {
    stroke = "var(--foreground)";
  }

  const strokeWidth = inSelectedPath
    ? 2.4
    : hovered
      ? 2
      : isLoopStyle
        ? 1.75
        : isChild
          ? 1.15
          : 1.4;
  const strokeDasharray = inSelectedPath
    ? undefined
    : isLoopStyle
      ? "5 4"
      : isChild
        ? "3 3"
        : undefined;
  const opacity = dimmed ? 0.12 : inSelectedPath || hovered ? 1 : isLoopStyle ? 0.88 : 0.72;

  const showLabel = inSelectedPath || hovered || isSelfLoop || (isLoopStyle && !dimmed);
  const labelText = isLoopStyle
    ? `↻ ${formatCompactCount(edge.transitionCount)}`
    : formatCompactCount(edge.transitionCount);

  return (
    <>
      <BaseEdge
        className={inSelectedPath ? "overmind-edge-animated" : undefined}
        id={id}
        markerEnd={markerEnd}
        path={edgePath}
        style={{
          opacity,
          stroke,
          strokeDasharray,
          strokeWidth,
        }}
      />
      {showLabel && (
        <EdgeLabelRenderer>
          <div
            className={[
              "obs-metrics rounded-sm border px-1.5 py-0.5 font-mono text-xs leading-none",
              inSelectedPath
                ? isLoopStyle
                  ? "border-warning bg-border text-warning"
                  : "border-primary/80 bg-card text-foreground"
                : isLoopStyle
                  ? "border-warning/50 bg-border text-warning"
                  : "border-border bg-card text-muted-foreground",
              dimmed ? "opacity-20" : "opacity-100",
            ].join(" ")}
            style={{
              pointerEvents: "none",
              position: "absolute",
              transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
            }}
          >
            {labelText}
          </div>
        </EdgeLabelRenderer>
      )}
    </>
  );
});

const nodeTypes = { execution: ExecutionNode };
const edgeTypes = { execution: ExecutionEdge };

export interface ExecutionGraphCanvasProps {
  nodes: GraphNode[];
  edges: GraphEdge[];
  selectedPath: GraphPath | null;
  filterNodeId: string | null;
  fitViewTrigger: number;
  onNodeClick: (nodeId: string) => void;
  onPaneClick?: () => void;
}

function ExecutionGraphCanvasInner({
  nodes,
  edges,
  selectedPath,
  filterNodeId,
  fitViewTrigger,
  onNodeClick,
  onPaneClick,
}: ExecutionGraphCanvasProps) {
  const { fitView, setCenter } = useReactFlow();
  const [hoveredEdgeId, setHoveredEdgeId] = useState<string | null>(null);
  const [collapseLoopsInStrip, setCollapseLoopsInStrip] = useState(false);

  const positions = useMemo(() => layoutExecutionGraph(nodes, edges), [nodes, edges]);

  const selectedNodeSteps = useMemo(() => {
    const map = new Map<string, number[]>();
    if (!selectedPath) return map;
    for (const step of selectedPath.steps) {
      const list = map.get(step.nodeId) ?? [];
      list.push(step.stepIndex + 1);
      map.set(step.nodeId, list);
    }
    return map;
  }, [selectedPath]);

  const selectedNodeSet = useMemo(() => new Set(selectedPath?.nodeIds ?? []), [selectedPath]);
  const selectedEdgeSet = useMemo(() => new Set(selectedPath?.edgeIds ?? []), [selectedPath]);

  const flowNodes: ExecutionFlowNode[] = useMemo(() => {
    const hasPath = selectedPath !== null;
    return nodes.map((node) => {
      const pos = positions.get(node.nodeId) ?? { x: 0, y: 0 };
      const inSelectedPath = hasPath && selectedNodeSet.has(node.nodeId);
      return {
        data: {
          dimmed: hasPath && !inSelectedPath,
          inSelectedPath,
          isFilterTarget: filterNodeId === node.nodeId,
          node,
          stepOrders: selectedNodeSteps.get(node.nodeId) ?? [],
        },
        draggable: true,
        id: node.nodeId,
        position: pos,
        selectable: true,
        type: "execution",
        zIndex: inSelectedPath ? 20 : 1,
      };
    });
  }, [nodes, positions, selectedPath, selectedNodeSet, selectedNodeSteps, filterNodeId]);

  const flowEdges: ExecutionFlowEdge[] = useMemo(() => {
    const hasPath = selectedPath !== null;
    const validNodeIds = new Set(nodes.map((n) => n.nodeId));
    const validEdges = edges.filter(
      (e) => validNodeIds.has(e.fromNodeId) && validNodeIds.has(e.toNodeId)
    );

    const backEdgeSlotMap = new Map<string, number>();
    let slot = 0;
    for (const edge of validEdges) {
      const isSelfLoop = edge.fromNodeId === edge.toNodeId;
      const fromPos = positions.get(edge.fromNodeId);
      const toPos = positions.get(edge.toNodeId);
      const isBackEdge =
        !isSelfLoop &&
        (edge.isLoop ||
          (fromPos !== undefined && toPos !== undefined && fromPos.x >= toPos.x - 10));
      if (isBackEdge) {
        backEdgeSlotMap.set(edge.edgeId, slot);
        slot += 1;
      }
    }

    return validEdges.map((edge) => {
      const isSelfLoop = edge.fromNodeId === edge.toNodeId;
      const curveSlot = backEdgeSlotMap.get(edge.edgeId) ?? 0;
      const isBackEdge = backEdgeSlotMap.has(edge.edgeId);
      const inSelectedPath = hasPath && selectedEdgeSet.has(edge.edgeId);
      const dimmed = hasPath && !inSelectedPath;
      const isLoopStyle = isSelfLoop || isBackEdge || edge.isLoop;
      const markerColor = inSelectedPath
        ? isLoopStyle
          ? "var(--foreground)"
          : edge.kind === "output"
            ? "var(--foreground)"
            : "var(--foreground)"
        : isLoopStyle
          ? "var(--foreground)"
          : edge.kind === "output"
            ? "var(--foreground)"
            : "var(--foreground)";

      return {
        data: {
          curveSlot,
          dimmed,
          edge,
          hovered: hoveredEdgeId === edge.edgeId,
          inSelectedPath,
          isBackEdge,
          isSelfLoop,
        },
        id: edge.edgeId,
        markerEnd: {
          color: markerColor,
          height: 14,
          type: MarkerType.ArrowClosed,
          width: 14,
        },
        source: edge.fromNodeId,
        target: edge.toNodeId,
        type: "execution",
        zIndex: inSelectedPath ? 30 : isLoopStyle ? 10 : 0,
      };
    });
  }, [edges, nodes, positions, selectedPath, selectedEdgeSet, hoveredEdgeId]);

  // Fit view whenever the underlying node set changes or Fit View button is clicked.
  const graphSignature = useMemo(() => nodes.map((n) => n.nodeId).join("|"), [nodes]);
  useEffect(() => {
    if (nodes.length === 0 || graphSignature.length + fitViewTrigger < 0) return;
    const timer = window.setTimeout(() => {
      void fitView({ duration: 240, padding: 0.16 });
    }, 30);
    return () => window.clearTimeout(timer);
  }, [graphSignature, fitViewTrigger, fitView, nodes.length]);

  function focusNode(nodeId: string) {
    const pos = positions.get(nodeId);
    if (!pos) return;
    void setCenter(pos.x + NODE_WIDTH / 2, pos.y + NODE_HEIGHT / 2, {
      duration: 240,
      zoom: 1.05,
    });
  }

  const collapsedSteps = useMemo(
    () => (selectedPath ? collapsePathSteps(selectedPath.steps) : []),
    [selectedPath]
  );

  return (
    <div className="overmind-flow relative h-full w-full bg-background">
      <ReactFlow
        edges={flowEdges}
        edgeTypes={edgeTypes}
        elementsSelectable
        fitView
        fitViewOptions={{ padding: 0.16 }}
        maxZoom={2.2}
        minZoom={0.12}
        nodes={flowNodes}
        nodesConnectable={false}
        nodeTypes={nodeTypes}
        onEdgeMouseEnter={(_event, edge) => setHoveredEdgeId(edge.id)}
        onEdgeMouseLeave={() => setHoveredEdgeId(null)}
        onNodeClick={(_event, node) => onNodeClick(node.id)}
        onPaneClick={onPaneClick}
        proOptions={{ hideAttribution: true }}
      >
        <Background color="var(--foreground)" gap={20} size={1} variant={BackgroundVariant.Dots} />
        <Controls position="top-right" showInteractive={false} />
        <MiniMap
          nodeColor={(node) => {
            const d = node.data as ExecutionNodeData | undefined;
            if (!d) return "var(--foreground)";
            if (d.dimmed) return "var(--foreground)";
            if (d.inSelectedPath) return "var(--foreground)";
            return getNodeKindStyle(d.node.kind).minimapColor;
          }}
          pannable
          position="bottom-right"
          style={{ height: 104, marginBottom: selectedPath ? 96 : 12, width: 156 }}
          zoomable
        />
      </ReactFlow>

      {/* Subtle legend in top-left corner */}
      <div className="obs-metrics pointer-events-none absolute top-3 left-3 flex flex-wrap items-center gap-2 rounded-sm border border-border bg-card/95 px-2.5 py-1.5 text-xs text-muted-foreground">
        <span className="inline-flex items-center gap-1.5">
          <span className="h-[2px] w-4 bg-border" />
          flow
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="h-0 w-4 border-t border-dashed border-warning" />
          loop
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="h-0 w-4 border-t border-dotted border-border" />
          child
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="h-[2px] w-4 bg-border" />
          output
        </span>
      </div>

      {/* Path Step Sequence Strip along bottom when a path is selected */}
      {selectedPath && (
        <div className="obs-metrics absolute right-3 bottom-3 left-3 z-20 rounded-sm border border-border bg-card/98 px-3 py-2">
          <div className="mb-1.5 flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <Icon.circle className="size-3.5 text-foreground" />
              <span className="font-medium text-foreground">Path sequence</span>
              <span className="font-mono text-xs">
                {selectedPath.steps.length} steps
                {selectedPath.hasLoops
                  ? ` · ↻ ${selectedPath.loopCount} loop${selectedPath.loopCount === 1 ? "" : "s"}`
                  : ""}
                {selectedPath.maxDepth > 0 ? ` · depth ${selectedPath.maxDepth}` : ""}
              </span>
            </div>
            <div className="inline-flex rounded-sm border border-border bg-background p-0.5 text-xs">
              <button
                className={[
                  "rounded-sm px-2 py-0.5 transition-colors",
                  !collapseLoopsInStrip
                    ? "bg-primary text-primary-foreground"
                    : "text-muted-foreground hover:text-foreground",
                ].join(" ")}
                onClick={() => setCollapseLoopsInStrip(false)}
                type="button"
              >
                Exact steps ({selectedPath.steps.length})
              </button>
              <button
                className={[
                  "rounded-sm px-2 py-0.5 transition-colors",
                  collapseLoopsInStrip
                    ? "bg-primary text-primary-foreground"
                    : "text-muted-foreground hover:text-foreground",
                ].join(" ")}
                onClick={() => setCollapseLoopsInStrip(true)}
                type="button"
              >
                Collapsed loops ({collapsedSteps.length})
              </button>
            </div>
          </div>

          <div className="flex items-center gap-1 overflow-x-auto pb-1">
            {!collapseLoopsInStrip
              ? selectedPath.steps.map((step, idx) => {
                  const kindStyle = getNodeKindStyle(step.kind);
                  return (
                    <div
                      className="flex shrink-0 items-center gap-1"
                      key={`${step.stepIndex}-${step.nodeId}`}
                    >
                      {idx > 0 && (
                        <span className="font-mono text-xs text-muted-foreground/60">→</span>
                      )}
                      <button
                        className={[
                          "inline-flex items-center gap-1 rounded-sm border px-1.5 py-0.5 font-mono text-xs transition-colors hover:border-foreground/60",
                          step.isLoopBack
                            ? "border-warning/60 bg-warning/10 text-warning"
                            : "border-border bg-background text-foreground",
                        ].join(" ")}
                        onClick={() => focusNode(step.nodeId)}
                        title={`Focus ${step.nodeId} (depth ${step.depth})`}
                        type="button"
                      >
                        <span className="text-xs text-muted-foreground">{step.stepIndex + 1}.</span>
                        <span
                          className="size-1.5 rounded-xs"
                          style={{ backgroundColor: kindStyle.accent }}
                        />
                        <span className="max-w-[140px] truncate">{step.label}</span>
                        {step.depth > 0 && (
                          <span className="text-xs text-muted-foreground">d{step.depth}</span>
                        )}
                        {step.isLoopBack && <span className="text-warning">↻</span>}
                      </button>
                    </div>
                  );
                })
              : collapsedSteps.map((step, idx) => {
                  const kindStyle = getNodeKindStyle(step.kind);
                  return (
                    <div
                      className="flex shrink-0 items-center gap-1"
                      key={`${step.firstStepIndex}-${step.nodeId}`}
                    >
                      {idx > 0 && (
                        <span className="font-mono text-xs text-muted-foreground/60">→</span>
                      )}
                      <button
                        className={[
                          "inline-flex items-center gap-1 rounded-sm border px-1.5 py-0.5 font-mono text-xs transition-colors hover:border-foreground/60",
                          step.isLoopBack || step.repeatCount > 1
                            ? "border-warning/60 bg-warning/10 text-warning"
                            : "border-border bg-background text-foreground",
                        ].join(" ")}
                        onClick={() => focusNode(step.nodeId)}
                        title={`Focus ${step.nodeId}`}
                        type="button"
                      >
                        <span
                          className="size-1.5 rounded-xs"
                          style={{ backgroundColor: kindStyle.accent }}
                        />
                        <span className="max-w-[140px] truncate">{step.label}</span>
                        {step.repeatCount > 1 && (
                          <span className="rounded-sm bg-warning/20 px-1 text-xs font-semibold text-warning">
                            ×{step.repeatCount}
                          </span>
                        )}
                        {step.isLoopBack && <span className="text-warning">↻</span>}
                      </button>
                    </div>
                  );
                })}
          </div>
        </div>
      )}
    </div>
  );
}

export function ExecutionGraphCanvas(props: ExecutionGraphCanvasProps) {
  return (
    <ReactFlowProvider>
      <ExecutionGraphCanvasInner {...props} />
    </ReactFlowProvider>
  );
}