Decision Loop
How an AI decision becomes an action: the event, the model's typed choice and score, plain-code rules that tick or cross, then the action or a person, and back to learn.
"use client"
import * as React from "react"
import { Code2, Pause, Play } from "lucide-react"
import {
AgentGlyph,
AiKitStyles,
AiStyle,
BrandIcon,
cx,
Edge,
Roll,
type AiTone,
} from "@/lib/ai-kit"
export interface LoopEvent {
brand: string
source: string
subject: string
body: string
/** Typed fields pulled from the event, shown as chips. */
fields: ReadonlyArray<{ label: string; value: string; tone: AiTone }>
}
export interface LoopOption {
label: string
icon: React.ReactNode
score: number
}
export interface LoopRule {
op: "IF" | "AND" | "OR"
field: string
cmp: string
value: string
/** todo: not checked yet, run: checking, pass, fail. */
state: "todo" | "run" | "pass" | "fail"
}
export interface LoopOutcome {
id: string
title: string
sub: string
icon: React.ReactNode
count: number
/** The outcome a person handles. The learn line starts here. */
human?: boolean
}
export interface DecisionLoopProps {
event: LoopEvent
model: {
name: string
model: string
vendor?: string
options: readonly LoopOption[]
status: "todo" | "run" | "done"
}
rules: readonly LoopRule[]
then: string
otherwise: string
/** Which branch the rules took, once they have. */
verdict?: "then" | "else"
outcomes: readonly LoopOutcome[]
/** The outcome the run went to. */
chosen?: string
/** Which line carries a value right now. */
flow: "idle" | "in" | "rules" | "out" | "learn"
paused?: boolean
onPause?: () => void
className?: string
}
const CSS = `
.aik-dl{width:min(100%,1100px);container-type:inline-size}
.aik-dl-grid{position:relative;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.08fr) minmax(0,.92fr);column-gap:60px;align-items:center;padding-bottom:52px}
.aik-dl-mid{display:grid;gap:44px}
.aik-dl-outs{display:grid;gap:12px}
.aik-dl-svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none}
.aik-dl-port{fill:var(--aik-bg);stroke-width:1.6;transition:stroke var(--aik-d-panel)}
.aik-dl-node{--aik-r-shell:22px;--aik-rim:5px;position:relative;animation:aik-dl-in 520ms var(--aik-ease-soft) both;animation-delay:calc(var(--i,0)*70ms)}
.aik-dl-card{display:grid;gap:12px;padding:14px}
.aik-dl-node .aik-beam{animation:aik-beam 2.2s linear infinite}
.aik-dl-top{display:flex;align-items:center;gap:12px;min-width:0}
.aik-dl-ico{display:grid;place-items:center;width:40px;height:40px;flex:none;border-radius:12px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line-2);color:var(--aik-text-2)}
.aik-dl-id{display:grid;line-height:20px;min-width:0}
.aik-dl-id b{font-weight:600;font-size:15.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aik-dl-id span{display:flex;align-items:center;gap:5px;font-size:13.5px;color:var(--aik-text-3);white-space:nowrap}
.aik-dl-top > :last-child:not(.aik-dl-id){margin-left:auto}
.aik-dl-tag{height:26px;display:inline-flex;align-items:center;padding:0 9px;border-radius:8px;font-size:12.5px;font-weight:500;color:var(--aik-text-2);background:var(--aik-raised);white-space:nowrap}
.aik-dl-btn{display:grid;place-items:center;width:28px;height:28px;border-radius:8px;color:var(--aik-text-2)}
.aik-dl-btn:hover{background:var(--aik-hover);color:var(--aik-text)}
.aik-dl-box{display:grid;gap:10px;padding:13px 14px;border-radius:13px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);font-size:14px;line-height:20px}
.aik-dl-box b{font-weight:600;font-size:15px}
.aik-dl-box p{color:var(--aik-text-2)}
.aik-dl-fields{display:flex;flex-wrap:wrap;gap:6px}
.aik-dl-fields span{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 9px;border-radius:8px;font-size:13px;color:var(--c);background:color-mix(in oklab,var(--c) 14%,transparent);animation:aik-dl-pop 420ms var(--aik-ease-soft) both}
.aik-dl-fields span b{font-size:13px;font-weight:600}
.aik-dl-choice{display:flex;align-items:center;gap:10px;height:44px;padding:0 8px 0 14px;border-radius:12px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);font-size:15px}
.aik-dl-choice span{color:var(--aik-text-3)}
.aik-dl-choice b{font-weight:600}
.aik-dl-choice em{margin-left:auto;font:600 13.5px var(--aik-mono);font-style:normal;color:var(--aik-blue);padding:4px 8px;border-radius:8px;background:color-mix(in oklab,var(--aik-blue) 15%,transparent);font-variant-numeric:tabular-nums}
.aik-dl-opts{display:grid;gap:9px;padding:2px 4px}
.aik-dl-opt{display:grid;grid-template-columns:20px minmax(0,1fr) 38% 40px;align-items:center;gap:9px;font-size:14px;color:var(--aik-text-2)}
.aik-dl-opt[data-top]{color:var(--aik-text)}
.aik-dl-opt i{height:5px;border-radius:5px;background:var(--aik-line);position:relative;overflow:hidden}
.aik-dl-opt i::after{content:"";position:absolute;inset:0;border-radius:inherit;background:var(--aik-text-3);transform-origin:left;transform:scaleX(var(--w));transition:transform 900ms var(--aik-ease-move),background var(--aik-d-state)}
.aik-dl-opt[data-top] i::after{background:var(--aik-blue);box-shadow:0 0 8px color-mix(in oklab,var(--aik-blue) 60%,transparent)}
.aik-dl-opt em{font:500 13px var(--aik-mono);font-style:normal;text-align:right;font-variant-numeric:tabular-nums}
.aik-dl-rules{display:grid;gap:8px;padding:12px;border-radius:13px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);font:500 13.5px var(--aik-mono)}
.aik-dl-rule{display:flex;align-items:center;gap:7px;min-height:30px;transition:opacity var(--aik-d-panel)}
.aik-dl-rule[data-state="todo"]{opacity:.55}
.aik-dl-op{display:inline-grid;place-items:center;min-width:44px;height:26px;padding:0 7px;border-radius:7px;font-weight:600;font-size:12.5px;color:var(--c);background:color-mix(in oklab,var(--c) 15%,transparent)}
.aik-dl-tok{display:inline-flex;align-items:center;height:28px;padding:0 9px;border-radius:7px;background:var(--aik-card);box-shadow:inset 0 0 0 1px var(--aik-line-2);color:var(--aik-text)}
.aik-dl-cmp{color:var(--aik-text-3)}
.aik-dl-res{margin-left:auto;width:20px;height:20px;display:grid;place-items:center}
.aik-dl-res[data-state="run"]{border-radius:50%;border:2px solid color-mix(in oklab,var(--aik-blue) 25%,transparent);border-top-color:var(--aik-blue);animation:aik-spin .8s linear infinite}
.aik-dl-res[data-state="todo"]{border-radius:50%;border:2px dashed var(--aik-line-3)}
.aik-dl-res[data-state="pass"]::before,.aik-dl-res[data-state="fail"]::before{content:"";width:18px;height:18px;background:var(--aik-green);-webkit-mask:var(--aik-m-check) center/100% no-repeat;mask:var(--aik-m-check) center/100% no-repeat;animation:aik-dl-pop 360ms var(--aik-ease-soft)}
.aik-dl-res[data-state="fail"]::before{background:var(--aik-red);-webkit-mask-image:var(--aik-m-x);mask-image:var(--aik-m-x)}
.aik-dl-branch{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding-top:6px;border-top:1px dashed var(--aik-line-2);margin-top:2px;font-family:var(--aik-sans);font-size:14px}
.aik-dl-branch > span{display:inline-flex;align-items:center;gap:8px;padding:3px 8px 3px 3px;border-radius:9px;color:var(--aik-text-3);transition:background var(--aik-d-panel),color var(--aik-d-panel)}
.aik-dl-branch > span[data-on]{color:var(--aik-text);background:color-mix(in oklab,var(--c) 12%,transparent)}
.aik-dl-out{--aik-r-shell:20px;--aik-rim:4px;position:relative;transition:opacity var(--aik-d-panel),transform var(--aik-d-move) var(--aik-ease-out)}
.aik-dl[data-chose] .aik-dl-out:not([data-on]){opacity:.5}
.aik-dl-out[data-on]{transform:translateX(-4px)}
.aik-dl-out .aik-dl-card{grid-template-columns:auto 1fr auto;align-items:center;gap:12px;padding:12px}
.aik-dl-out .aik-dl-ico{width:40px;height:40px}
.aik-dl-count{min-width:34px;height:28px;display:inline-grid;place-items:center;padding:0 8px;border-radius:8px;font:600 13.5px var(--aik-mono);background:var(--aik-raised);color:var(--aik-text-2);font-variant-numeric:tabular-nums;transition:background var(--aik-d-panel),color var(--aik-d-panel)}
.aik-dl-out[data-on] .aik-dl-count{background:color-mix(in oklab,var(--aik-green) 18%,transparent);color:var(--aik-green)}
.aik-dl-out[data-human][data-on] .aik-dl-count{background:color-mix(in oklab,var(--aik-amber) 18%,transparent);color:var(--aik-amber)}
.aik-dl-learn{position:absolute;z-index:2;display:inline-flex;align-items:center;height:26px;padding:0 10px;border-radius:8px;font-weight:600;font-size:13px;color:var(--aik-text-3);background:var(--aik-bg);box-shadow:inset 0 0 0 1px var(--aik-line-2);transform:translate(-50%,-50%);transition:color var(--aik-d-panel),box-shadow var(--aik-d-panel)}
.aik-dl-learn[data-on]{color:var(--aik-blue);box-shadow:inset 0 0 0 1px color-mix(in oklab,var(--aik-blue) 45%,transparent)}
.aik-dl-chip{position:absolute;left:0;top:0;z-index:3;display:inline-flex;align-items:center;height:24px;padding:0 9px;border-radius:7px;font:500 12.5px var(--aik-mono);white-space:nowrap;color:var(--aik-blue);background:color-mix(in oklab,var(--aik-blue) 16%,var(--aik-bg));box-shadow:0 0 0 1px color-mix(in oklab,var(--aik-blue) 32%,transparent),0 6px 16px -6px color-mix(in oklab,var(--aik-blue) 55%,transparent);pointer-events:none;opacity:0}
@keyframes aik-dl-in{from{opacity:0;transform:translateY(8px)}}
@keyframes aik-dl-pop{from{opacity:0;transform:scale(.6)}}
@container (max-width:820px){
.aik-dl-grid{grid-template-columns:minmax(0,1fr);row-gap:28px;padding-bottom:0}
.aik-dl-mid{gap:28px}.aik-dl-svg,.aik-dl-learn,.aik-dl-chip{display:none}
}
@media (prefers-reduced-motion: reduce){.aik-dl-node,.aik-dl-fields span{animation:none}}
`
function offsetBox(node: HTMLElement, stop: HTMLElement | null) {
let left = 0
let top = 0
let el: HTMLElement | null = node
while (el && el !== stop) {
left += el.offsetLeft
top += el.offsetTop
el = el.offsetParent as HTMLElement | null
}
return { left, top, width: node.offsetWidth, height: node.offsetHeight }
}
interface Lines {
in: string
rules: string
outs: Record<string, string>
learn: string
ports: Array<[number, number]>
learnAt: [number, number]
}
const CHIP: Record<Exclude<DecisionLoopProps["flow"], "idle">, string> = {
in: "ticket",
rules: "choice",
out: "act",
learn: "learn",
}
/**
* How an AI decision becomes an action: the event, the model's typed choice
* and score, plain-code rules that tick or cross, then the action or a person,
* and a dashed line back from the person so the model learns.
*/
export function DecisionLoop({
event,
model,
rules,
then,
otherwise,
verdict,
outcomes,
chosen,
flow,
paused,
onPause,
className,
}: DecisionLoopProps) {
const root = React.useRef<HTMLDivElement>(null)
const grid = React.useRef<HTMLDivElement>(null)
const refs = React.useRef(new Map<string, HTMLElement>())
const chip = React.useRef<HTMLSpanElement>(null)
const [lines, setLines] = React.useState<Lines | null>(null)
const reg = (id: string) => (el: HTMLElement | null) => {
if (el) refs.current.set(id, el)
else refs.current.delete(id)
}
const measure = React.useCallback(() => {
const g = grid.current
if (!g || (root.current?.clientWidth ?? 0) <= 820) return setLines(null)
const box = (id: string) => {
const el = refs.current.get(id)
return el ? offsetBox(el, g) : null
}
const ev = box("event")
const md = box("model")
const rl = box("rules")
if (!ev || !md || !rl) return
const ports: Array<[number, number]> = []
const a: [number, number] = [ev.left + ev.width, ev.top + ev.height / 2]
const b: [number, number] = [md.left, md.top + 76]
const mx = (a[0] + b[0]) / 2
const inPath = `M${a[0]} ${a[1]}H${mx - 12}Q${mx} ${a[1]} ${mx} ${a[1] + Math.sign(b[1] - a[1]) * 12}V${b[1] - Math.sign(b[1] - a[1]) * 12}Q${mx} ${b[1]} ${mx + 12} ${b[1]}H${b[0]}`
ports.push(a, b)
const c: [number, number] = [md.left + md.width / 2, md.top + md.height]
const d: [number, number] = [rl.left + rl.width / 2, rl.top]
ports.push(c, d)
const r0: [number, number] = [rl.left + rl.width, rl.top + rl.height - 40]
ports.push(r0)
const outs: Record<string, string> = {}
let human: {
left: number
top: number
width: number
height: number
} | null = null
for (const o of outcomes) {
const ob = box(`out-${o.id}`)
if (!ob) continue
if (o.human) human = ob
const t: [number, number] = [ob.left, ob.top + ob.height / 2]
ports.push(t)
const x = r0[0] + 34
const dy = t[1] - r0[1]
const r = Math.min(12, Math.abs(dy) / 2)
const s = Math.sign(dy) || 1
outs[o.id] =
Math.abs(dy) < 1
? `M${r0[0]} ${r0[1]}H${t[0]}`
: `M${r0[0]} ${r0[1]}H${x - r}Q${x} ${r0[1]} ${x} ${r0[1] + s * r}V${t[1] - s * r}Q${x} ${t[1]} ${x + r} ${t[1]}H${t[0]}`
}
let learn = ""
let learnAt: [number, number] = [0, 0]
if (human) {
const h: [number, number] = [
human.left + human.width / 2,
human.top + human.height,
]
const e: [number, number] = [ev.left + ev.width / 2, ev.top + ev.height]
const y = g.offsetHeight - 14
learn = `M${h[0]} ${h[1]}V${y - 14}Q${h[0]} ${y} ${h[0] - 14} ${y}H${e[0] + 14}Q${e[0]} ${y} ${e[0]} ${y - 14}V${e[1]}`
learnAt = [(h[0] + e[0]) / 2, y]
ports.push(h, e)
}
setLines({
in: inPath,
rules: `M${c[0]} ${c[1]}V${d[1]}`,
outs,
learn,
ports,
learnAt,
})
}, [outcomes])
React.useLayoutEffect(() => {
measure()
const observer = new ResizeObserver(() => measure())
if (root.current) observer.observe(root.current)
refs.current.forEach((el) => observer.observe(el))
return () => observer.disconnect()
}, [measure])
// The value chip rides the live line once, start to end, then fades.
React.useEffect(() => {
const el = chip.current
if (!el || !lines || flow === "idle") return
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
const d =
flow === "in"
? lines.in
: flow === "rules"
? lines.rules
: flow === "out"
? chosen
? lines.outs[chosen]
: ""
: lines.learn
if (!d) return
const path = document.createElementNS("http://www.w3.org/2000/svg", "path")
path.setAttribute("d", d)
const svg = root.current?.querySelector("svg")
svg?.appendChild(path)
const total = path.getTotalLength()
const frames = Array.from({ length: 25 }, (_, i) => {
const p = path.getPointAtLength((total * i) / 24)
return {
transform: `translate(${p.x}px, ${p.y}px) translate(-50%, -50%)`,
// Fade in over the first stretch and out before it reaches the card,
// so the chip never sits on top of the card it is arriving at.
opacity:
i === 0 ? 0 : i >= 21 ? Math.max(0, (24 - i) / 4) : i < 3 ? i / 3 : 1,
}
})
path.remove()
const anim = el.animate(frames, {
duration: flow === "learn" ? 1500 : 950,
easing: "cubic-bezier(.65,0,.15,1)",
})
return () => anim.cancel()
}, [flow, lines, chosen])
const top = model.options.reduce(
(best, o) => (o.score > best.score ? o : best),
model.options[0]
)
const shown = model.status === "done"
const chipText =
flow === "in"
? `${event.fields[0]?.label.toLowerCase()}: ${event.fields[0]?.value}`
: flow === "rules"
? `${top.label.toLowerCase()} ${top.score.toFixed(2)}`
: flow === "out"
? verdict === "then"
? "act alone"
: "ask a person"
: flow === "learn"
? "label: refund"
: CHIP.in
return (
<div
ref={root}
className={cx("aik aik-dl", className)}
data-chose={chosen ? "" : undefined}
>
<AiKitStyles />
<AiStyle id="decision-loop" css={CSS} />
<div ref={grid} className="aik-dl-grid">
{lines ? (
<svg className="aik-dl-svg" aria-hidden="true">
<Edge
d={lines.in}
tone="blue"
state={
flow === "in"
? "live"
: model.status !== "todo"
? "done"
: "idle"
}
duration={0.95}
/>
<Edge
d={lines.rules}
tone="blue"
state={
flow === "rules"
? "live"
: rules.some((r) => r.state !== "todo")
? "done"
: "idle"
}
duration={0.95}
/>
{outcomes.map((o) =>
lines.outs[o.id] ? (
<Edge
key={o.id}
d={lines.outs[o.id]}
tone={o.human ? "amber" : "green"}
state={
chosen === o.id
? flow === "out"
? "live"
: "done"
: "idle"
}
duration={0.95}
/>
) : null
)}
{lines.learn ? (
<Edge
d={lines.learn}
tone="blue"
dashed
state={flow === "learn" ? "live" : "idle"}
duration={1.5}
/>
) : null}
{lines.ports.map((p, i) => (
<circle
key={i}
className="aik-dl-port"
cx={p[0]}
cy={p[1]}
r={4}
stroke="var(--aik-line-3)"
/>
))}
</svg>
) : null}
{lines?.learn ? (
<span
className="aik-dl-learn"
data-on={flow === "learn" ? "" : undefined}
style={{ left: lines.learnAt[0], top: lines.learnAt[1] }}
>
Learn
</span>
) : null}
<span ref={chip} className="aik-dl-chip" aria-hidden="true">
{chipText}
</span>
<div
ref={reg("event")}
className="aik-dl-node aik-shell"
style={{ "--i": 0 } as React.CSSProperties}
>
<div className="aik-surface aik-dl-card">
<div className="aik-dl-top">
<span className="aik-dl-ico">
<BrandIcon name={event.brand} tint="brand" size={20} />
</span>
<span className="aik-dl-id">
<b>{event.source}</b>
<span>Input</span>
</span>
{onPause ? (
<button
type="button"
className="aik-dl-btn"
onClick={onPause}
aria-label={paused ? "Play" : "Pause"}
>
{paused ? <Play size={15} /> : <Pause size={15} />}
</button>
) : null}
</div>
<div className="aik-dl-box" key={event.subject}>
<b>{event.subject}</b>
<p>{event.body}</p>
<div className="aik-dl-fields">
{event.fields.map((f, i) => (
<span
key={f.label}
style={
{
"--c": `var(--aik-f-${f.tone})`,
animationDelay: `${200 + i * 90}ms`,
} as React.CSSProperties
}
>
{f.label} <b>{f.value}</b>
</span>
))}
</div>
</div>
</div>
</div>
<div className="aik-dl-mid">
<div
ref={reg("model")}
className="aik-dl-node aik-shell"
style={{ "--i": 1 } as React.CSSProperties}
>
<div className="aik-surface aik-dl-card">
<span
className="aik-beam"
data-on={model.status === "run" ? "" : undefined}
/>
<div className="aik-dl-top">
<span className="aik-dl-ico">
<AgentGlyph
seed={model.name}
tone="blue"
size={18}
live={model.status === "run"}
/>
</span>
<span className="aik-dl-id">
<b>{model.name}</b>
<span>
{model.vendor ? (
<BrandIcon name={model.vendor} tint="brand" size={12} />
) : null}
{model.model}
</span>
</span>
<span className="aik-dl-tag">Typed output</span>
</div>
<div className="aik-dl-choice">
<span>Choice</span>
<b>
<Roll>{shown ? top.label : "…"}</Roll>
</b>
<em>
<Roll>{shown ? top.score.toFixed(2) : "–"}</Roll>
</em>
</div>
<div className="aik-dl-opts">
{model.options.map((o) => (
<div
key={o.label}
className="aik-dl-opt"
data-top={shown && o === top ? "" : undefined}
>
{o.icon}
<span>{o.label}</span>
<i
style={
{
"--w": shown ? Math.max(0.03, o.score) : 0,
} as React.CSSProperties
}
/>
<em>{shown ? o.score.toFixed(2) : "–"}</em>
</div>
))}
</div>
</div>
</div>
<div
ref={reg("rules")}
className="aik-dl-node aik-shell"
style={{ "--i": 2 } as React.CSSProperties}
>
<div className="aik-surface aik-dl-card">
<div className="aik-dl-top">
<span className="aik-dl-ico">
<Code2 size={18} />
</span>
<span className="aik-dl-id">
<b>Rules</b>
<span>Code, before anything happens</span>
</span>
</div>
<div className="aik-dl-rules">
{rules.map((r, i) => (
<div key={i} className="aik-dl-rule" data-state={r.state}>
<span
className="aik-dl-op"
style={
{
"--c":
r.op === "IF"
? "var(--aik-f-rose)"
: "var(--aik-f-amber)",
} as React.CSSProperties
}
>
{r.op}
</span>
<span className="aik-dl-tok">{r.field}</span>
<span className="aik-dl-cmp">{r.cmp}</span>
<span className="aik-dl-tok">{r.value}</span>
<span className="aik-dl-res" data-state={r.state} />
</div>
))}
<div className="aik-dl-branch">
<span
data-on={verdict === "then" ? "" : undefined}
style={{ "--c": "var(--aik-green)" } as React.CSSProperties}
>
<span
className="aik-dl-op"
style={
{ "--c": "var(--aik-f-green)" } as React.CSSProperties
}
>
THEN
</span>
{then}
</span>
<span
data-on={verdict === "else" ? "" : undefined}
style={{ "--c": "var(--aik-amber)" } as React.CSSProperties}
>
<span
className="aik-dl-op"
style={
{ "--c": "var(--aik-text-3)" } as React.CSSProperties
}
>
ELSE
</span>
{otherwise}
</span>
</div>
</div>
</div>
</div>
</div>
<div className="aik-dl-outs">
{outcomes.map((o) => (
<div
key={o.id}
ref={reg(`out-${o.id}`)}
className="aik-dl-out aik-shell"
data-on={chosen === o.id ? "" : undefined}
data-human={o.human ? "" : undefined}
>
<div className="aik-surface aik-dl-card">
<span className="aik-dl-ico">{o.icon}</span>
<span className="aik-dl-id">
<b>{o.title}</b>
<span>{o.sub}</span>
</span>
<span className="aik-dl-count">
<Roll>{String(o.count)}</Roll>
</span>
</div>
</div>
))}
</div>
</div>
</div>
)
}
Installation
One command adds decision-loop 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/decision-loop.json