Skip to content

The platform for continuously improving AI agents.

6.8 KB
Raw Blame
import type { ReactNode } from "react";

import type { JsonObject, JsonValue } from "@bufbuild/protobuf";

import { GENAI_BODY_KEYS } from "@/lib/otel-rpc/genai";

export function AttributeSections({
  attributes,
  resource,
  omit,
}: {
  attributes: JsonObject | undefined;
  resource: JsonObject | undefined;
  omit?: Set<string>;
}) {
  const hidden = new Set([...GENAI_BODY_KEYS, ...(omit ?? [])]);
  return (
    <div className="grid min-w-0 gap-5">
      <AttributeList omit={hidden} title="Attributes" value={attributes} />
      <AttributeList title="Resource" value={resource} />
    </div>
  );
}

type Row = { key: string; label: string; value: JsonValue };
type Group = { title: string; rows: Row[]; groups: Group[] };
type Bucket = { rows: Row[]; groups: Group[] };
type Node = { value?: Row; children: Map<string, Node> };

function AttributeList({
  title,
  value,
  omit,
}: {
  title: string;
  value: JsonObject | undefined;
  omit?: Set<string>;
}) {
  const entries = Object.entries(value ?? {})
    .filter(
      (entry): entry is [string, JsonValue] =>
        !omit?.has(entry[0]) && entry[1] !== undefined && entry[1] !== null && entry[1] !== ""
    )
    .map(([key, entry]) => ({ key, label: key, value: entry }));
  if (entries.length === 0) return null;
  const bucket = groupRows(entries);
  return (
    <section className="grid min-w-0 gap-2">
      <h3 className="pixel-label text-xs text-muted-foreground">{title}</h3>
      <BucketView bucket={bucket} />
    </section>
  );
}

function BucketView({ bucket }: { bucket: Bucket }) {
  return (
    <div className="grid min-w-0 gap-3">
      {bucket.rows.length > 0 ? <Rows rows={bucket.rows} /> : null}
      {bucket.groups.map((group) => (
        <GroupView group={group} key={group.title} />
      ))}
    </div>
  );
}

function GroupView({ group }: { group: Group }) {
  return (
    <section className="grid min-w-0 gap-2">
      <h4
        className="font-mono text-xs break-words text-muted-foreground [overflow-wrap:anywhere]"
        title={group.title}
      >
        {group.title}
      </h4>
      {group.rows.length > 0 ? <Rows rows={group.rows} /> : null}
      {group.groups.length > 0 ? (
        <div className="grid min-w-0 gap-3 border-l border-border/70 pl-3">
          {group.groups.map((child) => (
            <GroupView group={child} key={child.title} />
          ))}
        </div>
      ) : null}
    </section>
  );
}

function Rows({ rows }: { rows: Row[] }) {
  return (
    <dl className="divide-y divide-border/70 rounded-md border border-border bg-card">
      {rows.map((row) => (
        <div
          className="grid gap-1 px-3 py-2 sm:grid-cols-[minmax(8rem,1fr)_minmax(0,1.4fr)] sm:gap-3"
          key={row.key}
        >
          <dt
            className="font-mono text-xs break-words text-muted-foreground [overflow-wrap:anywhere]"
            title={row.key}
          >
            {row.label}
          </dt>
          <dd className="min-w-0 text-sm text-foreground">{renderValue(row.value)}</dd>
        </div>
      ))}
    </dl>
  );
}

function groupRows(entries: Row[]): Bucket {
  const root = emptyNode();
  for (const entry of entries) {
    let node = root;
    for (const part of entry.key.split(".")) {
      const child = node.children.get(part) ?? emptyNode();
      node.children.set(part, child);
      node = child;
    }
    node.value = entry;
  }
  return hoist(partition(root, []));
}

function partition(node: Node, prefix: string[]): Bucket {
  const rows: Row[] = [];
  const groups: Group[] = [];
  if (node.value) rows.push(labeled(node.value, prefix));
  for (const [name, child] of [...node.children].sort(([left], [right]) =>
    left.localeCompare(right)
  )) {
    const collapsed = collapse(child, [...prefix, name]);
    const descendants = size(collapsed.node) - (collapsed.node.value ? 1 : 0);
    if (descendants >= 2) {
      if (collapsed.node.value) rows.push(labeled(collapsed.node.value, prefix));
      const inner = partition(
        { children: collapsed.node.children, value: undefined },
        collapsed.prefix
      );
      groups.push({ groups: inner.groups, rows: inner.rows, title: collapsed.prefix.join(".") });
    } else {
      rows.push(...leaves(collapsed.node, prefix));
    }
  }
  rows.sort(
    (left, right) => left.label.localeCompare(right.label) || left.key.localeCompare(right.key)
  );
  groups.sort((left, right) => left.title.localeCompare(right.title));
  return { groups, rows };
}

function hoist(bucket: Bucket): Bucket {
  const groups: Group[] = [];
  for (const group of bucket.groups) {
    const inner = hoist({ groups: group.groups, rows: group.rows });
    if (inner.rows.length === 0) groups.push(...inner.groups);
    else groups.push({ groups: inner.groups, rows: inner.rows, title: group.title });
  }
  return { groups, rows: bucket.rows };
}

function collapse(node: Node, prefix: string[]): { node: Node; prefix: string[] } {
  let current = node;
  let parts = prefix;
  while (!current.value && current.children.size === 1) {
    const [name, child] = [...current.children][0];
    current = child;
    parts = [...parts, name];
  }
  return { node: current, prefix: parts };
}

function leaves(node: Node, prefix: string[]): Row[] {
  const rows = node.value ? [labeled(node.value, prefix)] : [];
  for (const child of node.children.values()) rows.push(...leaves(child, prefix));
  return rows;
}

function size(node: Node): number {
  let count = node.value ? 1 : 0;
  for (const child of node.children.values()) count += size(child);
  return count;
}

function labeled(row: Row, prefix: string[]): Row {
  const parent = prefix.join(".");
  if (parent && row.key.startsWith(`${parent}.`))
    return { ...row, label: row.key.slice(parent.length + 1) };
  if (row.key === parent) return { ...row, label: prefix.at(-1) ?? row.key };
  return { ...row, label: row.key };
}

function emptyNode(): Node {
  return { children: new Map() };
}

function renderValue(value: JsonValue): ReactNode {
  const parsed = parseIfJson(value);
  if (parsed === null) return "null";
  if (typeof parsed === "string")
    return (
      <span className="break-words whitespace-pre-wrap [overflow-wrap:anywhere]">{parsed}</span>
    );
  if (typeof parsed === "number" || typeof parsed === "boolean") return String(parsed);
  return (
    <pre className="max-w-full overflow-auto rounded-sm border border-border/70 bg-code-surface px-2.5 py-2 font-mono text-xs whitespace-pre-wrap text-code-fg [overflow-wrap:anywhere]">
      {JSON.stringify(parsed, null, 2)}
    </pre>
  );
}

function parseIfJson(value: JsonValue): JsonValue {
  if (typeof value !== "string") return value;
  const trimmed = value.trim();
  const wrapped =
    (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
    (trimmed.startsWith("[") && trimmed.endsWith("]"));
  if (!wrapped) return value;
  try {
    return JSON.parse(trimmed) as JsonValue;
  } catch {
    return value;
  }
}