Agent State Machine
One agent as a state diagram: every state a card, every transition a line counting how often the run took it, retries as loops and the current state glowing.
"use client"
import * as React from "react"
import { CircleCheck, CircleX, Clock3 } from "lucide-react"
import {
AiKitStyles,
AiStyle,
BrandIcon,
BrandStack,
cx,
Edge,
Face,
Roll,
type AiMood,
type AiShape,
type AiTone,
} from "@/lib/ai-kit"
export interface MachineState {
id: string
label: string
/** Grid position, both counted from 1. */
col: number
row: number
tone: AiTone
/** "wait" for states that need a person, "error" for recovery, "end" for the final state. */
kind?: "step" | "wait" | "error" | "end"
tools?: readonly string[]
/** How many times the run entered this state. */
visits: number
/** Seconds spent here in total. */
seconds?: number
}
export interface MachineTransition {
id: string
from: string
to: string
/** How often the run took it. */
count: number
/** "over" arcs above the row (going back), "self" is a retry loop. */
route?: "direct" | "over" | "self"
}
export interface AgentStateMachineProps {
agent: {
name: string
model: string
vendor: string
tone: AiTone
shape?: AiShape
}
states: readonly MachineState[]
transitions: readonly MachineTransition[]
current: string
/** The transition taken last; it carries a pulse. */
last?: string
status: "run" | "ask" | "done" | "fail"
className?: string
}
const CSS = `
.aik-sm{--aik-r-shell:26px;--aik-rim:6px;width:min(100%,1080px);container-type:inline-size}
.aik-sm-card{padding:20px 22px 26px}
.aik-sm-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding-bottom:22px}
.aik-sm-head b{font-size:16px;font-weight:600}
.aik-sm-model{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 9px;border-radius:8px;background:var(--aik-raised);color:var(--aik-text-2);font-size:13px}
.aik-sm-right{margin-left:auto;display:flex;align-items:center;flex-wrap:wrap;gap:8px 14px;color:var(--aik-text-3);font-size:14px;font-variant-numeric:tabular-nums}
.aik-sm-status{display:inline-flex;align-items:center;gap:7px;height:28px;padding:0 11px;border-radius:9px;font-weight:500;font-size:13.5px;color:var(--c);background:color-mix(in oklab,var(--c) 14%,transparent);transition:color var(--aik-d-state),background var(--aik-d-state)}
.aik-sm-status i{width:7px;height:7px;border-radius:50%;background:currentColor}
.aik-sm-board{position:relative;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));grid-auto-rows:auto;column-gap:64px;row-gap:74px;padding:64px 0 6px 40px}
.aik-sm-svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none}
.aik-sm-start{fill:var(--aik-text-3)}
.aik-sm-node{position:relative;display:grid;gap:8px;padding:13px 14px;border-radius:15px;background:var(--aik-card);box-shadow:var(--aik-sh-card);transition:box-shadow var(--aik-d-panel),opacity var(--aik-d-panel),transform var(--aik-d-move) var(--aik-ease-out);z-index:1}
.aik-sm-node[data-off]{opacity:.62}
.aik-sm-node[data-now]{box-shadow:0 0 0 1.5px var(--c),0 0 0 6px color-mix(in oklab,var(--c) 16%,transparent),0 16px 40px -14px color-mix(in oklab,var(--c) 60%,transparent);transform:translateY(-2px)}
.aik-sm-node .aik-beam{--aik-beam-c:var(--c);animation:aik-beam 2.2s linear infinite}
.aik-sm-top{display:flex;align-items:center;gap:9px;min-width:0}
.aik-sm-top b{font-size:15px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aik-sm-ring{width:11px;height:11px;flex:none;border-radius:50%;box-shadow:inset 0 0 0 2px var(--c)}
.aik-sm-node[data-now] .aik-sm-ring{background:var(--c);box-shadow:0 0 0 3px color-mix(in oklab,var(--c) 25%,transparent)}
.aik-sm-top svg{color:var(--c)}
.aik-sm-sub{display:flex;align-items:center;gap:8px;min-height:22px;font-size:13px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-sm-node[data-now] .aik-sm-sub{color:var(--c)}
.aik-sm-sub .aik-brand-stack{margin-left:auto}
.aik-sm-count{position:absolute;z-index:2;translate:-50% -50%;display:inline-grid;place-items:center;min-width:30px;height:22px;padding:0 7px;border-radius:11px;font:500 12px/1 var(--aik-mono);color:var(--aik-text-3);background:var(--aik-card);box-shadow:0 0 0 1px var(--aik-line-2);transition:color var(--aik-d-state),box-shadow var(--aik-d-state),background var(--aik-d-state)}
.aik-sm-count[data-hit]{color:var(--aik-text)}
.aik-sm-count[data-last]{color:var(--aik-on-fill);background:var(--c);box-shadow:0 0 0 4px color-mix(in oklab,var(--c) 22%,transparent);animation:aik-sm-tick 480ms var(--aik-ease-out)}
@keyframes aik-sm-tick{30%{transform:scale(1.22)}}
@container (max-width:780px){
.aik-sm-board{grid-template-columns:repeat(2,minmax(0,1fr));column-gap:12px;row-gap:12px;padding:0}
.aik-sm-node{grid-column:auto!important;grid-row:auto!important}
.aik-sm-svg,.aik-sm-count{display:none}
.aik-sm-right{margin-left:0;width:100%}
}
@container (max-width:380px){.aik-sm-board{grid-template-columns:minmax(0,1fr)}}
@media (prefers-reduced-motion: reduce){.aik-sm-count{animation:none!important}}
`
const MOOD: Record<AgentStateMachineProps["status"], AiMood> = {
run: "work",
ask: "needs",
done: "happy",
fail: "oops",
}
const STATUS_COLOR = {
run: "var(--aik-blue)",
ask: "var(--aik-amber)",
done: "var(--aik-green)",
fail: "var(--aik-red)",
}
interface Box {
left: number
top: number
width: number
height: number
}
function boxIn(node: HTMLElement, root: HTMLElement): Box {
let left = 0
let top = 0
let el: HTMLElement | null = node
while (el && el !== root) {
left += el.offsetLeft
top += el.offsetTop
el = el.offsetParent as HTMLElement | null
}
return { left, top, width: node.offsetWidth, height: node.offsetHeight }
}
/** Path and label point for one transition between two boxes. */
function route(
a: Box,
b: Box,
kind: MachineTransition["route"],
lane: number
): { d: string; at: [number, number] } {
if (kind === "self") {
const x1 = a.left + a.width * 0.3
const x2 = a.left + a.width * 0.62
const y = a.top
return {
d: `M${x1} ${y}V${y - 18}Q${x1} ${y - 30} ${x1 + 12} ${y - 30}H${x2 - 12}Q${x2} ${y - 30} ${x2} ${y - 18}V${y}`,
at: [(x1 + x2) / 2, y - 30],
}
}
if (kind === "over") {
const x1 = a.left + a.width / 2
const x2 = b.left + b.width / 2
const y = Math.min(a.top, b.top) - 50 - lane * 20
return {
d: `M${x1} ${a.top}V${y + 10}Q${x1} ${y} ${x1 - Math.sign(x1 - x2) * 10} ${y}H${x2 + Math.sign(x1 - x2) * 10}Q${x2} ${y} ${x2} ${y + 10}V${b.top}`,
at: [(x1 + x2) / 2, y],
}
}
const sameRow = Math.abs(a.top - b.top) < 4
const sameCol = Math.abs(a.left - b.left) < 4
if (sameRow) {
const right = b.left > a.left
const y = a.top + a.height / 2 + lane * 12
const x1 = right ? a.left + a.width : a.left
const x2 = right ? b.left : b.left + b.width
return { d: `M${x1} ${y}H${x2}`, at: [(x1 + x2) / 2, y] }
}
if (sameCol) {
const down = b.top > a.top
const x = a.left + a.width / 2 + lane * 22
const y1 = down ? a.top + a.height : a.top
const y2 = down ? b.top : b.top + b.height
// A long run behind another card puts its count just above the arrival.
const far = Math.abs(y2 - y1) > 140
return {
d: `M${x} ${y1}V${y2}`,
at: [x, far ? y2 - (down ? 26 : -26) : (y1 + y2) / 2],
}
}
// Different row and column: leave from the side, turn, arrive from above or below.
const right = b.left > a.left
const x1 = right ? a.left + a.width : a.left
const y1 = a.top + a.height / 2
const x2 = b.left + b.width / 2 + (right ? -b.width * 0.25 : b.width * 0.25)
const y2 = b.top > a.top ? b.top : b.top + b.height
const mx = right ? x1 + 22 + lane * 10 : x1 - 22 - lane * 10
const r = 9
const sy = y2 > y1 ? 1 : -1
const sx = right ? 1 : -1
return {
d: `M${x1} ${y1}H${mx - sx * r}Q${mx} ${y1} ${mx} ${y1 + sy * r}V${(y1 + y2) / 2 - sy * r}Q${mx} ${(y1 + y2) / 2} ${mx + Math.sign(x2 - mx) * r} ${(y1 + y2) / 2}H${x2 - Math.sign(x2 - mx) * r}Q${x2} ${(y1 + y2) / 2} ${x2} ${(y1 + y2) / 2 + sy * r}V${y2}`,
at: [(mx + x2) / 2, (y1 + y2) / 2],
}
}
/**
* One agent as a state diagram. Every state is a card, every transition a
* line with a counter of how often the run took it. Retries draw as loops, the
* last transition carries a pulse and its counter ticks, and the current state
* glows in its colour.
*/
export function AgentStateMachine({
agent,
states,
transitions,
current,
last,
status,
className,
}: AgentStateMachineProps) {
const board = React.useRef<HTMLDivElement>(null)
const cards = React.useRef(new Map<string, HTMLElement>())
const [paths, setPaths] = React.useState<
Array<{ id: string; d: string; at: [number, number] }>
>([])
const [start, setStart] = React.useState<[number, number] | null>(null)
const layoutKey =
states.map((s) => `${s.id}${s.col}${s.row}`).join() +
transitions.map((t) => t.id).join()
const measure = React.useCallback(() => {
const root = board.current
if (!root) return
const boxes = new Map<string, Box>()
cards.current.forEach((node, id) => boxes.set(id, boxIn(node, root)))
// Two transitions between the same pair go side by side.
const seen = new Map<string, number>()
const next: typeof paths = []
for (const t of transitions) {
const a = boxes.get(t.from)
const b = boxes.get(t.to)
if (!a || !b) continue
const key = [t.from, t.to].sort().join("|") + (t.route ?? "")
const n = seen.get(key) ?? 0
seen.set(key, n + 1)
const lane =
t.route === "over"
? n
: n === 0
? transitions.some(
(o) =>
o.from === t.to &&
o.to === t.from &&
(o.route ?? "direct") === (t.route ?? "direct")
)
? -1
: 0
: 1
next.push({ id: t.id, ...route(a, b, t.route, lane) })
}
setPaths(next)
const first = boxes.get(states[0]?.id ?? "")
setStart(first ? [first.left - 30, first.top + first.height / 2] : null)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [layoutKey])
React.useLayoutEffect(() => {
measure()
const observer = new ResizeObserver(measure)
if (board.current) observer.observe(board.current)
return () => observer.disconnect()
}, [measure])
const taken = transitions.reduce((sum, t) => sum + t.count, 0)
const now = states.find((s) => s.id === current)
return (
<div className={cx("aik aik-sm aik-shell", className)}>
<AiKitStyles />
<AiStyle id="agent-state-machine" css={CSS} />
<div className="aik-surface aik-sm-card">
<div className="aik-sm-head">
<Face
mood={MOOD[status]}
shape={agent.shape ?? "orb"}
tone={agent.tone}
size={32}
/>
<b>{agent.name}</b>
<span className="aik-sm-model">
<BrandIcon name={agent.vendor} tint="brand" size={13} />
{agent.model}
</span>
<span className="aik-sm-right">
<Roll>{`${taken} transitions`}</Roll>
<span
className="aik-sm-status"
style={{ "--c": STATUS_COLOR[status] } as React.CSSProperties}
>
<i aria-hidden="true" />
<Roll>
{status === "done"
? "Finished"
: `${status === "ask" ? "Paused" : status === "fail" ? "Failed" : "Running"} · ${now?.label ?? ""}`}
</Roll>
</span>
</span>
</div>
<div ref={board} className="aik-sm-board">
<svg className="aik-sm-svg" aria-hidden="true">
<defs>
<marker
id="aik-sm-arrow"
viewBox="0 0 8 8"
refX="7"
refY="4"
markerWidth="7"
markerHeight="7"
orient="auto-start-reverse"
>
<path d="M0 0L8 4L0 8z" fill="var(--aik-line-3)" />
</marker>
</defs>
{start ? (
<g>
<circle
className="aik-sm-start"
cx={start[0]}
cy={start[1]}
r={7}
/>
<path
d={`M${start[0] + 8} ${start[1]}H${start[0] + 28}`}
stroke="var(--aik-line-3)"
strokeWidth={1.5}
markerEnd="url(#aik-sm-arrow)"
/>
</g>
) : null}
{paths.map((p) => {
const t = transitions.find((x) => x.id === p.id)
const to = states.find((s) => s.id === t?.to)
const isLast = p.id === last
return (
<g key={p.id}>
<Edge
d={p.d}
tone={to?.tone ?? "blue"}
state={isLast ? "live" : t && t.count > 0 ? "done" : "idle"}
width={1.5}
duration={1.3}
/>
<path
d={p.d}
fill="none"
stroke="transparent"
markerEnd="url(#aik-sm-arrow)"
/>
</g>
)
})}
</svg>
{paths.map((p) => {
const t = transitions.find((x) => x.id === p.id)
const to = states.find((s) => s.id === t?.to)
return (
<span
key={`${p.id}-${t?.count}`}
className="aik-sm-count"
data-hit={t && t.count > 0 ? "" : undefined}
data-last={p.id === last ? "" : undefined}
style={
{
left: p.at[0],
top: p.at[1],
"--c": `var(--aik-f-${to?.tone ?? "blue"})`,
} as React.CSSProperties
}
>
{t?.count ?? 0}×
</span>
)
})}
{states.map((state) => {
const isNow = state.id === current
const Icon =
state.kind === "wait"
? Clock3
: state.kind === "error"
? CircleX
: state.kind === "end"
? CircleCheck
: null
return (
<div
key={state.id}
ref={(node) => {
if (node) cards.current.set(state.id, node)
else cards.current.delete(state.id)
}}
className="aik-sm-node"
data-now={isNow ? "" : undefined}
data-off={state.visits === 0 && !isNow ? "" : undefined}
style={
{
gridColumn: state.col,
gridRow: state.row,
"--c": `var(--aik-f-${state.tone})`,
} as React.CSSProperties
}
>
<span
className="aik-beam"
data-on={isNow && status === "run" ? "" : undefined}
/>
<span className="aik-sm-top">
{Icon ? (
<Icon size={15} aria-hidden="true" />
) : (
<span className="aik-sm-ring" aria-hidden="true" />
)}
<b>{state.label}</b>
</span>
<span className="aik-sm-sub">
<Roll>
{state.visits === 0 && !isNow
? "Not reached"
: `${state.seconds ?? 0}s · ${state.visits}×`}
</Roll>
{state.tools?.length ? (
<BrandStack names={state.tools} size={22} />
) : null}
</span>
</div>
)
})}
</div>
</div>
</div>
)
}
Installation
One command adds agent-state-machine 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-state-machine.json