Agent Fleet
Several lead agents side by side, each card summing up its sub-agents. Click one and its tree opens to the right while the previous one folds back into its card.
"use client"
import * as React from "react"
import { Clock3, Sparkles } from "lucide-react"
import {
AiKitStyles,
AiStyle,
BrandIcon,
BrandStack,
BrandTile,
cx,
Edge,
elbowPath,
Face,
Mark,
Roll,
type AiMood,
type AiShape,
type AiStatus,
type AiTone,
} from "@/lib/ai-kit"
export interface FleetSub {
id: string
name: string
model: string
vendor: string
status: AiStatus
task: string
tools?: readonly string[]
cost: number
seconds: number
tasks?: number
/** One more level: agents this sub-agent started. */
children?: readonly FleetSub[]
}
export interface FleetLead {
id: string
name: string
model: string
vendor: string
tone: AiTone
shape?: AiShape
status: AiStatus
task: string
tools?: readonly string[]
cost: number
seconds: number
subs: readonly FleetSub[]
}
export interface AgentFleetProps {
leads: readonly FleetLead[]
/** The lead whose tree is open on the right. */
open: string
onOpen?: (id: string) => void
/** Called when you answer a sub-agent that needs you. */
onAnswer?: (leadId: string, subId: string) => void
className?: string
}
const CSS = `
.aik-fl{width:min(100%,1080px);container-type:inline-size}
.aik-fl-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:0 4px 20px;font-size:14.5px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-fl-head b{display:flex;align-items:center;gap:9px;margin-right:auto;font-size:16px;font-weight:600;color:var(--aik-text)}
.aik-fl-head b svg{color:var(--aik-blue)}
.aik-fl-head .run{color:var(--aik-blue)}.aik-fl-head .ask{color:var(--aik-amber)}
.aik-fl-head strong{color:var(--aik-text);font-weight:600}
.aik-fl-grid{position:relative;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,.92fr);gap:0 92px;align-items:start}
.aik-fl-svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none}
.aik-fl-list,.aik-fl-panel{display:grid;gap:12px;align-content:start}
.aik-fl-panel{will-change:translate}
.aik-fl-lead{position:relative;display:grid;gap:12px;width:100%;padding:15px 16px 14px;border-radius:18px;text-align:left;background:var(--aik-card);box-shadow:var(--aik-sh-card);transition:opacity var(--aik-d-panel),box-shadow var(--aik-d-panel),transform var(--aik-d-press)}
.aik-fl-lead:not([data-open]){opacity:.5}
.aik-fl-lead:not([data-open]):hover{opacity:.85}
.aik-fl-lead[data-open]{box-shadow:0 0 0 1px color-mix(in oklab,var(--c) 55%,transparent),0 12px 30px -16px color-mix(in oklab,var(--c) 60%,transparent)}
.aik-fl-lead[data-eat]{animation:aik-fl-eat 420ms var(--aik-ease-out)}
.aik-fl-lead:active{transform:scale(.99)}
.aik-fl-row{display:flex;align-items:center;gap:11px;min-width:0}
.aik-fl-id{display:grid;min-width:0;line-height:19px}
.aik-fl-id b{font-size:15.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aik-fl-id span{display:flex;align-items:center;gap:5px;font-size:13px;color:var(--aik-text-3)}
.aik-fl-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(--k);background:color-mix(in oklab,var(--k) 13%,transparent);white-space:nowrap}
.aik-fl-st .aik-mark{transform:scale(.76)}
.aik-fl-task{display:flex;align-items:center;gap:9px;min-width:0;font-size:14.5px}
.aik-fl-task span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-fl-foot{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-fl-foot svg{flex:none}
.aik-fl-foot .m{margin-left:auto;font-family:var(--aik-mono)}
.aik-fl-foot .m strong{color:var(--aik-text);font-weight:500}
.aik-fl-sub{position:relative;display:grid;gap:11px;padding:14px 15px 13px;border-radius:16px;background:var(--aik-card);box-shadow:var(--aik-sh-card);animation:aik-fl-in 460ms var(--aik-ease-soft) both;animation-delay:calc(var(--i)*70ms + 80ms);transform-origin:left center}
.aik-fl-sub[data-s="ask"]{box-shadow:0 0 0 1px color-mix(in oklab,var(--aik-amber) 50%,transparent)}
.aik-fl-sub .aik-beam{animation:aik-beam 2.6s linear infinite}
.aik-fl-panel[data-leaving] .aik-fl-sub{animation:aik-fl-out 300ms var(--aik-ease-in) both;animation-delay:calc(var(--i)*30ms)}
.aik-fl-nest{display:grid;gap:10px;padding-left:28px}
.aik-fl-answer{margin-left:auto}
@keyframes aik-fl-in{from{opacity:0;transform:translateX(-26px) scale(.96)}}
@keyframes aik-fl-out{to{opacity:0;transform:translateX(-60px) scale(.88)}}
@keyframes aik-fl-eat{40%{transform:scale(1.015)}}
@container (max-width:720px){
.aik-fl-grid{grid-template-columns:minmax(0,1fr);gap:12px}
.aik-fl-panel{padding-left:28px}
.aik-fl-head > span:nth-of-type(1){display:none}
}
@media (prefers-reduced-motion: reduce){.aik-fl-sub,.aik-fl-lead{animation:none!important}}
`
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 KEY: Record<AiStatus, string> = {
todo: "var(--aik-text-3)",
run: "var(--aik-blue)",
ask: "var(--aik-amber)",
done: "var(--aik-green)",
fail: "var(--aik-red)",
}
const money = (n: number) => `$${n.toFixed(2)}`
const clock = (s: number) =>
`${Math.floor(s / 60)}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`
const flat = (subs: readonly FleetSub[]): FleetSub[] =>
subs.flatMap((s) => [s, ...flat(s.children ?? [])])
function State({ status }: { status: AiStatus }) {
return (
<span
className="aik-fl-st"
style={{ "--k": KEY[status] } as React.CSSProperties}
>
<Mark status={status} />
<Roll>{LABEL[status]}</Roll>
</span>
)
}
/**
* Several lead agents side by side. Each card sums up its sub-agents; opening
* one folds the previous tree back into its card and unfolds the new one to
* the right, joined by a trunk in the lead's colour.
*/
export function AgentFleet({
leads,
open,
onOpen,
onAnswer,
className,
}: AgentFleetProps) {
const root = React.useRef<HTMLDivElement>(null)
const grid = React.useRef<HTMLDivElement>(null)
const nodes = React.useRef(new Map<string, HTMLElement>())
const [shown, setShown] = React.useState(open)
const [leaving, setLeaving] = React.useState(false)
const [narrow, setNarrow] = React.useState(false)
// How far the open tree slides down to sit level with its lead.
const [shift, setShift] = React.useState(0)
// The panel's drawn offset. It glides toward `shift` with requestAnimationFrame
// as a translate (no layout animation), and the connectors read the same value.
const drawn = React.useRef(0)
const panelRef = React.useRef<HTMLDivElement>(null)
const [edges, setEdges] = React.useState<
Array<{ id: string; d: string; port: [number, number]; live: boolean }>
>([])
// Fold the old tree back, then unfold the new one.
React.useEffect(() => {
if (open === shown) return
setLeaving(true)
const id = window.setTimeout(() => {
setShown(open)
setLeaving(false)
}, 340)
return () => window.clearTimeout(id)
}, [open, shown])
const lead = leads.find((l) => l.id === shown) ?? leads[0]
const box = (node: HTMLElement) => {
let x = 0
let y = 0
let el: HTMLElement | null = node
while (el && el !== grid.current) {
x += el.offsetLeft
y += el.offsetTop
el = el.offsetParent as HTMLElement | null
}
return { x, y, w: node.offsetWidth, h: node.offsetHeight }
}
const measure = React.useCallback(() => {
const width = root.current?.clientWidth ?? 0
const isNarrow = width <= 720
setNarrow(isNarrow)
const from = lead && nodes.current.get(`lead:${lead.id}`)
if (!from || !grid.current) return setEdges([])
const f = box(from)
const panelEl = panelRef.current
if (panelEl && !isNarrow) {
const listH = from.parentElement?.offsetHeight ?? 0
const own = panelEl.offsetHeight
const want = Math.max(0, Math.min(listH - own, f.y + f.h / 2 - own / 2))
setShift((s) => (Math.abs(s - want) > 1 ? want : s))
} else setShift(0)
const out: typeof edges = []
const link = (
sub: FleetSub,
parent: { x: number; y: number; w: number; h: number },
top: boolean
) => {
const to = nodes.current.get(`sub:${sub.id}`)
if (!to) return
const raw = box(to)
const t = isNarrow ? raw : { ...raw, y: raw.y + drawn.current }
let d: string
let port: [number, number]
if (top && !isNarrow) {
port = [parent.x + parent.w, parent.y + parent.h / 2]
d = elbowPath(
port[0],
port[1],
t.x,
t.y + Math.min(t.h / 2, 36),
"h",
12
)
} else {
port = [parent.x + 14, parent.y + parent.h]
const by = t.y + Math.min(t.h / 2, 30)
d = `M${port[0]} ${port[1]}V${by - 10}Q${port[0]} ${by} ${port[0] + 10} ${by}H${t.x}`
}
out.push({ id: sub.id, d, port, live: sub.status === "run" })
sub.children?.forEach((c) => link(c, t, false))
}
lead.subs.forEach((s) => link(s, f, true))
setEdges(out)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lead, leads])
React.useLayoutEffect(() => {
measure()
const ro = new ResizeObserver(() => measure())
if (root.current) ro.observe(root.current)
nodes.current.forEach((n) => ro.observe(n))
// The panel glides to its new height: follow it with the lines.
let frame = 0
const until = performance.now() + 560
const follow = () => {
measure()
if (performance.now() < until) frame = requestAnimationFrame(follow)
}
frame = requestAnimationFrame(follow)
return () => {
ro.disconnect()
cancelAnimationFrame(frame)
}
}, [measure, shown, narrow, shift])
// A freshly mounted panel starts at the current drawn offset.
React.useLayoutEffect(() => {
if (panelRef.current)
panelRef.current.style.translate = `0 ${narrow ? 0 : drawn.current}px`
}, [lead?.id, narrow])
// Glide the panel to its target offset; the connectors follow every frame.
React.useEffect(() => {
const target = narrow ? 0 : shift
const from = drawn.current
if (Math.abs(target - from) < 0.5) return
const start = performance.now()
const dur = 460
let frame = 0
const step = (now: number) => {
const k = Math.min(1, (now - start) / dur)
const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2
drawn.current = from + (target - from) * e
if (panelRef.current)
panelRef.current.style.translate = `0 ${drawn.current}px`
measure()
if (k < 1) frame = requestAnimationFrame(step)
}
frame = requestAnimationFrame(step)
return () => cancelAnimationFrame(frame)
}, [shift, narrow, measure])
const register = (key: string) => (node: HTMLElement | null) => {
if (node) nodes.current.set(key, node)
else nodes.current.delete(key)
}
const all = leads.flatMap((l) => flat(l.subs))
const running =
all.filter((s) => s.status === "run").length +
leads.filter((l) => l.status === "run").length
const asking = all.filter((s) => s.status === "ask").length
const spend = leads.reduce(
(sum, l) => sum + l.cost + flat(l.subs).reduce((a, s) => a + s.cost, 0),
0
)
const subCard = (sub: FleetSub, i: number): React.ReactNode => (
<React.Fragment key={sub.id}>
<div
ref={register(`sub:${sub.id}`)}
className="aik-fl-sub"
data-s={sub.status}
style={
{
"--i": i,
"--aik-beam-c": `var(--aik-f-${lead.tone})`,
} as React.CSSProperties
}
>
<span
className="aik-beam"
data-on={sub.status === "run" ? "" : undefined}
/>
<div className="aik-fl-row">
<BrandTile name={sub.vendor} size={34} />
<span className="aik-fl-id">
<b>{sub.name}</b>
<span>{sub.model}</span>
</span>
<State status={sub.status} />
</div>
<div className="aik-fl-task">
{sub.tools?.length ? (
<BrandStack names={sub.tools} size={20} />
) : null}
<span>{sub.task}</span>
</div>
<div className="aik-fl-foot">
<span className="m" style={{ marginLeft: 0 }}>
<strong>{money(sub.cost)}</strong> ·{" "}
<Roll>{clock(sub.seconds)}</Roll>
</span>
{sub.status === "ask" && onAnswer ? (
<button
type="button"
className="aik-btn line sm aik-fl-answer"
onClick={() => onAnswer(lead.id, sub.id)}
>
Answer
</button>
) : sub.tasks ? (
<span style={{ marginLeft: "auto" }}>{sub.tasks} tasks</span>
) : null}
</div>
</div>
{sub.children?.length ? (
<div className="aik-fl-nest">
{sub.children.map((c, k) => subCard(c, i + k + 1))}
</div>
) : null}
</React.Fragment>
)
const panel = lead ? (
<div
key={lead.id}
ref={panelRef}
className="aik-fl-panel"
data-leaving={leaving ? "" : undefined}
>
{lead.subs.map((s, i) => subCard(s, i))}
</div>
) : null
return (
<div ref={root} className={cx("aik aik-fl", className)}>
<AiKitStyles />
<AiStyle id="agent-fleet" css={CSS} />
<div className="aik-fl-head">
<b>
<Sparkles size={17} aria-hidden="true" />
Fleet
</b>
<span>
{leads.length} agents / {all.length} sub-agents
</span>
<span className="run">
<Roll>{`${running} running`}</Roll>
</span>
{asking ? (
<span className="ask">
<Roll>{`${asking} needs you`}</Roll>
</span>
) : null}
<strong>
<Roll>{money(spend)}</Roll>
</strong>
</div>
<div ref={grid} className="aik-fl-grid">
<svg
className="aik-fl-svg"
aria-hidden="true"
style={{ opacity: leaving ? 0 : 1, transition: "opacity 200ms" }}
>
{edges.map((e) => (
<g key={e.id}>
<Edge
d={e.d}
tone={lead.tone}
state={e.live ? "live" : "done"}
duration={1.3}
/>
<circle
cx={e.port[0]}
cy={e.port[1]}
r={4}
fill="var(--aik-bg)"
stroke={`var(--aik-f-${lead.tone})`}
strokeWidth={1.5}
/>
</g>
))}
</svg>
<div className="aik-fl-list" role="tablist" aria-label="Lead agents">
{leads.map((l) => {
const subs = flat(l.subs)
const ask = subs.filter((s) => s.status === "ask").length
const fail = subs.filter((s) => s.status === "fail").length
const run = subs.filter((s) => s.status === "run").length
const total = l.cost + subs.reduce((a, s) => a + s.cost, 0)
return (
<React.Fragment key={l.id}>
<button
type="button"
role="tab"
aria-selected={l.id === open}
ref={register(`lead:${l.id}`)}
className="aik-fl-lead"
data-open={l.id === open ? "" : undefined}
data-eat={leaving && l.id === shown ? "" : undefined}
style={
{ "--c": `var(--aik-f-${l.tone})` } as React.CSSProperties
}
onClick={() => onOpen?.(l.id)}
>
<span className="aik-fl-row">
<Face
mood={MOOD[l.status]}
shape={l.shape ?? "squircle"}
tone={l.tone}
size={36}
/>
<span className="aik-fl-id">
<b>{l.name}</b>
<span>
<BrandIcon name={l.vendor} tint="brand" size={12} />
{l.model}
</span>
</span>
<State status={l.status} />
</span>
<span className="aik-fl-task">
{l.tools?.length ? (
<BrandStack names={l.tools} size={20} />
) : null}
<span>{l.task}</span>
</span>
<span className="aik-fl-foot">
<Clock3 size={14} aria-hidden="true" />
<Roll>
{ask
? `${ask} needs you`
: fail
? `${fail} failed`
: run
? `${run}/${subs.length} running`
: `${subs.length} done`}
</Roll>
<span className="m">
<strong>{money(total)}</strong> · {clock(l.seconds)}
</span>
</span>
</button>
{narrow && l.id === shown ? panel : null}
</React.Fragment>
)
})}
</div>
{narrow ? null : panel}
</div>
</div>
)
}
Installation
One command adds agent-fleet 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-fleet.json