AI Thread
The conversation itself: typing bubbles that open into the message, flat Storm-style turns with artefacts inside them, and a room where several agents talk and hand off.
"use client"
import * as React from "react"
import { ArrowDown, ArrowRight, ArrowUp, CornerDownRight } from "lucide-react"
import {
AiKitStyles,
AiStyle,
cx,
Face,
Mark,
toneColor,
type AiMood,
type AiShape,
type AiStatus,
type AiTone,
} from "@/lib/ai-kit"
const CSS = `
.aik-th{--aik-r-shell:28px;--aik-rim:6px;width:min(100%,560px);container-type:inline-size}
.aik-th-card{display:grid;grid-template-rows:minmax(0,1fr) auto;height:var(--aik-th-h,420px);overflow:hidden}
.aik-th-view{position:relative;min-height:0}
.aik-th-scroll{height:100%;overflow-y:auto;scrollbar-width:none;padding:22px 20px 18px;display:flex;flex-direction:column;-webkit-mask:linear-gradient(transparent,#000 26px);mask:linear-gradient(transparent,#000 26px)}
.aik-th-scroll::-webkit-scrollbar{display:none}
.aik-th-scroll > :first-child{margin-top:auto}
.aik-th-band{position:absolute;left:0;right:0;bottom:0;height:64px;display:grid;place-items:end center;padding-bottom:10px;pointer-events:none;background:linear-gradient(transparent,var(--aik-card) 82%);opacity:0;transition:opacity var(--aik-d-state) var(--aik-ease-out)}
.aik-th-band[data-on]{opacity:1}
.aik-th-jump{display:inline-flex;align-items:center;gap:7px;height:32px;padding:0 12px 0 10px;border-radius:16px;background:var(--aik-card);box-shadow:var(--aik-sh-pop);font-size:13px;font-weight:500;pointer-events:none;transform:translateY(8px) scale(.96);transition:transform var(--aik-d-enter) var(--aik-ease-out)}
.aik-th-band[data-on] .aik-th-jump{pointer-events:auto;transform:none}
.aik-th-jump i{display:grid;place-items:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--aik-blue);color:var(--aik-on-fill);font:600 11px var(--aik-sans);font-style:normal}
.aik-th-field{display:flex;align-items:center;gap:10px;height:56px;padding:0 10px 0 18px;border-top:1px solid var(--aik-line)}
.aik-th-in{flex:1;min-width:0;height:100%;border:0;outline:0;background:none;font-size:15px}
.aik .aik-th-in:focus-visible{outline:none}
.aik-th-in::placeholder{color:var(--aik-text-3);opacity:1}
.aik-th-send{display:grid;place-items:center;width:36px;height:36px;border-radius:11px;background:color-mix(in oklab,var(--aik-raised) 78%,var(--aik-text) 22%);color:var(--aik-pri-ink);transition:background var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-press) var(--aik-ease-out)}
.aik-th-send[data-ready]{background:var(--aik-pri)}
.aik-th-send:active{transform:scale(.94)}
.aik-th-u{align-self:flex-end;max-width:75%;padding:10px 16px;border-radius:18px;background:var(--aik-raised);font-size:15px;line-height:22px;overflow-wrap:anywhere;transform-origin:100% 100%}
.aik-th-u[data-new]{animation:aik-th-launch 520ms var(--aik-ease-move) both}
.aik-th-meta{align-self:flex-end;margin-top:6px;font-size:12px;color:var(--aik-text-3)}
.aik-th-gap{margin-top:26px}
.aik-th-cont{margin-top:6px}
@keyframes aik-th-launch{from{opacity:.2;transform:translateY(72px) scale(.9)}}
.aik-th-a{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;align-items:end}
.aik-th-a > .aik-face{margin-bottom:2px}
.aik-th-a[data-cont] > .aik-face{visibility:hidden}
.aik-th-b{justify-self:start;max-width:86%;padding:10px 16px;border-radius:18px 18px 18px 6px;background:var(--aik-card);box-shadow:inset 0 0 0 1px var(--aik-line-2);font-size:15px;line-height:22px;overflow-wrap:anywhere}
.aik-th-b[data-new]{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-th-b[data-state="typing"]{display:flex;align-items:center;gap:5px;width:60px;height:42px;padding:0 18px}
.aik-th-b[data-state="typing"] i{width:6px;height:6px;border-radius:50%;background:var(--aik-text-3);animation:aik-th-dot 1.2s cubic-bezier(.2,0,0,1) infinite}
.aik-th-b[data-state="typing"] i:nth-child(2){animation-delay:.15s}
.aik-th-b[data-state="typing"] i:nth-child(3){animation-delay:.3s}
.aik-th-b[data-morph]{animation:aik-th-open 560ms var(--aik-ease-move) both}
.aik-th-b[data-morph] > span{animation:aik-th-fade 320ms var(--aik-ease-out) 200ms both}
@keyframes aik-th-dot{0%,60%,100%{transform:none;opacity:.5}30%{transform:translateY(-4px);opacity:1}}
@keyframes aik-th-open{from{clip-path:inset(calc(100% - 42px) calc(100% - 60px) 0 0 round 18px 18px 18px 6px)}to{clip-path:inset(0 0 0 0 round 18px 18px 18px 6px)}}
@keyframes aik-th-fade{from{opacity:0}}
.aik-th-rule{display:flex;align-items:center;gap:12px;margin:26px 0 0;font-size:12px;color:var(--aik-text-3);white-space:nowrap}
.aik-th-rule::before,.aik-th-rule::after{content:"";flex:1;height:1px;background:var(--aik-line-2)}
.aik-th-head{display:flex;align-items:center;gap:10px;min-width:0}
.aik-th-head b{font-size:15px;font-weight:500}
.aik-th-model{display:inline-flex;align-items:center;height:22px;padding:0 7px;border-radius:7px;font:11.5px var(--aik-mono);color:var(--aik-text-2);box-shadow:inset 0 0 0 1px var(--aik-line-2);white-space:nowrap}
.aik-th-head time{font-size:13px;color:var(--aik-text-3);font-variant-numeric:tabular-nums}
.aik-th-reply{display:grid;gap:10px;margin:4px 0 0 38px;font-size:15px;line-height:24px;overflow-wrap:anywhere}
.aik-th-flat[data-new]{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-th-reply code{font-size:13px;padding:2px 5px;border-radius:6px;background:var(--aik-raised)}
.aik-th-arts{display:flex;flex-wrap:wrap;gap:8px}
.aik-th-chip{display:inline-flex;align-items:center;gap:7px;height:28px;padding:0 9px 0 8px;border-radius:9px;background:var(--aik-raised);font:12.5px var(--aik-mono);color:var(--aik-text-2);white-space:nowrap;animation:aik-pop var(--aik-d-enter) var(--aik-ease-out) both;transition:background var(--aik-d-state),color var(--aik-d-state)}
.aik-th-chip[data-s="run"]{color:var(--aik-blue);background:color-mix(in oklab,var(--aik-blue) 12%,transparent)}
.aik-th-chip svg{color:var(--aik-text-3)}
.aik-th-chip .aik-mark{width:14px;height:14px;transform:scale(.78);margin:0 -2px}
.aik-th-file{position:relative;display:flex;align-items:center;gap:12px;width:min(100%,340px);padding:10px 10px 10px 10px;border-radius:14px;background:var(--aik-panel);box-shadow:inset 0 0 0 1px var(--aik-line-2);animation:aik-pop var(--aik-d-panel) var(--aik-ease-out) both}
.aik-th-ftile{display:grid;place-items:center;width:40px;height:40px;border-radius:10px;flex:none;background:var(--aik-raised);color:var(--aik-text)}
.aik-th-ftxt{flex:1;min-width:0;display:grid}
.aik-th-file b{font:500 13.5px/18px var(--aik-mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.aik-th-file em{font-style:normal;font-size:12.5px;line-height:17px;color:var(--aik-text-3)}
.aik-th-room .aik-th-card{grid-template-rows:minmax(0,1fr) auto;grid-template-columns:72px minmax(0,1fr)}
.aik-th-rail{grid-row:1/-1;position:relative;display:flex;flex-direction:column;align-items:center;gap:16px;padding:20px 0;border-right:1px solid var(--aik-line);background:var(--aik-panel)}
.aik-th-ring{position:absolute;left:50%;top:14px;width:48px;height:48px;margin-left:-24px;border-radius:16px;box-shadow:inset 0 0 0 2px var(--c);background:color-mix(in oklab,var(--c) 10%,transparent);transform:translateY(calc(var(--i)*52px));transition:transform 480ms var(--aik-ease-move),box-shadow var(--aik-d-panel),background var(--aik-d-panel),opacity var(--aik-d-state)}
.aik-th-ring[data-off]{opacity:0}
.aik-th-seat{position:relative;display:grid;place-items:center;width:36px;height:36px}
.aik-th-seat .aik-mark{position:absolute;right:-6px;bottom:-5px;transform:scale(.72);box-shadow:0 0 0 3px var(--aik-panel);background:var(--aik-panel)}
.aik-th-msg{display:grid;grid-template-columns:22px minmax(0,1fr);gap:10px;font-size:15px;line-height:23px}
.aik-th-msg[data-new]{animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-th-msg > .aik-face{margin-top:2px}
.aik-th-msg b{font-weight:600;color:var(--c);margin-right:8px}
.aik-th-msg time{font-size:12px;color:var(--aik-text-3);margin-left:8px;font-variant-numeric:tabular-nums}
.aik-th-msg p{overflow-wrap:anywhere}
.aik-th-msg[data-reply]{position:relative;margin-left:32px}
.aik-th-msg[data-reply]::before{content:"";position:absolute;left:-22px;top:-16px;width:14px;height:28px;border-left:1.5px solid var(--aik-line-3);border-bottom:1.5px solid var(--aik-line-3);border-bottom-left-radius:10px}
.aik-th-you{width:22px;height:22px;margin-top:2px;border-radius:7px;display:grid;place-items:center;background:var(--aik-raised);font:600 11px var(--aik-sans);color:var(--aik-text-2)}
.aik-th-hand{display:inline-flex;align-items:center;gap:8px;height:30px;margin-top:8px;padding:0 10px 0 6px;border-radius:10px;font-size:13px;font-weight:500;color:var(--c);background:color-mix(in oklab,var(--c) 11%,transparent);box-shadow:inset 0 0 0 1px color-mix(in oklab,var(--c) 34%,transparent);animation:aik-th-hand 520ms var(--aik-ease-move) both}
.aik-th-hand{max-width:100%;white-space:nowrap}
.aik-th-hand svg{color:currentColor}
.aik-th-hl{min-width:0;overflow:hidden;text-overflow:ellipsis}
@keyframes aik-th-hand{from{opacity:0;transform:translateX(-18px)}}
.aik-th-pres{display:flex;align-items:center;gap:8px;height:44px;padding:0 18px;border-top:1px solid var(--aik-line);font-size:13px;color:var(--aik-text-2);min-width:0}
.aik-th-pres span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@container (max-width:420px){.aik-th-scroll{padding:18px 14px 14px}.aik-th-b{max-width:100%}.aik-th-u{max-width:86%}.aik-th-model{display:none}.aik-th-room .aik-th-card{grid-template-columns:56px minmax(0,1fr)}.aik-th-reply{margin-left:0}}
@media (prefers-reduced-motion: reduce){.aik-th-u[data-new],.aik-th-b[data-morph],.aik-th-b[data-morph] > span,.aik-th-hand,.aik-th-b[data-state="typing"] i{animation:none}.aik-th-ring{transition:none}}
`
export interface AiTurn {
id: string
role: "user" | "agent"
text: string
/** The agent's name. Consecutive turns with the same name are grouped. */
name?: string
tone?: AiTone | (string & {})
shape?: AiShape
/** `typing` shows dots, `streaming` shows a caret after the text. */
state?: "typing" | "streaming" | "done"
/** Already formatted, such as "9:41". */
time?: string
/** A short line under a user turn, such as "Read". */
meta?: string
/** Flat thread only: the model chip in the name row. */
model?: string
/** Flat thread only: a date rule drawn above this turn. */
day?: string
/** Flat thread only: chips and cards shown inside the turn. */
artefacts?: React.ReactNode
}
interface ThreadBase extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSubmit"
> {
/** Height of the thread in pixels. It scrolls inside itself. */
height?: number
/** Called with the trimmed text from the reply field. The field is hidden when omitted. */
onSend?: (text: string) => void
placeholder?: string
}
/** Keeps a scroller pinned to its end as content arrives, unless the reader has scrolled away. */
function useStick(signal: unknown) {
const ref = React.useRef<HTMLDivElement>(null)
const [away, setAway] = React.useState(false)
const awayRef = React.useRef(false)
const jump = React.useCallback((smooth: boolean) => {
const node = ref.current
if (node)
node.scrollTo({
top: node.scrollHeight,
behavior: smooth ? "smooth" : "auto",
})
}, [])
React.useEffect(() => {
if (!awayRef.current) jump(false)
}, [signal, jump])
const onScroll = () => {
const node = ref.current
if (!node) return
const far = node.scrollHeight - node.scrollTop - node.clientHeight > 48
awayRef.current = far
setAway(far)
}
return { ref, away, onScroll, jump }
}
/** Ids that arrived after the first render, so only new turns animate in. */
function useArrivals(ids: string[]) {
const [seen] = React.useState(() => new Set(ids))
return (id: string) => !seen.has(id)
}
function Field({
onSend,
placeholder,
}: {
onSend: (text: string) => void
placeholder: string
}) {
const [value, setValue] = React.useState("")
const send = () => {
const text = value.trim()
if (!text) return
onSend(text)
setValue("")
}
return (
<div className="aik-th-field">
<input
className="aik-th-in"
value={value}
placeholder={placeholder}
aria-label={placeholder}
onChange={(event) => setValue(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
event.preventDefault()
send()
}
}}
/>
<button
type="button"
className="aik-th-send"
aria-label="Send"
data-ready={value.trim() ? "" : undefined}
onClick={send}
>
<ArrowUp size={18} />
</button>
</div>
)
}
function Jump({
on,
count,
onClick,
}: {
on: boolean
count: number
onClick: () => void
}) {
return (
<div className="aik-th-band" data-on={on ? "" : undefined}>
<button
type="button"
className="aik-th-jump"
tabIndex={on ? 0 : -1}
onClick={onClick}
>
<ArrowDown size={14} />
Latest
{count > 0 ? <i>{count}</i> : null}
</button>
</div>
)
}
const moodOf = (turn: AiTurn): AiMood =>
turn.state === "typing"
? "think"
: turn.state === "streaming"
? "talk"
: "idle"
function Bubble({ turn, fresh }: { turn: AiTurn; fresh: boolean }) {
const was = React.useRef(turn.state)
const [morph, setMorph] = React.useState(false)
React.useEffect(() => {
if (was.current === "typing" && turn.state !== "typing") setMorph(true)
was.current = turn.state
}, [turn.state])
const typing = turn.state === "typing"
return (
<div
className="aik-th-b"
data-state={turn.state ?? "done"}
data-new={fresh && !morph ? "" : undefined}
data-morph={morph ? "" : undefined}
>
{typing ? (
<>
<i />
<i />
<i />
</>
) : (
<span>
{turn.text}
{turn.state === "streaming" ? <i className="aik-caret" /> : null}
</span>
)}
</div>
)
}
export interface AiBubbleThreadProps extends ThreadBase {
turns: AiTurn[]
}
/**
* A chat in bubbles. The agent's typing bubble opens out into its message,
* your messages launch up from the field, and a pill brings you back to the
* latest when you scroll away.
*/
export function AiBubbleThread({
turns,
height = 420,
onSend,
placeholder = "Reply",
className,
style,
...rest
}: AiBubbleThreadProps) {
const last = turns[turns.length - 1]
const stick = useStick(
`${turns.length}:${last?.text.length ?? 0}:${last?.state ?? ""}`
)
const fresh = useArrivals(turns.map((turn) => turn.id))
const [seen, setSeen] = React.useState(turns.length)
React.useEffect(() => {
if (!stick.away) setSeen(turns.length)
}, [stick.away, turns.length])
return (
<div
{...rest}
className={cx("aik aik-th", className)}
style={{ "--aik-th-h": `${height}px`, ...style } as React.CSSProperties}
>
<AiKitStyles />
<AiStyle id="ai-thread" css={CSS} />
<div className="aik-shell">
<div className="aik-surface aik-th-card">
<div className="aik-th-view">
<div
className="aik-th-scroll"
ref={stick.ref}
onScroll={stick.onScroll}
role="log"
aria-live="polite"
>
{turns.map((turn, at) => {
const before = turns[at - 1]
const cont =
before?.role === turn.role && before?.name === turn.name
const space =
at === 0 ? undefined : cont ? "aik-th-cont" : "aik-th-gap"
if (turn.role === "user")
return (
<React.Fragment key={turn.id}>
<div
className={cx("aik-th-u", space)}
data-new={fresh(turn.id) ? "" : undefined}
>
{turn.text}
</div>
{turn.meta ? (
<span className="aik-th-meta">{turn.meta}</span>
) : null}
</React.Fragment>
)
const next = turns[at + 1]
const tail = next?.role === "agent" && next.name === turn.name
return (
<div
key={turn.id}
className={cx("aik-th-a", space)}
data-cont={tail ? "" : undefined}
>
<Face
size={28}
shape={turn.shape ?? "orb"}
tone={turn.tone ?? "blue"}
mood={moodOf(turn)}
/>
<Bubble turn={turn} fresh={fresh(turn.id)} />
</div>
)
})}
</div>
<Jump
on={stick.away}
count={Math.max(0, turns.length - seen)}
onClick={() => stick.jump(true)}
/>
</div>
{onSend ? <Field onSend={onSend} placeholder={placeholder} /> : null}
</div>
</div>
</div>
)
}
export interface AiFlatThreadProps extends ThreadBase {
turns: AiTurn[]
}
/**
* A chat as a document. The agent's turns are flat text under a face and a
* name row, with tool chips and files inside the turn. Only you get a bubble.
*/
export function AiFlatThread({
turns,
height = 420,
onSend,
placeholder = "Reply",
className,
style,
...rest
}: AiFlatThreadProps) {
const last = turns[turns.length - 1]
const stick = useStick(
`${turns.length}:${last?.text.length ?? 0}:${last?.state ?? ""}`
)
const fresh = useArrivals(turns.map((turn) => turn.id))
return (
<div
{...rest}
className={cx("aik aik-th", className)}
style={{ "--aik-th-h": `${height}px`, ...style } as React.CSSProperties}
>
<AiKitStyles />
<AiStyle id="ai-thread" css={CSS} />
<div className="aik-shell">
<div className="aik-surface aik-th-card">
<div className="aik-th-view">
<div
className="aik-th-scroll"
ref={stick.ref}
onScroll={stick.onScroll}
role="log"
aria-live="polite"
>
{turns.map((turn, at) => {
const before = turns[at - 1]
const cont =
!turn.day &&
before?.role === turn.role &&
before?.name === turn.name
const space =
at === 0 || turn.day
? undefined
: cont
? "aik-th-cont"
: "aik-th-gap"
const rule = turn.day ? (
<div
className="aik-th-rule"
style={at === 0 ? { marginTop: 0 } : undefined}
>
{turn.day}
</div>
) : null
if (turn.role === "user")
return (
<React.Fragment key={turn.id}>
{rule}
<div
className={cx(
"aik-th-u",
turn.day ? "aik-th-gap" : space
)}
data-new={fresh(turn.id) ? "" : undefined}
>
{turn.text}
</div>
{turn.meta ? (
<span className="aik-th-meta">{turn.meta}</span>
) : null}
</React.Fragment>
)
return (
<React.Fragment key={turn.id}>
{rule}
<div
className={cx(
"aik-th-flat",
turn.day ? "aik-th-gap" : cont ? undefined : space
)}
style={cont ? { marginTop: 20 } : undefined}
data-new={fresh(turn.id) ? "" : undefined}
>
{cont ? null : (
<div className="aik-th-head">
<Face
size={28}
shape={turn.shape ?? "orb"}
tone={turn.tone ?? "blue"}
mood={moodOf(turn)}
/>
<b>{turn.name ?? "Agent"}</b>
{turn.model ? (
<span className="aik-th-model">{turn.model}</span>
) : null}
{turn.time ? <time>{turn.time}</time> : null}
</div>
)}
<div className="aik-th-reply">
{turn.state === "typing" ? (
<span className="aik-shimmer">Thinking</span>
) : turn.text ? (
<p>
{turn.text}
{turn.state === "streaming" ? (
<i className="aik-caret" />
) : null}
</p>
) : null}
{turn.artefacts}
</div>
</div>
</React.Fragment>
)
})}
</div>
<Jump on={stick.away} count={0} onClick={() => stick.jump(true)} />
</div>
{onSend ? <Field onSend={onSend} placeholder={placeholder} /> : null}
</div>
</div>
</div>
)
}
/** A row of artefacts inside a flat turn. */
export function AiTurnArtefacts({ children }: { children: React.ReactNode }) {
return <div className="aik-th-arts">{children}</div>
}
/** A tool call inside a flat turn: icon, name in mono, and a status mark. */
export function AiTurnChip({
icon,
status = "done",
children,
}: {
icon?: React.ReactNode
status?: AiStatus
children: React.ReactNode
}) {
return (
<span className="aik-th-chip" data-s={status}>
{icon}
{children}
<Mark status={status} />
</span>
)
}
/** A file an agent made, inside a flat turn. Shows a travelling edge light while `building`. */
export function AiTurnFile({
icon,
name,
detail,
building = false,
action,
}: {
icon?: React.ReactNode
name: string
detail?: string
building?: boolean
action?: React.ReactNode
}) {
return (
<div className="aik-th-file">
<span className="aik-th-ftile">{icon}</span>
<span className="aik-th-ftxt">
<b>{name}</b>
{detail ? <em>{detail}</em> : null}
</span>
{action}
<i className="aik-beam" data-on={building ? "" : undefined} />
</div>
)
}
export interface AiRoomAgent {
id: string
name: string
tone?: AiTone | (string & {})
shape?: AiShape
/** Shown as a mark on the agent's seat in the rail. */
status?: AiStatus
}
export interface AiRoomTurn {
id: string
/** An agent's id, or "you". */
from: string
text: string
time?: string
/** Indents the turn under the one before it, joined by a connector. */
reply?: boolean
/** An agent id: adds a chip passing work to that agent. */
handoff?: string
/** The handoff chip's text. */
handoffLabel?: string
}
export interface AiRoomThreadProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onSubmit"
> {
agents: AiRoomAgent[]
turns: AiRoomTurn[]
/** The id of the agent talking now. The ring in the rail moves to it. */
speaking?: string | null
/** A line under the thread naming who is working. */
presence?: string
height?: number
}
/**
* Several agents in one room. A rail of faces shows who is talking, replies
* thread under the turn they answer, and a chip hands work to the next agent.
*/
export function AiRoomThread({
agents,
turns,
speaking,
presence,
height = 420,
className,
style,
...rest
}: AiRoomThreadProps) {
const stick = useStick(turns.length)
const fresh = useArrivals(turns.map((turn) => turn.id))
const by = new Map(agents.map((agent) => [agent.id, agent]))
const at = agents.findIndex((agent) => agent.id === speaking)
const active = at >= 0 ? agents[at] : undefined
return (
<div
{...rest}
className={cx("aik aik-th aik-th-room", className)}
style={{ "--aik-th-h": `${height}px`, ...style } as React.CSSProperties}
>
<AiKitStyles />
<AiStyle id="ai-thread" css={CSS} />
<div className="aik-shell">
<div className="aik-surface aik-th-card">
<div className="aik-th-rail" aria-label="In this room">
<i
className="aik-th-ring"
data-off={active ? undefined : ""}
style={
{
"--i": Math.max(0, at),
"--c": toneColor(active?.tone ?? "blue"),
} as React.CSSProperties
}
/>
{agents.map((agent) => (
<span key={agent.id} className="aik-th-seat" title={agent.name}>
<Face
size={36}
shape={agent.shape ?? "blob"}
tone={agent.tone ?? "blue"}
mood={
agent.id === speaking
? "talk"
: agent.status === "run"
? "work"
: agent.status === "ask"
? "needs"
: agent.status === "done"
? "happy"
: "idle"
}
/>
{agent.status ? <Mark status={agent.status} /> : null}
</span>
))}
</div>
<div className="aik-th-view">
<div
className="aik-th-scroll"
ref={stick.ref}
onScroll={stick.onScroll}
role="log"
aria-live="polite"
>
{turns.map((turn, index) => {
const agent = by.get(turn.from)
const target = turn.handoff ? by.get(turn.handoff) : undefined
const color = agent
? toneColor(agent.tone ?? "blue")
: "var(--aik-text)"
return (
<div
key={turn.id}
className="aik-th-msg"
data-reply={turn.reply ? "" : undefined}
data-new={fresh(turn.id) ? "" : undefined}
style={
{
"--c": color,
marginTop:
index === 0 ? undefined : turn.reply ? 12 : 20,
} as React.CSSProperties
}
>
{agent ? (
<Face
size={22}
shape={agent.shape ?? "blob"}
tone={agent.tone ?? "blue"}
mood={turn.from === speaking ? "talk" : "idle"}
/>
) : (
<span className="aik-th-you">Y</span>
)}
<div>
<p>
<b>{agent?.name ?? "You"}</b>
{turn.text}
{turn.time ? <time>{turn.time}</time> : null}
</p>
{target ? (
<span
className="aik-th-hand"
style={
{
"--c": toneColor(target.tone ?? "blue"),
} as React.CSSProperties
}
>
<CornerDownRight size={14} />
<Face
size={18}
shape={target.shape ?? "blob"}
tone={target.tone ?? "blue"}
mood="listen"
/>
@{target.name}
{turn.handoffLabel ? (
<>
<ArrowRight size={13} />
<span className="aik-th-hl">
{turn.handoffLabel}
</span>
</>
) : null}
</span>
) : null}
</div>
</div>
)
})}
</div>
<Jump on={stick.away} count={0} onClick={() => stick.jump(true)} />
</div>
<div className="aik-th-pres" role="status">
{presence ? (
<>
<Mark status="run" />
<span className="aik-shimmer">{presence}</span>
</>
) : (
<span>Everyone is idle</span>
)}
</div>
</div>
</div>
</div>
)
}
Installation
One command adds ai-thread 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/ai-thread.json
ai-thread-demo
"use client"
import * as React from "react"
import { ArrowUpRight, FileCode, FileSearch, Search } from "lucide-react"
import { AiDemo } from "@/lib/ai-demo"
import {
paceToken,
useAiLoop,
useIdleHands,
type AiStatus,
} from "@/lib/ai-kit"
import {
AiBubbleThread,
AiFlatThread,
AiRoomThread,
AiTurnArtefacts,
AiTurnChip,
AiTurnFile,
type AiRoomAgent,
type AiRoomTurn,
type AiTurn,
} from "@/registry/tween/ai-thread"
type Sleep = (ms: number) => Promise<void>
const wait: Sleep = (ms) =>
new Promise((resolve) => window.setTimeout(resolve, ms))
const HISTORY: AiTurn[] = [
{ id: "h1", role: "user", text: "Add a pricing section under the hero." },
{
id: "h2",
role: "agent",
name: "Mira",
text: "On it. I will reuse text-skew-reveal for the heading, so there is no new dependency.",
},
]
const FOLLOW = "Keep the monthly and yearly toggle."
const ANSWER =
"Kept. The toggle switches prices with a 180ms state change, and the saving badge rolls over when you pick yearly."
const WRAP: React.CSSProperties = { display: "grid", width: "min(100%, 560px)" }
function Bubbles() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [turns, setTurns] = React.useState<AiTurn[]>(HISTORY)
const run = React.useRef(0)
const serial = React.useRef(0)
const answer = React.useCallback(async (sleep: Sleep, mine: number) => {
const alive = () => run.current === mine
const id = `a${++serial.current}`
await sleep(700)
if (!alive()) return
setTurns((list) => [
...list.map((turn) =>
turn.role === "user" && turn.meta ? { ...turn, meta: "Read" } : turn
),
{ id, role: "agent", name: "Mira", text: "", state: "typing" },
])
await sleep(1600)
let text = ""
for (const word of ANSWER.split(" ")) {
if (!alive()) return
text += (text ? " " : "") + word
const next = text
setTurns((list) =>
list.map((turn) =>
turn.id === id ? { ...turn, text: next, state: "streaming" } : turn
)
)
await sleep(paceToken(word, 36))
}
if (!alive()) return
setTurns((list) =>
list.map((turn) => (turn.id === id ? { ...turn, state: "done" } : turn))
)
}, [])
useAiLoop(
root,
async ({ sleep }) => {
const mine = ++run.current
setTurns(HISTORY)
await sleep(1400)
setTurns((list) => [
...list,
{
id: `u${++serial.current}`,
role: "user",
text: FOLLOW,
meta: "Delivered",
},
])
await answer(sleep, mine)
await sleep(2600)
},
{ gap: 400, enabled: !hands }
)
return (
<div ref={root} style={WRAP} onPointerDown={touch} onKeyDown={touch}>
<AiBubbleThread
turns={turns}
placeholder="Reply to Mira"
onSend={(text) => {
const mine = ++run.current
setTurns((list) => [
...list.slice(-5).map((turn) => ({ ...turn, meta: undefined })),
{
id: `u${++serial.current}`,
role: "user",
text,
meta: "Delivered",
},
])
void answer(wait, mine)
}}
/>
</div>
)
}
const FLAT_TEXT =
"The section is written. It sits under the hero and reuses the reveal you already ship, so nothing new was installed."
interface FlatScene {
text: string
state: AiTurn["state"]
chips: Array<[string, AiStatus]>
file: "none" | "building" | "ready"
second: boolean
}
function Flat() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [scene, setScene] = React.useState<FlatScene>({
text: FLAT_TEXT,
state: "done",
chips: [
["read_file", "done"],
["search_registry", "done"],
],
file: "ready",
second: true,
})
const [extra, setExtra] = React.useState<AiTurn[]>([])
const run = React.useRef(0)
useAiLoop(
root,
async ({ sleep }) => {
++run.current
setExtra([])
const base: FlatScene = {
text: "",
state: "typing",
chips: [],
file: "none",
second: false,
}
setScene(base)
await sleep(1100)
setScene({ ...base, chips: [["read_file", "run"]] })
await sleep(900)
setScene({
...base,
chips: [
["read_file", "done"],
["search_registry", "run"],
],
})
await sleep(900)
const chips: FlatScene["chips"] = [
["read_file", "done"],
["search_registry", "done"],
]
let text = ""
for (const word of FLAT_TEXT.split(" ")) {
text += (text ? " " : "") + word
setScene({ ...base, chips, text, state: "streaming" })
await sleep(paceToken(word, 34))
}
setScene({ ...base, chips, text, state: "done", file: "building" })
await sleep(1700)
setScene({ ...base, chips, text, state: "done", file: "ready" })
await sleep(900)
setScene({
...base,
chips,
text,
state: "done",
file: "ready",
second: true,
})
await sleep(2800)
},
{ gap: 400, enabled: !hands }
)
const turns: AiTurn[] = [
{
id: "f1",
role: "user",
day: "Today",
text: "Add a pricing section under the hero.",
},
{
id: "f2",
role: "agent",
name: "Mira",
model: "tween-fast",
time: "9:41",
text: scene.text,
state: scene.state,
artefacts: (
<>
{scene.chips.length > 0 ? (
<AiTurnArtefacts>
{scene.chips.map(([name, status]) => (
<AiTurnChip
key={name}
status={status}
icon={
name === "read_file" ? (
<FileSearch size={14} />
) : (
<Search size={14} />
)
}
>
{name}
</AiTurnChip>
))}
</AiTurnArtefacts>
) : null}
{scene.file === "none" ? null : (
<AiTurnFile
icon={<FileCode size={18} />}
name="pricing-section.tsx"
detail={
scene.file === "building"
? "Writing 148 lines"
: "148 lines · React"
}
building={scene.file === "building"}
action={
scene.file === "ready" ? (
<button type="button" className="aik-btn sm line">
Open
<ArrowUpRight size={14} />
</button>
) : null
}
/>
)}
</>
),
},
...(scene.second
? [
{
id: "f3",
role: "agent" as const,
name: "Odo",
tone: "violet",
shape: "blob" as const,
model: "tween-deep",
time: "9:42",
text: "Reviewed it. The toggle is keyboard reachable and the type check passes.",
},
]
: []),
...extra,
]
return (
<div ref={root} style={WRAP} onPointerDown={touch} onKeyDown={touch}>
<AiFlatThread
turns={turns}
placeholder="Reply to Mira"
onSend={(text) => {
const mine = ++run.current
const id = `x${mine}`
setExtra((list) => [
...list.slice(-2),
{ id: `u${id}`, role: "user", text },
{
id,
role: "agent",
name: "Mira",
model: "tween-fast",
text: "",
state: "typing",
},
])
void (async () => {
await wait(1200)
let reply = ""
for (const word of ANSWER.split(" ")) {
if (run.current !== mine) return
reply += (reply ? " " : "") + word
const next = reply
setExtra((list) =>
list.map((turn) =>
turn.id === id
? { ...turn, text: next, state: "streaming" }
: turn
)
)
await wait(paceToken(word, 34))
}
setExtra((list) =>
list.map((turn) =>
turn.id === id ? { ...turn, state: "done" } : turn
)
)
})()
}}
/>
</div>
)
}
const CAST: AiRoomAgent[] = [
{ id: "mira", name: "Mira", tone: "blue", shape: "orb" },
{ id: "odo", name: "Odo", tone: "violet", shape: "blob" },
{ id: "juno", name: "Juno", tone: "amber", shape: "arch" },
{ id: "pim", name: "Pim", tone: "green", shape: "leaf" },
]
interface Beat {
turn: AiRoomTurn
speaking: string | null
presence?: string
status: Record<string, AiStatus | undefined>
}
const BEATS: Beat[] = [
{
turn: {
id: "r1",
from: "you",
text: "Ship the pricing section today.",
time: "9:40",
},
speaking: null,
status: {},
},
{
turn: {
id: "r2",
from: "mira",
text: "I will write the section and the toggle.",
},
speaking: "mira",
presence: "Mira is working",
status: { mira: "run" },
},
{
turn: {
id: "r3",
from: "odo",
text: "I can write the tests while you build.",
reply: true,
},
speaking: "odo",
presence: "Mira and Odo are working",
status: { mira: "run", odo: "run" },
},
{
turn: {
id: "r4",
from: "mira",
text: "The section is in.",
handoff: "odo",
handoffLabel: "run the 24 tests",
},
speaking: "mira",
presence: "Odo is working",
status: { mira: "done", odo: "run" },
},
{
turn: {
id: "r5",
from: "odo",
text: "All 24 pass.",
handoff: "juno",
handoffLabel: "review before merge",
},
speaking: "odo",
presence: "Juno is working",
status: { mira: "done", odo: "done", juno: "run" },
},
{
turn: {
id: "r6",
from: "juno",
text: "Reviewed. One contrast fix on the badge, then it is ready.",
},
speaking: "juno",
status: { mira: "done", odo: "done", juno: "done" },
},
]
function Room() {
const root = React.useRef<HTMLDivElement>(null)
const [hands, touch] = useIdleHands()
const [count, setCount] = React.useState(4)
useAiLoop(
root,
async ({ sleep }) => {
setCount(1)
await sleep(1200)
for (let at = 2; at <= BEATS.length; at++) {
setCount(at)
await sleep(2000)
}
await sleep(1600)
},
{ gap: 400, enabled: !hands, still: () => setCount(5) }
)
const beat = BEATS[count - 1] ?? BEATS[0]!
return (
<div
ref={root}
style={WRAP}
onPointerDown={() => {
touch()
setCount((value) => (value >= BEATS.length ? 1 : value + 1))
}}
onKeyDown={touch}
>
<AiRoomThread
agents={CAST.map((agent) => ({
...agent,
status: beat.status[agent.id],
}))}
turns={BEATS.slice(0, count).map((item) => item.turn)}
speaking={beat.speaking}
presence={beat.presence}
/>
</div>
)
}
export function AiThreadDemo({ only }: { only?: string }) {
return (
<AiDemo
only={only}
tabs={[
{ name: "Bubbles", node: <Bubbles /> },
{ name: "Flat", node: <Flat /> },
{ name: "Room", node: <Room /> },
]}
/>
)
}
Installation
Usage
import {
AiBubbleThread,
AiFlatThread,
AiRoomThread,
AiTurnArtefacts,
AiTurnChip,
AiTurnFile,
} from "@/components/ui/ai-thread"<AiBubbleThread
turns={[
{ id: "1", role: "user", text: "Add a pricing section.", meta: "Read" },
{ id: "2", role: "agent", name: "Mira", text: "", state: "typing" },
]}
onSend={(text) => send(text)}
/>A turn's state maps onto a stream: typing before the first token, streaming while text arrives, done after.
Versions
AiBubbleThreadis a chat in bubbles. The agent's typing bubble opens out into its message, your messages launch up from the field, and a Latest pill appears when you scroll away from the end.AiFlatThreadreads like a document. An agent turn is flat text under a face, a name, a model chip and a time, with the reply indented beneath. Tool chips and files sit inside the turn throughartefacts, anddaydraws a date rule. Only you get a bubble.AiRoomThreadholds several agents. A rail of faces shows who is talking with a ring that moves between them, replies thread under the turn they answer, and a handoff chip passes work to the next agent.
Each thread scrolls inside itself and stays pinned to the end until the reader scrolls up.
Props
AiBubbleThread and AiFlatThread
| Prop | Type | Default | Description |
|---|---|---|---|
turns | AiTurn[] | The conversation, oldest first. | |
height | number | 420 | Height in pixels. The thread scrolls inside it. |
onSend | (text: string) => void | Called from the reply field. The field hides when omitted. | |
placeholder | string | "Reply" | The reply field's placeholder. |
AiTurn
| Field | Type | Description |
|---|---|---|
id | string | Stable key. |
role | "user" | "agent" | Who is speaking. |
text | string | The message so far. |
name | string | The agent's name. Same-name turns are grouped. |
tone | tone or CSS colour | The face's colour. |
state | "typing" | "streaming" | "done" | Dots, a caret after the text, or settled. |
time | string | Already formatted. |
meta | string | A line under a user turn, such as "Read". |
model | string | Flat only: the model chip. |
day | string | Flat only: a date rule above this turn. |
artefacts | ReactNode | Flat only: chips and files inside the turn. |
AiRoomThread
| Prop | Type | Default | Description |
|---|---|---|---|
agents | { id, name, tone?, shape?, status? }[] | Who is in the room, in rail order. | |
turns | { id, from, text, time?, reply?, handoff?, handoffLabel? }[] | from is an agent id or "you". | |
speaking | string | null | The agent talking now. The ring moves to it. | |
presence | string | A line naming who is working. | |
height | number | 420 | Height in pixels. |