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.

Installation

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
components/ui/ai-thread-demo.tsx
"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

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-thread.json

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

  • AiBubbleThread is 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.
  • AiFlatThread reads 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 through artefacts, and day draws a date rule. Only you get a bubble.
  • AiRoomThread holds 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

PropTypeDefaultDescription
turnsAiTurn[]The conversation, oldest first.
heightnumber420Height in pixels. The thread scrolls inside it.
onSend(text: string) => voidCalled from the reply field. The field hides when omitted.
placeholderstring"Reply"The reply field's placeholder.

AiTurn

FieldTypeDescription
idstringStable key.
role"user" | "agent"Who is speaking.
textstringThe message so far.
namestringThe agent's name. Same-name turns are grouped.
tonetone or CSS colourThe face's colour.
state"typing" | "streaming" | "done"Dots, a caret after the text, or settled.
timestringAlready formatted.
metastringA line under a user turn, such as "Read".
modelstringFlat only: the model chip.
daystringFlat only: a date rule above this turn.
artefactsReactNodeFlat only: chips and files inside the turn.

AiRoomThread

PropTypeDefaultDescription
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".
speakingstring | nullThe agent talking now. The ring moves to it.
presencestringA line naming who is working.
heightnumber420Height in pixels.