Agent Flame Graph
A multi-agent call stack as a flame graph: orchestrator on top, sub-agents, model calls and tools beneath, every block as wide as it took. Switch between time, tokens and cost, and click to zoom.
"use client"
import * as React from "react"
import { ChevronRight, Play, Search, Terminal } from "lucide-react"
import {
AgentGlyph,
AiKitStyles,
AiStyle,
BrandIcon,
cx,
Roll,
type AiTone,
} from "@/lib/ai-kit"
export type FlameMetric = "time" | "tokens" | "cost"
export interface FlameNode {
id: string
name: string
/** Agents carry a tone and a pixel mark; model and tool calls a brand mark. */
kind: "agent" | "llm" | "tool"
tone?: AiTone
brand?: string
/** Seconds, tokens and dollars spent in this block and everything under it. */
time: number
tokens: number
cost: number
status?: "run" | "done" | "fail"
children?: readonly FlameNode[]
}
export interface AgentFlameGraphProps {
title: string
root: FlameNode
metric?: FlameMetric
onMetric?: (metric: FlameMetric) => void
/** Id of the block the view is zoomed into. */
zoom?: string
onZoom?: (id: string) => void
query?: string
onQuery?: (query: string) => void
live?: boolean
className?: string
}
const ROW = 38
const GAP = 5
const CSS = `
.aik-fg{width:min(100%,1060px);container-type:inline-size}
.aik-fg-card{--aik-r-shell:24px;--aik-rim:5px}
.aik-fg-head{display:flex;align-items:center;gap:16px;padding:20px 22px 18px;border-bottom:1px solid var(--aik-line)}
.aik-fg-head > div:first-child{display:grid;gap:3px;margin-right:auto}
.aik-fg-title{display:flex;align-items:center;gap:10px;font-weight:600;font-size:16px}
.aik-fg-live{display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 9px;border-radius:7px;font-size:13px;font-weight:500;color:var(--aik-blue);background:color-mix(in oklab,var(--aik-blue) 15%,transparent)}
.aik-fg-live i{width:6px;height:6px;border-radius:50%;background:currentColor;animation:aik-fg-blink 1.4s ease-in-out infinite}
.aik-fg-sub{font-size:14.5px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-fg-seg{position:relative;display:inline-grid;grid-template-columns:repeat(3,1fr);padding:3px;border-radius:12px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line)}
.aik-fg-seg button{position:relative;z-index:1;height:32px;padding:0 16px;border-radius:9px;font-size:14px;font-weight:500;color:var(--aik-text-3);transition:color var(--aik-d-state)}
.aik-fg-seg button[aria-pressed="true"]{color:var(--aik-text)}
.aik-fg-seg span{position:absolute;top:3px;bottom:3px;left:3px;width:calc((100% - 6px)/3);border-radius:9px;background:var(--aik-card);box-shadow:var(--aik-sh-card);transition:translate var(--aik-d-move) var(--aik-ease-move)}
.aik-fg-bar{display:flex;align-items:center;gap:12px;padding:14px 22px}
.aik-fg-crumbs{display:flex;align-items:center;gap:4px;min-width:0;font-size:14.5px;color:var(--aik-text-3)}
.aik-fg-crumbs button{height:28px;padding:0 6px;border-radius:7px;font-weight:500;color:var(--aik-text-2);white-space:nowrap}
.aik-fg-crumbs button:last-of-type{color:var(--aik-text)}
.aik-fg-crumbs button:hover{background:var(--aik-hover)}
.aik-fg-crumbs em{font-style:normal;margin-left:8px;white-space:nowrap}
.aik-fg-search{margin-left:auto;display:flex;align-items:center;gap:8px;width:260px;height:38px;padding:0 12px;border-radius:11px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);color:var(--aik-text-3);transition:box-shadow var(--aik-d-state)}
.aik-fg-search:focus-within{box-shadow:inset 0 0 0 1px var(--aik-blue),0 0 0 3px color-mix(in oklab,var(--aik-blue) 18%,transparent)}
.aik-fg-search input{flex:1;min-width:0;background:none;border:0;outline:0;font-size:14.5px;color:var(--aik-text)}
.aik-fg-axis{position:relative;height:30px;margin:0 22px;border-bottom:1px solid var(--aik-line)}
.aik-fg-axis span{position:absolute;bottom:7px;font:12.5px var(--aik-mono);color:var(--aik-text-3);translate:4px 0;white-space:nowrap}
.aik-fg-axis span::before{content:"";position:absolute;left:-4px;top:-4px;height:30px;width:1px;background:var(--aik-line)}
.aik-fg-plot{position:relative;container-type:inline-size;margin:10px 22px 20px;transition:height var(--aik-d-move) var(--aik-ease-move)}
.aik-fg-b{position:absolute;height:${ROW}px;display:flex;align-items:center;gap:7px;padding:0 9px;border-radius:9px;overflow:hidden;white-space:nowrap;font-size:14px;font-weight:500;cursor:pointer;text-align:left;
color:color-mix(in oklab,var(--c) 55%,var(--aik-text));background:color-mix(in oklab,var(--c) var(--mix,18%),var(--aik-card));box-shadow:inset 0 0 0 1px color-mix(in oklab,var(--c) 30%,transparent);
left:0;top:0;transition:transform 560ms var(--aik-ease-move),width 560ms var(--aik-ease-move),opacity 320ms,background var(--aik-d-state),box-shadow var(--aik-d-state)}
.aik-fg-b[data-k="llm"]{--mix:11%}
.aik-fg-b[data-k="tool"]{--mix:7%;color:var(--aik-text-2)}
.aik-fg-b[data-s="fail"]{--c:var(--aik-red);--mix:18%;color:var(--aik-red)}
.aik-fg-b:hover{box-shadow:inset 0 0 0 1.5px color-mix(in oklab,var(--c) 70%,transparent)}
.aik-fg-b[data-dim]{opacity:.22}
.aik-fg-b[data-hit]{box-shadow:inset 0 0 0 1.5px var(--c),0 0 16px -4px var(--c)}
.aik-fg-b[data-out]{opacity:0;pointer-events:none}
.aik-fg-b[data-s="run"]::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,color-mix(in oklab,var(--c) 30%,transparent),transparent);translate:-100% 0;animation:aik-fg-sheen 2.2s var(--aik-ease-move) infinite}
.aik-fg-b > span{overflow:hidden;text-overflow:ellipsis;min-width:0}
.aik-fg-b > em{margin-left:auto;font:12.5px var(--aik-mono);font-style:normal;opacity:.85;padding-left:6px}
.aik-fg-b[data-narrow] > span,.aik-fg-b[data-narrow] > em{display:none}
.aik-fg-b[data-tiny] > *{display:none}
.aik-fg-b[data-tiny]{padding:0}
.aik-fg-tip{position:absolute;z-index:3;translate:-50% calc(-100% - 10px);min-width:190px;padding:11px 13px;border-radius:12px;background:var(--aik-card);box-shadow:var(--aik-sh-pop);font-size:13.5px;pointer-events:none;animation:aik-fg-tip 180ms var(--aik-ease-out) both}
.aik-fg-tip b{display:block;font-weight:600;font-size:14.5px;margin-bottom:6px}
.aik-fg-tip div{display:flex;justify-content:space-between;gap:18px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-fg-tip div span:last-child{color:var(--aik-text);font-family:var(--aik-mono);font-size:12.5px}
@keyframes aik-fg-blink{50%{opacity:.3}}
@keyframes aik-fg-sheen{65%,100%{translate:100% 0}}
@keyframes aik-fg-tip{from{opacity:0;translate:-50% calc(-100% - 4px)}}
@container (max-width:640px){
.aik-fg-head{flex-wrap:wrap;padding:16px}
.aik-fg-seg{width:100%}
.aik-fg-bar{flex-wrap:wrap;padding:12px 16px}
.aik-fg-search{width:100%;margin:0}
.aik-fg-axis,.aik-fg-plot{margin-left:12px;margin-right:12px}
.aik-fg-axis span:nth-child(even){display:none}
}
@media (prefers-reduced-motion:reduce){.aik-fg-b::after,.aik-fg-live i{animation:none}}
`
interface Box {
node: FlameNode
depth: number
x: number
w: number
tone: AiTone
path: string[]
}
function fmtTime(s: number) {
if (s < 60) return `${Math.round(s)}s`
return `${Math.floor(s / 60)}m ${String(Math.round(s % 60)).padStart(2, "0")}s`
}
function fmtTokens(n: number) {
return n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}K` : String(n)
}
function fmtCost(n: number) {
return `$${n < 0.1 ? n.toFixed(3) : n.toFixed(2)}`
}
const FORMAT: Record<FlameMetric, (n: number) => string> = {
time: fmtTime,
tokens: fmtTokens,
cost: fmtCost,
}
/**
* A multi-agent run's call stack as a flame graph: orchestrator on top, then
* sub-agents and their model and tool calls, each block as wide as the time,
* tokens or money it took. Switch the measure and every block glides to its
* new width; click a block to zoom into it, search to light up matches.
*/
export function AgentFlameGraph({
title,
root,
metric = "time",
onMetric,
zoom,
onZoom,
query = "",
onQuery,
live = false,
className,
}: AgentFlameGraphProps) {
const [hover, setHover] = React.useState<string | null>(null)
// The plot's real width, so labels and icons hide by the pixels a block
// actually has (a phone gets a third of a desktop's room).
const plotRef = React.useRef<HTMLDivElement>(null)
const [plotPx, setPlotPx] = React.useState(1000)
React.useLayoutEffect(() => {
const node = plotRef.current
if (!node) return
const sync = () => setPlotPx(node.clientWidth || 1000)
sync()
const observer = new ResizeObserver(sync)
observer.observe(node)
return () => observer.disconnect()
}, [])
const boxes = React.useMemo(() => {
const out: Box[] = []
const walk = (
node: FlameNode,
depth: number,
x: number,
w: number,
tone: AiTone,
path: string[]
) => {
const t = node.tone ?? tone
out.push({ node, depth, x, w, tone: t, path })
const kids = node.children ?? []
const sum = kids.reduce((a, k) => a + k[metric], 0)
const total = Math.max(node[metric], sum)
let cx = x
for (const kid of kids) {
const kw = total ? (kid[metric] / total) * w : 0
walk(kid, depth + 1, cx, kw, t, [...path, node.id])
cx += kw
}
}
walk(root, 0, 0, 1, root.tone ?? "blue", [])
return out
}, [root, metric])
const focus = boxes.find((b) => b.node.id === zoom) ?? boxes[0]
const maxDepth = Math.max(
...boxes
.filter((b) => b.path.includes(focus.node.id) || b === focus)
.map((b) => b.depth)
)
const rows = maxDepth - focus.depth + 1
const q = query.trim().toLowerCase()
const match = (b: Box) =>
!!q &&
(b.node.name.toLowerCase().includes(q) || (b.node.brand ?? "").includes(q))
const crumbs = [...focus.path, focus.node.id].map(
(id) => boxes.find((b) => b.node.id === id)!
)
const hovered = boxes.find((b) => b.node.id === hover)
const plotW = 100
const sx = (x: number) => ((x - focus.x) / focus.w) * plotW
const ticks = [0, 0.25, 0.5, 0.75]
return (
<div className={cx("aik aik-fg", className)}>
<AiKitStyles />
<AiStyle id="agent-flame-graph" css={CSS} />
<div className="aik-shell aik-fg-card">
<div className="aik-surface">
<div className="aik-fg-head">
<div>
<span className="aik-fg-title">
{title}
{live ? (
<span className="aik-fg-live">
<i /> Live
</span>
) : null}
</span>
<span className="aik-fg-sub">
{fmtTime(root.time)} · {fmtTokens(root.tokens)} tokens ·{" "}
{fmtCost(root.cost)}
</span>
</div>
<div className="aik-fg-seg" role="group" aria-label="Measure">
<span
style={{
translate: `${["time", "tokens", "cost"].indexOf(metric) * 100}% 0`,
}}
aria-hidden="true"
/>
{(["time", "tokens", "cost"] as const).map((m) => (
<button
key={m}
type="button"
aria-pressed={metric === m}
onClick={() => onMetric?.(m)}
>
{m === "time" ? "Time" : m === "tokens" ? "Tokens" : "Cost"}
</button>
))}
</div>
</div>
<div className="aik-fg-bar">
<nav className="aik-fg-crumbs" aria-label="Zoom">
<Play size={13} aria-hidden="true" />
{crumbs.map((b, i) => (
<React.Fragment key={b.node.id}>
{i ? <ChevronRight size={14} aria-hidden="true" /> : null}
<button type="button" onClick={() => onZoom?.(b.node.id)}>
{i === 0 ? "Run" : b.node.name}
</button>
</React.Fragment>
))}
<em>
{focus === boxes[0] ? (
"Click a block to zoom in"
) : (
<Roll>{FORMAT[metric](focus.node[metric])}</Roll>
)}
</em>
</nav>
<label className="aik-fg-search">
<Search size={16} aria-hidden="true" />
<input
value={query}
placeholder="Search"
aria-label="Search blocks"
onChange={(e) => onQuery?.(e.target.value)}
/>
</label>
</div>
<div className="aik-fg-axis" aria-hidden="true">
{ticks.map((t) => (
<span key={t} style={{ left: `${t * 100}%` }}>
{t === 0 ? "0" : FORMAT[metric](focus.node[metric] * t)}
</span>
))}
</div>
<div
ref={plotRef}
className="aik-fg-plot"
style={{ height: rows * (ROW + GAP) }}
onPointerLeave={() => setHover(null)}
>
{boxes.map((b) => {
const inside = b === focus || b.path.includes(focus.node.id)
const left = sx(b.x)
const width = (b.w / focus.w) * plotW
const px = (width / 100) * plotPx
const hit = match(b)
return (
<button
key={b.node.id}
type="button"
className="aik-fg-b"
data-k={b.node.kind}
data-s={b.node.status}
data-out={inside ? undefined : ""}
data-hit={hit ? "" : undefined}
data-dim={q && !hit ? "" : undefined}
data-narrow={px < 74 ? "" : undefined}
data-tiny={px < 30 ? "" : undefined}
tabIndex={inside ? 0 : -1}
aria-label={`${b.node.name}, ${FORMAT[metric](b.node[metric])}`}
style={
{
// Position rides a transform (container units of the
// plot); only the width eases with layout, since a block
// label must not stretch while it resizes.
transform: `translate(calc(${left}cqw + 1px), ${(b.depth - focus.depth) * (ROW + GAP)}px)`,
width: `max(0px, calc(${width}cqw - 3px))`,
"--c": `var(--aik-f-${b.tone})`,
} as React.CSSProperties
}
onClick={() =>
onZoom?.(
b === focus && b.path.length ? b.path.at(-1)! : b.node.id
)
}
onPointerEnter={() => setHover(b.node.id)}
onFocus={() => setHover(b.node.id)}
onBlur={() => setHover(null)}
>
{b.node.kind === "agent" ? (
<AgentGlyph
seed={b.node.id}
tone={b.tone}
size={15}
live={b.node.status === "run"}
/>
) : b.node.brand ? (
<BrandIcon name={b.node.brand} tint="brand" size={14} />
) : (
<Terminal size={14} aria-hidden="true" />
)}
<span>{b.node.name}</span>
{b.node.kind === "agent" ? (
<em>{FORMAT[metric](b.node[metric])}</em>
) : null}
</button>
)
})}
{hovered &&
(hovered === focus || hovered.path.includes(focus.node.id)) ? (
<div
className="aik-fg-tip"
style={{
left: `${Math.min(88, Math.max(12, sx(hovered.x) + ((hovered.w / focus.w) * plotW) / 2))}%`,
top: (hovered.depth - focus.depth) * (ROW + GAP),
}}
>
<b>{hovered.node.name}</b>
<div>
<span>Time</span>
<span>{fmtTime(hovered.node.time)}</span>
</div>
<div>
<span>Tokens</span>
<span>{fmtTokens(hovered.node.tokens)}</span>
</div>
<div>
<span>Cost</span>
<span>{fmtCost(hovered.node.cost)}</span>
</div>
</div>
) : null}
</div>
</div>
</div>
</div>
)
}
Installation
One command adds agent-flame-graph and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.
$npx shadcn@latest add https://tweenui.dev/r/agent-flame-graph.json