AI Composer

Three ways to ask an agent: a chat dock where a light travels round the card while the agent works, a pill that opens in place into a full prompt, and a command palette with a live preview pane.

Installation

Installation

One command adds ai-composer 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-composer.json
ai-composer-demo
components/ui/ai-composer-demo.tsx
"use client"

import * as React from "react"
import {
  BookOpen,
  Brain,
  FileCode,
  FolderOpen,
  GitPullRequest,
  Globe,
  Rocket,
  Wrench,
} from "lucide-react"

import { AiDemo } from "@/lib/ai-demo"
import {
  AiStyle,
  Face,
  paceToken,
  typeInto,
  useAiLoop,
  useIdleHands,
  type AiMood,
} from "@/lib/ai-kit"
import {
  AiCommandPalette,
  AiComposer,
  AiPromptPill,
  type AiComposerAttachment,
  type AiPaletteGroup,
  type AiPaletteItem,
} from "@/registry/tween/ai-composer"

const CSS = `
.aik-cpd-scene{display:grid;gap:14px;width:min(100%,560px)}
.aik-cpd-thread{display:flex;flex-direction:column;justify-content:flex-end;gap:12px;min-height:176px;padding:0 6px}
.aik-cpd-user{align-self:flex-end;max-width:78%;padding:10px 16px;border-radius:18px;background:var(--aik-raised);font-size:15px;line-height:22px;transform-origin:100% 100%;animation:aik-cpd-launch 520ms var(--aik-ease-move) both}
.aik-cpd-bot{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;align-items:start;font-size:15px;line-height:24px;animation:aik-in var(--aik-d-enter) var(--aik-ease-out) both}
.aik-cpd-bot p{padding-top:2px}
.aik-cpd-bot code{font-size:13px;padding:2px 5px;border-radius:6px;background:var(--aik-raised)}
@keyframes aik-cpd-launch{from{opacity:.2;transform:translateY(96px) scale(.9)}}
.aik-cpd-art{position:absolute;inset:0;background:radial-gradient(80% 90% at 20% 20%,var(--aik-f-amber),transparent 60%),radial-gradient(90% 90% at 85% 80%,var(--aik-f-rose),transparent 62%),var(--aik-f-violet)}
.aik-cpd-pill{display:grid;align-content:start;justify-items:center;width:min(100%,540px);min-height:236px}
@media (prefers-reduced-motion: reduce){.aik-cpd-user{animation:none}}
`

const PROMPT = "Make the headline reveal word by word"
const REPLY =
  "Done. The headline now uses text-skew-reveal with a 0.05s stagger, so the whole line lands in under a second."

interface Turn {
  id: number
  role: "user" | "bot"
  text: string
}

function Dock() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [value, setValue] = React.useState("")
  const [files, setFiles] = React.useState<AiComposerAttachment[]>([])
  const [mode, setMode] = React.useState("Ask")
  const [status, setStatus] = React.useState<"ready" | "streaming">("ready")
  const [context, setContext] = React.useState(12)
  const [turns, setTurns] = React.useState<Turn[]>([])
  const [mood, setMood] = React.useState<AiMood>("idle")
  const run = React.useRef(0)

  // Plays the agent's reply. Shared by the script and by a real send.
  const respond = React.useCallback(
    async (sleep: (ms: number) => Promise<void>, mine: number) => {
      const alive = () => run.current === mine
      setStatus("streaming")
      setMood("think")
      await sleep(1100)
      if (!alive()) return
      const id = Date.now()
      setMood("talk")
      setTurns((list) => [...list.slice(-1), { id, role: "bot", text: "" }])
      let text = ""
      for (const word of REPLY.split(" ")) {
        if (!alive()) return
        text += (text ? " " : "") + word
        const next = text
        setTurns((list) =>
          list.map((turn) => (turn.id === id ? { ...turn, text: next } : turn))
        )
        await sleep(paceToken(word, 38))
      }
      if (!alive()) return
      setStatus("ready")
      setMood("happy")
      setContext((value) => Math.min(96, value + 7))
    },
    []
  )

  useAiLoop(
    root,
    async ({ sleep }) => {
      const mine = ++run.current
      setTurns([])
      setFiles([])
      setValue("")
      setMode("Ask")
      setStatus("ready")
      setContext(12)
      setMood("idle")
      await sleep(700)
      for (const progress of [0.15, 0.45, 0.8, 1]) {
        setFiles([
          {
            id: "hero",
            name: "hero.tsx",
            kind: "code",
            meta: "4 KB",
            progress,
          },
        ])
        await sleep(240)
      }
      setContext(18)
      await typeInto(setValue, PROMPT, sleep)
      await sleep(350)
      setMode("Build")
      await sleep(900)
      setTurns([{ id: 1, role: "user", text: PROMPT }])
      setValue("")
      setFiles([])
      await respond(sleep, mine)
      await sleep(2200)
    },
    { gap: 400, enabled: !hands }
  )

  // The first touch takes over from the script: whatever it was mid-way through is cancelled.
  const takeOver = () => {
    if (!hands) {
      run.current++
      setStatus("ready")
      setMood("idle")
    }
    touch()
  }

  const send = (text: string) => {
    const mine = ++run.current
    setTurns([{ id: Date.now(), role: "user", text }])
    setValue("")
    setFiles([])
    void respond(
      (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
      mine
    )
  }

  return (
    <div
      ref={root}
      className="aik-cpd-scene"
      onPointerDown={takeOver}
      onKeyDown={takeOver}
    >
      <div className="aik-cpd-thread" aria-live="polite">
        {turns.map((turn) =>
          turn.role === "user" ? (
            <div key={turn.id} className="aik-cpd-user">
              {turn.text}
            </div>
          ) : (
            <div key={turn.id} className="aik-cpd-bot">
              <Face size={28} shape="orb" mood={mood} />
              <p>
                {turn.text}
                {status === "streaming" ? <i className="aik-caret" /> : null}
              </p>
            </div>
          )
        )}
      </div>
      <AiComposer
        value={value}
        onValueChange={setValue}
        status={status}
        attachments={files}
        onRemoveAttachment={(id) =>
          setFiles((list) => list.filter((file) => file.id !== id))
        }
        onAttach={() =>
          setFiles((list) =>
            list.some((file) => file.id === "ref")
              ? list
              : [
                  ...list,
                  {
                    id: "ref",
                    name: "reference.png",
                    kind: "image",
                    meta: "1.8 MB",
                    preview: <span className="aik-cpd-art" />,
                  },
                ]
          )
        }
        modes={["Ask", "Plan", "Build"]}
        mode={mode}
        onModeChange={setMode}
        agent={{ name: "Mira", detail: "fast", mood }}
        context={context}
        placeholder="Ask Mira to build something"
        streamingPlaceholder="Mira is working. Esc to stop."
        onSubmit={send}
        onStop={() => {
          run.current++
          setStatus("ready")
          setMood("idle")
        }}
      />
    </div>
  )
}

const PILL_STEPS = ["Reading hero.tsx", "Rewriting 3 lines", "Checking types"]

function Pill() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [open, setOpen] = React.useState(false)
  const [value, setValue] = React.useState("")
  const [status, setStatus] = React.useState<"idle" | "running" | "done">(
    "idle"
  )
  const [label, setLabel] = React.useState("")
  const [tools, setTools] = React.useState({
    web: false,
    files: true,
    think: false,
  })
  const run = React.useRef(0)

  const work = React.useCallback(
    async (sleep: (ms: number) => Promise<void>, mine: number) => {
      setOpen(false)
      setValue("")
      setStatus("running")
      for (const step of PILL_STEPS) {
        if (run.current !== mine) return
        setLabel(step)
        await sleep(1300)
      }
      if (run.current !== mine) return
      setStatus("done")
      setLabel("Done · 3 lines changed")
      await sleep(2000)
      if (run.current !== mine) return
      setStatus("idle")
    },
    []
  )

  useAiLoop(
    root,
    async ({ sleep }) => {
      const mine = ++run.current
      setOpen(false)
      setStatus("idle")
      setValue("")
      setTools({ web: false, files: true, think: false })
      await sleep(1200)
      setOpen(true)
      await sleep(900)
      await typeInto(setValue, "Tighten the hero copy", sleep, 32)
      await sleep(400)
      setTools({ web: false, files: true, think: true })
      await sleep(900)
      await work(sleep, mine)
      await sleep(600)
    },
    { gap: 300, enabled: !hands }
  )

  return (
    <div
      ref={root}
      className="aik-cpd-pill"
      onPointerDown={() => {
        if (!hands) {
          run.current++
          setStatus("idle")
        }
        touch()
      }}
      onKeyDown={touch}
    >
      <AiPromptPill
        open={open}
        onOpenChange={setOpen}
        value={value}
        onValueChange={setValue}
        status={status}
        statusLabel={label}
        label="Ask Mira anything"
        suggestions={[
          "Tighten the hero copy",
          "Add a pricing section with a toggle",
          "Explain how text-skew-reveal works",
        ]}
        tools={[
          { id: "web", label: "Web", icon: <Globe size={14} />, on: tools.web },
          {
            id: "files",
            label: "Project files",
            icon: <FolderOpen size={14} />,
            on: tools.files,
          },
          {
            id: "think",
            label: "Think longer",
            icon: <Brain size={14} />,
            on: tools.think,
          },
        ]}
        onToggleTool={(id) =>
          setTools((state) => ({
            ...state,
            [id]: !state[id as keyof typeof state],
          }))
        }
        onSubmit={() => {
          const mine = ++run.current
          void work(
            (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
            mine
          )
        }}
      />
    </div>
  )
}

const GROUPS: AiPaletteGroup[] = [
  {
    label: "Commands",
    items: [
      {
        id: "build",
        title: "Build a section",
        hint: "/build",
        icon: <Rocket size={16} />,
        description:
          "Describe a section and Mira writes it with components already in your registry.",
        facts: [
          ["Agent", "Mira"],
          ["Usually", "40 s"],
        ],
      },
      {
        id: "fix",
        title: "Fix lint and type errors",
        hint: "/fix",
        icon: <Wrench size={16} />,
        description:
          "Runs the checks, fixes what it can and lists what needs you.",
        facts: [
          ["Open errors", "14"],
          ["Files", "6"],
        ],
      },
      {
        id: "review",
        title: "Review open changes",
        hint: "/review",
        icon: <GitPullRequest size={16} />,
        description:
          "Odo reads the diff and leaves comments on anything risky.",
        facts: [
          ["Agent", "Odo"],
          ["Changed", "+126 −8"],
        ],
      },
    ],
  },
  {
    label: "Files",
    items: [
      {
        id: "pricing",
        title: "pricing-section.tsx",
        hint: "components",
        icon: <FileCode size={16} />,
        description: "The pricing section with a monthly and yearly toggle.",
        facts: [
          ["Lines", "148"],
          ["Edited", "2 min ago"],
        ],
      },
      {
        id: "docs",
        title: "text-skew-reveal.mdx",
        hint: "docs",
        icon: <BookOpen size={16} />,
        description: "Docs page for the skewed word-by-word reveal.",
        facts: [
          ["Lines", "92"],
          ["Edited", "yesterday"],
        ],
      },
    ],
  },
]

function Palette() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [query, setQuery] = React.useState("")
  const [active, setActive] = React.useState<string | undefined>("build")
  const [status, setStatus] = React.useState<"idle" | "running" | "done">(
    "idle"
  )
  const [label, setLabel] = React.useState("")
  const run = React.useRef(0)

  const launch = React.useCallback(
    async (
      item: AiPaletteItem,
      sleep: (ms: number) => Promise<void>,
      mine: number
    ) => {
      setStatus("running")
      setLabel(`Running: ${item.title}`)
      await sleep(2400)
      if (run.current !== mine) return
      setStatus("done")
      setLabel(`Finished: ${item.title}`)
      await sleep(1700)
      if (run.current !== mine) return
      setStatus("idle")
      setQuery("")
    },
    []
  )

  useAiLoop(
    root,
    async ({ sleep }) => {
      const mine = ++run.current
      setStatus("idle")
      setQuery("")
      setActive("build")
      await sleep(1100)
      for (const id of ["fix", "review", "pricing", "docs", "pricing"]) {
        setActive(id)
        await sleep(780)
      }
      await typeInto(setQuery, "fix", sleep, 90)
      setActive("fix")
      await sleep(900)
      const item = GROUPS[0]?.items[1]
      if (item) await launch(item, sleep, mine)
    },
    { gap: 500, enabled: !hands }
  )

  return (
    <div
      ref={root}
      style={{ display: "grid", width: "min(100%, 580px)" }}
      onPointerDown={() => {
        if (!hands) {
          run.current++
          setStatus("idle")
        }
        touch()
      }}
      onKeyDown={touch}
    >
      <AiCommandPalette
        groups={GROUPS}
        query={query}
        onQueryChange={setQuery}
        active={hands ? undefined : active}
        status={status}
        statusLabel={label}
        onRun={(item) => {
          const mine = ++run.current
          void launch(
            item,
            (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)),
            mine
          )
        }}
      />
    </div>
  )
}

export function AiComposerDemo({ only }: { only?: string }) {
  return (
    <>
      <AiStyle id="ai-composer-demo" css={CSS} />
      <AiDemo
        only={only}
        tabs={[
          { name: "Dock", node: <Dock /> },
          { name: "Prompt pill", node: <Pill /> },
          { name: "Command palette", node: <Palette /> },
        ]}
      />
    </>
  )
}

Installation

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

Usage

import {
  AiCommandPalette,
  AiComposer,
  AiPromptPill,
} from "@/components/ui/ai-composer"
const [value, setValue] = useState("")
const [status, setStatus] = useState<"ready" | "streaming">("ready")
 
<AiComposer
  value={value}
  onValueChange={setValue}
  status={status}
  modes={["Ask", "Plan", "Build"]}
  mode={mode}
  onModeChange={setMode}
  agent={{ name: "Mira", detail: "fast" }}
  context={18}
  onSubmit={(text) => {
    setStatus("streaming")
    setValue("")
    send(text)
  }}
  onStop={() => setStatus("ready")}
/>

status maps directly onto the AI SDK: pass "streaming" while useChat reports submitted or streaming, and "ready" otherwise.

Versions

  • AiComposer is the chat dock: a rim holding one card. Attachments sit in a tray with an upload ring, the field grows with its text, and a mode switch slides between Ask, Plan and Build. Enter sends and Shift Enter adds a line. While streaming, send becomes stop in place, a light travels round the card's edge, and Escape stops the run.
  • AiPromptPill lives as a small pill and opens in place into a full prompt with suggestions and tool toggles. After sending it folds back, and the pill itself reports progress with statusLabel.
  • AiCommandPalette is one search over commands, files and agents. A highlight slides between rows as you arrow through them, and a preview pane describes the current row. While a command runs, the search row becomes the status line.

Props

AiComposer

PropTypeDefaultDescription
valuestringThe field's text.
onValueChange(value: string) => voidCalled on every edit.
onSubmit(value: string) => voidCalled with the trimmed text on Enter or send.
onStop() => voidCalled on send or Escape while streaming.
status"ready" | "streaming""ready"Streaming turns send into stop and starts the edge light.
attachments{ id, name, kind?, meta?, progress?, preview? }[][]Tray chips. progress from 0 to 1 shows an upload ring.
onRemoveAttachment(id: string) => voidCalled from a chip's remove button.
modesstring[]Names for the segmented mode switch.
modestringThe selected mode.
onModeChange(mode: string) => voidCalled when a mode is picked.
agent{ name, detail?, tone?, shape?, mood? }The agent chip. Its face listens while you type.
contextnumberContext use from 0 to 100, as a pie on the agent chip.
bannerReactNodeA row docked in the frame above the card.
disabledbooleanfalseDims the dock and blocks input.

AiPromptPill

PropTypeDefaultDescription
openbooleanWhether the pill is opened into the full prompt.
onOpenChange(open: boolean) => voidCalled on click, and on Escape.
valuestringThe prompt text.
onSubmit(value: string) => voidCalled on Enter, send, or a suggestion.
status"idle" | "running" | "done""idle"Running and done show statusLabel in the pill.
statusLabelstringWhat the pill says while it works.
labelstring"Ask anything"The resting label and placeholder.
suggestionsstring[][]One-tap prompts in the open pill.
tools{ id, label, icon?, on }[][]Toggles along the bottom.
onToggleTool(id: string) => voidCalled when a toggle is pressed.

AiCommandPalette

PropTypeDefaultDescription
groups{ label, items }[]Items take id, title, hint, icon, description and facts.
querystringThe search text. Filtering is built in.
onQueryChange(query: string) => voidCalled on every edit.
onRun(item) => voidCalled on Enter or a click.
activestringControls the highlighted item. Omit to use arrow keys.
status"idle" | "running" | "done""idle"Running and done replace the search field.
statusLabelstringThe status line's text.