Skip to content

The platform for continuously improving AI agents.

7.0 KB
Raw Blame
import { Graph as DagreGraph, layout as dagreLayout } from "@dagrejs/dagre";

import type { GraphEdge, GraphNode, PathStep } from "@/lib/otel-rpc/gen/v1/graph_pb";

export type EdgeFilterMode = "all" | "flow" | "hierarchy";

export const NODE_WIDTH = 228;
export const NODE_HEIGHT = 82;

export interface NodeKindStyle {
  label: string;
  accent: string;
  pillClass: string;
  minimapColor: string;
}

export const NODE_KIND_STYLES: Record<string, NodeKindStyle> = {
  agent: {
    accent: "var(--info)",
    label: "AGENT",
    minimapColor: "var(--info)",
    pillClass: "border-info/40 bg-info/10 text-info",
  },
  chain: {
    accent: "var(--muted-foreground)",
    label: "CHAIN",
    minimapColor: "var(--muted-foreground)",
    pillClass: "border-border bg-wash-subtle text-muted-foreground",
  },
  llm: {
    accent: "var(--primary)",
    label: "LLM",
    minimapColor: "var(--primary)",
    pillClass: "border-primary/40 bg-primary/10 text-primary",
  },
  output: {
    accent: "var(--destructive)",
    label: "OUTPUT",
    minimapColor: "var(--destructive)",
    pillClass: "border-destructive/40 bg-destructive/10 text-destructive",
  },
  retrieval: {
    accent: "var(--warning)",
    label: "RETRIEVAL",
    minimapColor: "var(--warning)",
    pillClass: "border-warning/40 bg-warning/10 text-warning",
  },
  span: {
    accent: "var(--muted-foreground)",
    label: "SPAN",
    minimapColor: "var(--muted-foreground)",
    pillClass: "border-border bg-wash-raised text-muted-foreground",
  },
  tool: {
    accent: "var(--success)",
    label: "TOOL",
    minimapColor: "var(--success)",
    pillClass: "border-success/40 bg-success/10 text-success",
  },
};

export function getNodeKindStyle(kind: string): NodeKindStyle {
  return NODE_KIND_STYLES[kind.toLowerCase()] ?? NODE_KIND_STYLES.span;
}

export function filterEdgesByMode(edges: GraphEdge[], mode: EdgeFilterMode): GraphEdge[] {
  if (mode === "all") return edges;
  if (mode === "flow") {
    return edges.filter((e) => e.kind !== "child");
  }
  return edges.filter((e) => e.kind === "child" || e.kind === "output");
}

export interface NodePosition {
  x: number;
  y: number;
}

/**
 * Computes a deterministic left-to-right (LR) hierarchical layout via Dagre.
 * Self-loops are excluded from ranking and non-loop edges take priority so
 * cyclic graphs stay readable left-to-right from entrypoints to outputs.
 */
export function layoutExecutionGraph(
  nodes: GraphNode[],
  edges: GraphEdge[]
): Map<string, NodePosition> {
  const positions = new Map<string, NodePosition>();
  if (nodes.length === 0) return positions;

  const g = new DagreGraph({ compound: false, multigraph: false });
  g.setGraph({
    edgesep: 24,
    marginx: 36,
    marginy: 36,
    nodesep: 42,
    rankdir: "LR",
    ranker: "network-simplex",
    ranksep: 96,
  });
  g.setDefaultEdgeLabel(() => ({}));

  const nodeIds = new Set<string>();
  for (const node of nodes) {
    nodeIds.add(node.nodeId);
    g.setNode(node.nodeId, { height: NODE_HEIGHT, width: NODE_WIDTH });
  }

  const pairAdded = new Set<string>();
  const sortedEdges = [...edges].sort((a, b) => {
    // Non-loop edges first, then by transition count descending.
    if (a.isLoop !== b.isLoop) return a.isLoop ? 1 : -1;
    if (a.transitionCount !== b.transitionCount) {
      return a.transitionCount > b.transitionCount ? -1 : 1;
    }
    return a.edgeId.localeCompare(b.edgeId);
  });

  for (const edge of sortedEdges) {
    if (edge.fromNodeId === edge.toNodeId) continue;
    if (!nodeIds.has(edge.fromNodeId) || !nodeIds.has(edge.toNodeId)) continue;
    // Skip loop edges during Dagre ranking if they create trivial reverse pairs
    // so the main forward direction governs LR ordering.
    const reverseKey = `${edge.toNodeId}=>${edge.fromNodeId}`;
    const forwardKey = `${edge.fromNodeId}=>${edge.toNodeId}`;
    if (pairAdded.has(forwardKey)) continue;
    if (edge.isLoop && pairAdded.has(reverseKey)) continue;

    pairAdded.add(forwardKey);
    g.setEdge(edge.fromNodeId, edge.toNodeId, {
      minlen: 1,
      weight: edge.isLoop ? 1 : edge.kind === "child" ? 2 : 3,
    });
  }

  dagreLayout(g);

  for (const node of nodes) {
    const laidOut = g.node(node.nodeId);
    if (laidOut && Number.isFinite(laidOut.x) && Number.isFinite(laidOut.y)) {
      positions.set(node.nodeId, {
        x: Math.round(laidOut.x - NODE_WIDTH / 2),
        y: Math.round(laidOut.y - NODE_HEIGHT / 2),
      });
    } else {
      positions.set(node.nodeId, { x: 0, y: 0 });
    }
  }

  return positions;
}

export interface CollapsedPathStep {
  nodeId: string;
  label: string;
  kind: string;
  depth: number;
  repeatCount: number;
  isLoopBack: boolean;
  firstStepIndex: number;
  lastStepIndex: number;
}

export function collapsePathSteps(steps: PathStep[]): CollapsedPathStep[] {
  const result: CollapsedPathStep[] = [];
  for (const step of steps) {
    const prev = result[result.length - 1];
    if (prev && prev.nodeId === step.nodeId && prev.depth === step.depth) {
      prev.repeatCount += 1;
      prev.isLoopBack = prev.isLoopBack || step.isLoopBack;
      prev.lastStepIndex = step.stepIndex;
    } else {
      result.push({
        depth: step.depth,
        firstStepIndex: step.stepIndex,
        isLoopBack: step.isLoopBack,
        kind: step.kind,
        label: step.label,
        lastStepIndex: step.stepIndex,
        nodeId: step.nodeId,
        repeatCount: 1,
      });
    }
  }
  return result;
}

export function formatDurationMs(ms: number | undefined): string {
  if (ms === undefined || !Number.isFinite(ms)) return "—";
  if (ms < 1) return `${Math.round(ms * 1000)}µs`;
  if (ms < 1000) return `${ms >= 100 ? ms.toFixed(0) : ms.toFixed(1).replace(/\.0$/, "")}ms`;
  if (ms < 60_000) return `${(ms / 1000).toFixed(2).replace(/0+$/, "").replace(/\.$/, "")}s`;
  const mins = Math.floor(ms / 60_000);
  const secs = Math.round((ms % 60_000) / 1000);
  return `${mins}m ${secs}s`;
}

export function formatCompactCount(value: bigint | number): string {
  const num = typeof value === "bigint" ? Number(value) : value;
  if (!Number.isFinite(num)) return "0";
  if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
  if (num >= 10_000) return `${(num / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
  return new Intl.NumberFormat().format(num);
}

export function formatMeasuredCost(usd: number | undefined): string {
  if (usd === undefined || !Number.isFinite(usd) || usd <= 0) return "—";
  if (usd < 0.01) return `$${usd.toFixed(5).replace(/0+$/, "")}`;
  return `$${usd.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}`;
}

export function formatPercent(ratio: number): string {
  if (!Number.isFinite(ratio) || ratio <= 0) return "0%";
  const pct = ratio * 100;
  if (pct < 0.1) return "<0.1%";
  if (pct >= 10) return `${pct.toFixed(1)}%`;
  return `${pct.toFixed(1)}%`;
}

export function formatScore(score: number | undefined): string {
  if (score === undefined || !Number.isFinite(score)) return "—";
  return score.toFixed(2);
}

export function stripNodePrefix(nodeId: string): string {
  const idx = nodeId.indexOf(":");
  return idx >= 0 ? nodeId.slice(idx + 1) : nodeId;
}