Chat
The thread of a conversation with the agent, with a scroller that keeps the reader's place while a reply streams.
Installation
pnpm dlx shadcn@latest add @silkware/ai-chatTo copy the pattern by hand, install the components it composes:
pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/code-block @silkware/dropdown-menu @silkware/empty @silkware/input-group @silkware/message @silkware/message-scroller @silkware/tooltip @silkware/traceThen install the packages it imports:
pnpm add ai @ai-sdk/react @shadcn/helpers streamdown lucide-reactThe pattern also imports @/lib/ai (the scripted streams) and @/components/markdown (renders the reply as Markdown, set with the typeset-chat preset of Typeset, which the markdown item brings). Copy both from the repository, then copy the pattern into components/ai-elements/chat.tsx:
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import { ArrowUpIcon, CircleCheckIcon, GlobeIcon, LoaderCircleIcon, MessageCircleDashedIcon, PaperclipIcon, PlusIcon, RotateCwIcon, TelescopeIcon, TerminalIcon,} from "lucide-react"import { motion, useReducedMotion, type Variants } from "motion/react"
import { createChat, getMessageText } from "@/lib/ai"import { Markdown } from "@/components/markdown"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { DropdownMenu, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,} from "@/components/ui/empty"import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextarea,} from "@/components/ui/input-group"import { Message, MessageContent } from "@/components/ui/message"import { MessageScroller, MessageScrollerButton, MessageScrollerContent, MessageScrollerItem, MessageScrollerProvider, MessageScrollerViewport,} from "@/components/ui/message-scroller"import { Tooltip, TooltipTrigger } from "@/components/ui/tooltip"import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage< unknown, UIDataTypes, { runCommand: { input: { command: string } output: { stdout: string } } }>
type ChatPart = ChatMessage["parts"][number]
type ToolPart = Extract<ChatPart, { type: "tool-runCommand" }>
const chat = createChat<ChatMessage>() .user("Add a dark mode toggle to the settings page.") .sleep(600) .assistant(({ writer }) => { writer.reasoning( "I need to know how themes are set up before I add a toggle. If next-themes is already in the layout, the toggle only has to call setTheme." ) writer.sleep(400) writer .tool("runCommand", { input: { command: "rg -l ThemeProvider app" } }) .sleep(800) .output({ stdout: "app/layout.tsx" }) writer.sleep(500) writer.text(`next-themes is already set up in \`app/layout.tsx\`, so the toggle only has to call \`setTheme\`.
**Changes**
- Added \`components/mode-toggle.tsx\` with a Light and Dark option.- Put \`<ModeToggle />\` next to the Appearance heading in \`app/settings/page.tsx\`.
\`\`\`tsxconst { setTheme } = useTheme()\`\`\``) }) .user("Make it follow the system setting by default.") .sleep(600) .assistant(({ writer }) => { writer.reasoning( "The default theme lives on the ThemeProvider. I should check what it is set to now." ) writer.sleep(400) writer .tool("runCommand", { input: { command: "rg -n defaultTheme app/layout.tsx" }, }) .sleep(800) .output({ stdout: '12: <ThemeProvider attribute="class" defaultTheme="light">', }) writer.sleep(500) writer.text(`It was set to \`light\`. I updated the \`ThemeProvider\` in \`app/layout.tsx\`:
\`\`\`tsx<ThemeProvider attribute="class" defaultTheme="system" enableSystem>\`\`\`
New visitors now get the theme from their OS. The toggle also has a **System** option, so anyone who picked Light or Dark can switch back.`) }) .user("Run the build before I ship it.") .sleep(600) .assistant(({ writer }) => { writer .tool("runCommand", { input: { command: "pnpm build" } }) .sleep(1600) .output({ stdout: "▲ Next.js 16.0.0\n\n✓ Compiled successfully in 4.2s\n✓ Linting and checking validity of types\n✓ Generating static pages (12/12)", }) writer.sleep(500) writer.text(`The build passes, so it is ready to ship.
- Compiled in **4.2s**.- No lint or type errors.- Generated all **12** static pages.`) })
const slideUp: Variants = { initial: { opacity: 0, y: 10 }, animate: { opacity: 1, y: 0, transition: { duration: 0.26, ease: [0.16, 1, 0.3, 1] }, }, exit: { opacity: 0, y: 4, transition: { duration: 0.15 } },}
const initialMessages = chat.get(0)const transport = chat.transport({ delayMs: 16, fallback: "This demo only knows the scripted turns. Press reset to start over.",})
const MotionMessageScrollerItem = motion.create(MessageScrollerItem)
export function ChatDemo() { const { messages, sendMessage, setMessages, status } = useChat({ messages: initialMessages, transport, throttle: 50, }) const [draft, setDraft] = React.useState<string | null>(null) const formRef = React.useRef<HTMLFormElement>(null) const shouldReduceMotion = useReducedMotion() const nextMessage = chat.next(messages) const busy = status === "submitted" || status === "streaming" const text = draft ?? (nextMessage ? getMessageText(nextMessage) : "") const canSend = text.trim().length > 0 && !busy
function onSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault() if (!canSend) { return }
if (draft === null && nextMessage) { void sendMessage(nextMessage) } else { void sendMessage({ text: text.trim() }) } setDraft(null) }
return ( <MessageScrollerProvider> <div className="relative flex w-full flex-col gap-4 [[data-slot=preview]:has(&)]:bg-background [[data-slot=preview]:has(&)>div]:p-0!"> <div className="flex h-200 w-full flex-col gap-4"> <div className="flex items-start justify-between gap-4 p-8 pb-4"> <div className="flex flex-col gap-1"> <div className="font-medium">New Thread</div> <div className="text-sm text-muted-foreground"> Ask the agent to change your code. </div> </div> <TooltipTrigger> <Button variant="outline" size="icon" aria-label="Reset conversation" onPress={() => { setMessages(initialMessages) setDraft(null) }} isDisabled={busy} > <RotateCwIcon /> </Button> <Tooltip> <p>Reset</p> </Tooltip> </TooltipTrigger> </div> <div className="min-h-0 flex-1"> {messages.length === 0 ? ( <Empty className="h-full"> <EmptyHeader> <EmptyMedia variant="icon"> <MessageCircleDashedIcon /> </EmptyMedia> <EmptyTitle>What should we build?</EmptyTitle> <EmptyDescription> The agent can read your code, run commands and make changes. Press send to start. </EmptyDescription> </EmptyHeader> </Empty> ) : ( <MessageScroller> <MessageScrollerViewport> <MessageScrollerContent aria-busy={busy} className="gap-6 px-8 py-0" > {messages.map((message) => { if (message.role === "user") { return ( <MotionMessageScrollerItem key={message.id} messageId={message.id} scrollAnchor variants={slideUp} initial={shouldReduceMotion ? false : "initial"} animate="animate" > <Message align="end"> <MessageContent> <Bubble align="end" variant="muted"> <BubbleContent> {getMessageText(message)} </BubbleContent> </Bubble> </MessageContent> </Message> </MotionMessageScrollerItem> ) }
const streaming = busy && message === messages.at(-1) const steps = message.parts.filter( (part) => part.type === "reasoning" || part.type === "tool-runCommand" ) const reply = getMessageText(message)
return ( <MessageScrollerItem key={message.id} messageId={message.id} > <Message> <MessageContent className="gap-3"> {steps.length > 0 && ( <Trace> {steps.map((part, index) => ( <StepRow key={index} part={part} streaming={streaming} /> ))} </Trace> )} {reply && <Markdown>{reply}</Markdown>} </MessageContent> </Message> </MessageScrollerItem> ) })} </MessageScrollerContent> </MessageScrollerViewport> <MessageScrollerButton /> </MessageScroller> )} </div> <div className="p-8 pt-0"> <form ref={formRef} onSubmit={onSubmit} className="w-full"> <InputGroup> <InputGroupTextarea value={text} onChange={(event) => { setDraft( typeof event === "string" ? event : event.currentTarget.value ) }} placeholder="Ask the agent..." aria-label="Message" className="min-h-14" onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) { event.preventDefault() formRef.current?.requestSubmit() } }} /> <InputGroupAddon align="block-end" className="pt-1"> <DropdownMenuTrigger> <InputGroupButton aria-label="Add context" type="button" size="icon-sm" variant="outline" > <PlusIcon /> </InputGroupButton> <DropdownMenu placement="top start" className="w-44"> <DropdownMenuItem> <PaperclipIcon /> Add Photos & Files </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem> <TelescopeIcon /> Deep Research </DropdownMenuItem> <DropdownMenuItem> <GlobeIcon /> Web Search </DropdownMenuItem> </DropdownMenu> </DropdownMenuTrigger> <InputGroupButton type="submit" variant="default" size="icon-sm" isDisabled={!canSend} className="ml-auto" > <ArrowUpIcon /> <span className="sr-only">Send</span> </InputGroupButton> </InputGroupAddon> </InputGroup> </form> </div> </div> </div> </MessageScrollerProvider> )}
function StepRow({ part, streaming }: { part: ChatPart; streaming: boolean }) { if (part.type === "reasoning") { return ( <ReasoningRow text={part.text} running={part.state === "streaming"} /> ) }
if (part.type === "tool-runCommand") { return <ToolRow part={part} streaming={streaming} /> }
return null}
function ReasoningRow({ text, running }: { text: string; running: boolean }) { const [open, setOpen] = React.useState<boolean>()
return ( <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}> <TraceCollapsibleTrigger> <TraceLine status={running ? "running" : undefined}> <TraceIcon> {running ? ( <LoaderCircleIcon className="animate-spin" /> ) : ( <CircleCheckIcon /> )} </TraceIcon> <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent className="whitespace-pre-wrap"> {text} </TraceCollapsibleContent> </TraceCollapsible> )}
function ToolRow({ part, streaming }: { part: ToolPart; streaming: boolean }) { const command = part.input?.command
if (part.state === "output-available" || part.state === "output-error") { const failed = part.state === "output-error"
return ( <TraceCollapsible> <TraceCollapsibleTrigger> <TraceLine status={failed ? "error" : undefined}> <TraceIcon> <TerminalIcon /> </TraceIcon> <TraceTitle> {failed ? "Failed to run" : "Ran"} {command} </TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <CodeBlock size="sm"> <CodeBlockContent wrap className="max-h-64"> {failed ? part.errorText : part.output.stdout} </CodeBlockContent> </CodeBlock> </TraceCollapsibleContent> </TraceCollapsible> ) }
return ( <TraceLine status={streaming ? "running" : "error"}> <TraceIcon> <TerminalIcon /> </TraceIcon> <TraceTitle> {streaming ? "Running" : "Failed to run"} {command} </TraceTitle> </TraceLine> )}Usage
import { useChat } from "@ai-sdk/react"
import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Message, MessageContent } from "@/components/ui/message"import { MessageScroller, MessageScrollerButton, MessageScrollerContent, MessageScrollerItem, MessageScrollerProvider, MessageScrollerViewport,} from "@/components/ui/message-scroller"function Thread() { const { messages, status } = useChat() const busy = status === "submitted" || status === "streaming"
return (<MessageScrollerProvider> <MessageScroller> <MessageScrollerViewport> <MessageScrollerContent aria-busy={busy}> {messages.map((message) => ( <MessageScrollerItem key={message.id} messageId={message.id} scrollAnchor={message.role === "user"} > <Message align={message.role === "user" ? "end" : "start"}> <MessageContent>{/* the turn */}</MessageContent> </Message> </MessageScrollerItem> ))} </MessageScrollerContent> </MessageScrollerViewport> <MessageScrollerButton /> </MessageScroller></MessageScrollerProvider> )}Put scrollAnchor on the person's turn, not the agent's. A new question then settles near the top and the reply streams in underneath it. Every item needs a messageId, or the scroller cannot track it.
The pattern keeps autoScroll off, which is the default. Set autoScroll on MessageScrollerProvider if you want the viewport to follow the reply to the bottom instead of anchoring to the question.
Examples
Thread with steps
The demo above shows three turns. Each agent turn is a Trace of steps (reasoning, then a command) followed by the reply as Markdown, set with typeset-chat so every reply has the same rhythm. Steps open while they run and stay closed afterwards, and the person can open any of them to read the command output.
Empty
Before the first message, show an Empty with what the agent can do and one or two starting points, and keep the field below it. The send button stays disabled until there is text. See also Suggestion.
AI SDK
useChat from @ai-sdk/react gives you messages and status. Render each message's parts in order: text becomes the reply, reasoning and tool-<name> parts become steps in a Trace.
"use client"
import { useChat } from "@ai-sdk/react"
export function Thread() { const { messages, sendMessage, status } = useChat() const busy = status === "submitted" || status === "streaming"
return ( <MessageScrollerProvider> <MessageScroller> <MessageScrollerViewport> <MessageScrollerContent aria-busy={busy}> {messages.map((message) => ( <MessageScrollerItem key={message.id} messageId={message.id} scrollAnchor={message.role === "user"} > {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </MessageScrollerItem> ))} </MessageScrollerContent> </MessageScrollerViewport> <MessageScrollerButton /> </MessageScroller> </MessageScrollerProvider> )}The route that answers it, on the server:
import { convertToModelMessages, streamText, type UIMessage } from "ai"
export async function POST(request: Request) { const { messages }: { messages: UIMessage[] } = await request.json()
const result = streamText({ model: "openai/gpt-5", messages: await convertToModelMessages(messages), })
return result.toUIMessageStreamResponse({ sendReasoning: true })}Use status to tell the stages apart. submitted means the request left and nothing has arrived, streaming means parts are arriving, ready means the turn is done and error means it failed. Disable sending while submitted or streaming, and offer stop() instead (see Prompt Input).
Develop without a model
lib/ai.ts re-exports createChat from @shadcn/helpers/ai-sdk. It scripts a whole conversation, then streams it through the real useChat lifecycle, so the thread behaves as it will in production with no model, route or key.
const chat = createChat() .user("Which orders are late this week?") .assistant(({ writer }) => { writer.reasoning("I should read the open orders first.") writer.text("Three orders are late. Two are waiting on steel.") })
const { messages, sendMessage } = useChat({ messages: chat.get(0), transport: chat.transport({ delayMs: 16 }),})chat.get(0) starts with no messages and chat.next(messages) returns the next scripted user message, which is how the demo fills the field. A fallback string in transport answers once the script has run out. The demo is a scripted run: its replies are canned, and it changes nothing.
Accessibility
| Key | Action |
|---|---|
| Tab | Moves focus into the message list, which is a focusable region, then on to the controls inside it and the field. |
| ArrowUp | Scrolls the message list up when it has focus. |
| ArrowDown | Scrolls the message list down when it has focus. |
| PageUp | Scrolls the message list up by a page. |
| Enter | Sends the message from the field, as in the demo, or presses the focused scroll-to-end button. |
| ShiftEnter | Adds a new line in the field. |
The message scroller provides:
- A viewport with
role="region", the label "Messages" and a tab stop, so people can scroll it by keyboard. - A content list with
role="log"andaria-relevant="additions", so screen readers announce new messages as they are added. - A scroll-to-end button with a screen-reader label that leaves the tab order while the viewport is already at the bottom.
You provide:
aria-busyonMessageScrollerContentwhile a reply streams, as the pattern does.- A label on the field (
aria-label="Message") and on every icon button, such as the reset button. - A way to stop a running reply. Keyboard focus stays in the field after send, because the field is not unmounted.
Guidelines
When to use
- For a conversation where the agent works in turns and the person reads along: questions, tasks, reviews.
- When replies stream and may be long, so the reader needs to keep their place.
When not to use
- For a single answer with no follow-up. Show the result in the page, with an Alert or a Card.
- For a list of tasks the agent runs unattended. Use Queue or Task.
Content
- Show the person's message as a muted bubble on the end side and the agent's turn as plain text on the start side.
- Put what the agent did (reasoning, commands, tool calls) in a collapsed
Traceabove the reply, not in the reply. - Say what the agent can do in the empty state, in one or two sentences.
Human in the loop
The person must always be able to see what the agent is doing, stop it and undo it. Show each step as it runs, keep a stop control reachable while a reply streams, and put Checkpoint markers after turns that change data. Ask with Confirmation before an action that cannot be undone.
Anchor the thread to the person's question so the reply starts in view, and keep the thread where it is when they scroll up to reread.
Don’t pull the viewport to the bottom on every streamed word. The person loses their place and cannot read.
Composition
| Component | What it does here |
|---|---|
| Message Scroller | Holds the thread, anchors the person's turn and shows the scroll-to-end button. |
| Message | Lays out one turn and aligns it to the start or end. |
| Bubble | Wraps the person's message. |
| Trace | Shows reasoning and commands as collapsible steps. |
| Code Block | Shows command output inside a step. |
| Empty | Fills the thread before the first message. |
| Input Group | The field, with the add and send buttons. |
| Dropdown Menu | The add-context menu beside the field. |
| Button and Tooltip | The reset control and its label. |
The pattern exports one component, ChatDemo, which owns the scripted chat, the field and the thread. Its internal StepRow, ReasoningRow and ToolRow are not exported: copy the file and change them to match your own tools.