Agent Tree
Who started whom: an orchestrator and its sub-agents as a tree with status, cost and time on every card, costs rolling up each branch and branches that fold into one line.
"use client"
import * as React from "react"
import { ChevronDown, Sparkles } from "lucide-react"
import {
AiKitStyles,
AiStyle,
BrandIcon,
BrandStack,
cx,
Edge,
elbowPath,
Face,
Mark,
Roll,
type AiMood,
type AiShape,
type AiStatus,
type AiTone,
} from "@/lib/ai-kit"
export interface TreeAgent {
id: string
name: string
model: string
/** Brand mark for the model's maker, e.g. "claude", "openai", "googlegemini". */
vendor?: string
/** The agent that started this one. The orchestrator has none. */
parent?: string
tone: AiTone
shape?: AiShape
status: AiStatus
task: string
tools?: readonly string[]
/** This agent's own spend in dollars, without its sub-agents. */
cost: number
/** Seconds it has been running. */
seconds: number
}
export interface AgentTreeProps {
agents: readonly TreeAgent[]
/** Ids of agents whose branch is folded into one line. */
folded?: readonly string[]
onFold?: (id: string) => void
/** Ids of agents whose spend is rolling up to their parent right now. */
rolling?: readonly string[]
title?: string
className?: string
}
const CSS = `
.aik-tree{width:min(100%,1060px);container-type:inline-size}
.aik-tree-head{display:flex;align-items:center;gap:10px;padding:0 6px 22px;font-size:15px}
.aik-tree-head b{font-weight:600;font-size:16px}
.aik-tree-head > svg{color:var(--aik-blue)}
.aik-tree-sum{margin-left:auto;display:flex;align-items:center;gap:16px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-tree-sum span:nth-child(2){color:var(--aik-blue)}
.aik-tree-sum strong{color:var(--aik-text);font-weight:600;font-size:16px}
.aik-tree-body{position:relative;display:grid;justify-items:center;gap:44px}
.aik-tree-svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none}
.aik-tree-row{display:grid;grid-template-columns:repeat(var(--n),minmax(0,1fr));gap:18px;width:100%;align-items:start}
.aik-tree-col{display:grid;gap:12px;align-content:start}
.aik-tree-kids{display:grid;padding-left:30px;transform-origin:top left;transition:opacity 240ms var(--aik-ease-out),translate 320ms var(--aik-ease-move),scale 320ms var(--aik-ease-move),display 320ms allow-discrete}
.aik-tree-kids[data-folded]{display:none;opacity:0;translate:0 -12px;scale:.97}
@starting-style{.aik-tree-kids{opacity:0;translate:0 -12px;scale:.97}}
.aik-tree-kids > div{display:grid;gap:12px;padding:2px}
.aik-tree-card{position:relative;width:100%;max-width:330px;display:grid;gap:11px;padding:14px;border-radius:16px;background:var(--aik-card);box-shadow:var(--aik-sh-card);animation:aik-tree-in 520ms var(--aik-ease-soft) both;animation-delay:calc(var(--d,0)*80ms)}
.aik-tree-card[data-root]{max-width:360px}
.aik-tree-card .aik-beam{--aik-beam-c:var(--c);animation:aik-beam 2.6s linear infinite}
.aik-tree-top{display:flex;align-items:center;gap:10px;min-width:0}
.aik-tree-id{display:grid;min-width:0;line-height:19px}
.aik-tree-id b{font-weight:600;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aik-tree-id{flex:1 1 auto}
.aik-tree-id span{display:block;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;color:var(--aik-text-3)}
.aik-tree-id span svg{display:inline-block;vertical-align:-1.5px;margin-right:5px}
.aik-tree-card{container-type:inline-size}
@container (max-width:250px){.aik-tree-st .aik-roll{display:none}.aik-tree-st{padding:0 4px}}
.aik-tree-st{margin-left:auto;display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 9px 0 5px;border-radius:9px;font-size:12.5px;font-weight:500;color:var(--aik-c,var(--aik-text-3));background:color-mix(in oklab,var(--aik-c,var(--aik-text-3)) 13%,transparent);white-space:nowrap}
.aik-tree-st .aik-mark{transform:scale(.76)}
.aik-tree-task{display:flex;align-items:flex-start;gap:8px;font-size:14.5px;line-height:20px;color:var(--aik-text)}
.aik-tree-task .aik-brand-stack{margin-top:-1px}
.aik-tree-task p{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.aik-tree-foot{display:flex;align-items:center;gap:6px;font:13px var(--aik-mono);color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-tree-foot strong{font-weight:500;color:var(--aik-text)}
.aik-tree-foot strong[data-up]{animation:aik-tree-bump 640ms var(--aik-ease-out)}
.aik-tree-fold{margin-left:auto;display:inline-flex;align-items:center;gap:3px;height:24px;padding:0 6px 0 8px;border-radius:7px;font:500 12.5px var(--aik-sans);color:var(--aik-text-2);transition:background var(--aik-d-state)}
.aik-tree-fold:hover{background:var(--aik-hover)}
.aik-tree-fold svg{transition:transform var(--aik-d-move) var(--aik-ease-out)}
.aik-tree-fold[aria-expanded="false"] svg{transform:rotate(-90deg)}
.aik-tree-line{display:flex;align-items:center;gap:8px;height:34px;padding:0 12px;margin-left:30px;border-radius:11px;font-size:13px;color:var(--aik-text-2);background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);animation:aik-tree-in 360ms var(--aik-ease-out) both}
.aik-tree-line i{display:flex}
.aik-tree-line i span{width:8px;height:8px;border-radius:3px;margin-right:-2px;background:var(--c);box-shadow:0 0 0 2px var(--aik-sunk)}
.aik-tree-line em{margin-left:auto;font:13px var(--aik-mono);font-style:normal;color:var(--aik-text)}
@keyframes aik-tree-in{from{opacity:0;transform:translateY(8px)}}
@keyframes aik-tree-bump{30%{color:var(--aik-green);transform:translateY(-2px)}}
@container (max-width:760px){
.aik-tree-row{grid-template-columns:minmax(0,1fr);gap:22px}
.aik-tree-body{justify-items:stretch;gap:22px}
.aik-tree-card,.aik-tree-card[data-root]{max-width:none}
.aik-tree-col{padding-left:26px}
.aik-tree-sum span:first-child{display:none}
}
@media (prefers-reduced-motion: reduce){.aik-tree-card,.aik-tree-line{animation:none}}
`
const MOOD: Record<AiStatus, AiMood> = {
todo: "sleep",
run: "work",
ask: "needs",
done: "happy",
fail: "oops",
}
const LABEL: Record<AiStatus, string> = {
todo: "Queued",
run: "Running",
ask: "Needs you",
done: "Done",
fail: "Failed",
}
const money = (n: number) => `$${n.toFixed(2)}`
const time = (s: number) =>
s < 60
? `${Math.round(s)}s`
: `${Math.floor(s / 60)}m ${String(Math.round(s % 60)).padStart(2, "0")}s`
/**
* Who started whom: an orchestrator and its sub-agents as a live tree. Every
* card shows its whole branch's cost, so spend rolls up the tree as a small
* light running back along the connector. A branch folds into one line.
*/
export function AgentTree({
agents,
folded = [],
onFold,
rolling = [],
title = "Agents",
className,
}: AgentTreeProps) {
const body = React.useRef<HTMLDivElement>(null)
const root = React.useRef<HTMLDivElement>(null)
const nodes = React.useRef(new Map<string, HTMLElement>())
const [edges, setEdges] = React.useState<
Array<{
id: string
d: string
back: string
tone: AiTone
port: [number, number]
}>
>([])
const byId = React.useMemo(
() => new Map(agents.map((a) => [a.id, a])),
[agents]
)
const kids = React.useCallback(
(id: string) => agents.filter((a) => a.parent === id),
[agents]
)
const branch = React.useCallback(
(id: string): number =>
(byId.get(id)?.cost ?? 0) +
kids(id).reduce((sum, k) => sum + branch(k.id), 0),
[byId, kids]
)
const top = agents.find((a) => !a.parent)
const box = (node: HTMLElement) => {
let left = 0
let topY = 0
let el: HTMLElement | null = node
while (el && el !== body.current) {
left += el.offsetLeft
topY += el.offsetTop
el = el.offsetParent as HTMLElement | null
}
return { left, top: topY, w: node.offsetWidth, h: node.offsetHeight }
}
const measure = React.useCallback(() => {
if (!body.current) return
const wide = (root.current?.clientWidth ?? 0) > 760
const out: typeof edges = []
for (const agent of agents) {
if (!agent.parent) continue
const from = nodes.current.get(agent.parent)
const to = nodes.current.get(agent.id)
if (!from || !to || to.offsetParent === null) continue
if (to.closest(".aik-tree-kids")?.hasAttribute("data-folded")) continue
const f = box(from)
const t = box(to)
const level1 = !byId.get(agent.parent)?.parent
if (level1 && wide) {
const ax = f.left + f.w / 2
const ay = f.top + f.h
const bx = t.left + t.w / 2
const by = t.top
out.push({
id: agent.id,
d: elbowPath(ax, ay, bx, by, "v", 12),
back: elbowPath(bx, by, ax, ay, "v", 12),
tone: agent.tone,
port: [ax, ay],
})
} else {
const ax = f.left + (level1 ? 10 : 20)
const ay = f.top + f.h
const bx = t.left
const by = t.top + Math.min(t.h / 2, 32)
out.push({
id: agent.id,
d: `M${ax} ${ay}V${by - 10}Q${ax} ${by} ${ax + 10} ${by}H${bx}`,
back: `M${bx} ${by}H${ax + 10}Q${ax} ${by} ${ax} ${by - 10}V${ay}`,
tone: agent.tone,
port: [ax, ay],
})
}
}
setEdges(out)
}, [agents, byId])
React.useLayoutEffect(() => {
measure()
const observer = new ResizeObserver(() => measure())
if (root.current) observer.observe(root.current)
nodes.current.forEach((n) => observer.observe(n))
let frame = 0
const until = performance.now() + 560
const follow = () => {
measure()
if (performance.now() < until) frame = requestAnimationFrame(follow)
}
frame = requestAnimationFrame(follow)
return () => {
observer.disconnect()
cancelAnimationFrame(frame)
}
}, [measure, folded])
// Remember each card's branch cost so a rise can flash.
const last = React.useRef(new Map<string, number>())
const rose = new Set<string>()
for (const agent of agents) {
const now = branch(agent.id)
const before = last.current.get(agent.id)
if (before !== undefined && now > before + 0.0001) rose.add(agent.id)
}
React.useEffect(() => {
agents.forEach((a) => last.current.set(a.id, branch(a.id)))
})
if (!top) return null
const running = agents.filter((a) => a.status === "run").length
const register = (id: string) => (node: HTMLElement | null) => {
if (node) nodes.current.set(id, node)
else nodes.current.delete(id)
}
const card = (agent: TreeAgent, depth: number): React.ReactNode => {
const children = kids(agent.id)
const isFolded = folded.includes(agent.id)
const statusTone =
agent.status === "run"
? "var(--aik-blue)"
: agent.status === "ask"
? "var(--aik-amber)"
: agent.status === "done"
? "var(--aik-green)"
: agent.status === "fail"
? "var(--aik-red)"
: undefined
return (
<div
ref={register(agent.id)}
className="aik-tree-card"
data-root={depth === 0 ? "" : undefined}
style={
{
"--c": `var(--aik-f-${agent.tone})`,
"--d": depth,
} as React.CSSProperties
}
>
<span
className="aik-beam"
data-on={agent.status === "run" && depth < 2 ? "" : undefined}
/>
<div className="aik-tree-top">
<Face
mood={MOOD[agent.status]}
shape={agent.shape ?? "squircle"}
tone={agent.tone}
size={depth === 0 ? 38 : 32}
/>
<span className="aik-tree-id">
<b>{agent.name}</b>
<span>
{agent.vendor ? (
<BrandIcon name={agent.vendor} tint="brand" size={12} />
) : null}
{agent.model}
</span>
</span>
<span
className="aik-tree-st"
style={
statusTone
? ({ "--aik-c": statusTone } as React.CSSProperties)
: undefined
}
>
<Mark status={agent.status} />
<Roll>{LABEL[agent.status]}</Roll>
</span>
</div>
<div className="aik-tree-task">
{agent.tools?.length ? (
<BrandStack names={agent.tools} size={20} />
) : null}
<p>{agent.task}</p>
</div>
<div className="aik-tree-foot">
<strong
key={rose.has(agent.id) ? `u${branch(agent.id)}` : "s"}
data-up={rose.has(agent.id) ? "" : undefined}
>
{money(branch(agent.id))}
</strong>
<span>·</span>
<Roll>{time(agent.seconds)}</Roll>
{children.length && onFold ? (
<button
type="button"
className="aik-tree-fold"
aria-expanded={!isFolded}
aria-label={`${isFolded ? "Unfold" : "Fold"} ${agent.name}'s ${children.length} sub-agents`}
onClick={() => onFold(agent.id)}
>
{children.length}
<ChevronDown size={14} aria-hidden="true" />
</button>
) : null}
</div>
</div>
)
}
const descendants = (id: string): TreeAgent[] =>
kids(id).flatMap((k) => [k, ...descendants(k.id)])
const nest = (agent: TreeAgent, depth: number): React.ReactNode => {
const children = kids(agent.id)
const isFolded = folded.includes(agent.id)
const all = descendants(agent.id)
return (
<React.Fragment key={agent.id}>
{card(agent, depth)}
{children.length ? (
<>
<div
className="aik-tree-kids"
data-folded={isFolded ? "" : undefined}
>
<div>
{children.map((child) => (
<div key={child.id} className="aik-tree-col">
{nest(child, depth + 1)}
</div>
))}
</div>
</div>
{isFolded ? (
<div className="aik-tree-line">
<i aria-hidden="true">
{all.slice(0, 4).map((a) => (
<span
key={a.id}
style={
{
"--c": `var(--aik-f-${a.tone})`,
} as React.CSSProperties
}
/>
))}
</i>
{all.length} sub-agent{all.length === 1 ? "" : "s"} ·{" "}
{all.filter((a) => a.status === "run").length} running
<em>{money(all.reduce((s, a) => s + a.cost, 0))}</em>
</div>
) : null}
</>
) : null}
</React.Fragment>
)
}
const team = kids(top.id)
return (
<div ref={root} className={cx("aik aik-tree", className)}>
<AiKitStyles />
<AiStyle id="agent-tree" css={CSS} />
<div className="aik-tree-head">
<Sparkles size={17} aria-hidden="true" />
<b>{title}</b>
<span className="aik-tree-sum">
<span>{agents.length} agents</span>
<span>
<Roll>{`${running} running`}</Roll>
</span>
<strong>
<Roll>{money(branch(top.id))}</Roll>
</strong>
</span>
</div>
<div ref={body} className="aik-tree-body">
<svg className="aik-tree-svg" aria-hidden="true">
{edges.map((edge) => {
const child = byId.get(edge.id)
const on = child && child.status !== "todo"
return (
<g key={edge.id}>
<Edge
d={edge.d}
tone={edge.tone}
state={on ? "done" : "idle"}
/>
{rolling.includes(edge.id) ? (
<Edge
d={edge.back}
tone="green"
state="live"
duration={0.9}
width={1.25}
/>
) : null}
<circle
cx={edge.port[0]}
cy={edge.port[1]}
r={3.5}
fill="var(--aik-bg)"
strokeWidth={1.5}
stroke={
on ? `var(--aik-f-${edge.tone})` : "var(--aik-line-3)"
}
/>
</g>
)
})}
</svg>
{card(top, 0)}
{!folded.includes(top.id) ? (
<div
className="aik-tree-row"
style={{ "--n": team.length } as React.CSSProperties}
>
{team.map((member) => (
<div key={member.id} className="aik-tree-col">
{nest(member, 1)}
</div>
))}
</div>
) : null}
</div>
</div>
)
}
Installation
One command adds agent-tree 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-tree.json