- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Attachment
- Avatar
- Badge
- Breadcrumb
- Bubble
- Button
- Button Group
- Calendar
- Card
- Carousel
- Chart
- Checkbox
- Code Block
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Direction
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Kbd
- Label
- Marker
- Menubar
- Message
- Message Scroller
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Questionnaire
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toast
- Toggle
- Toggle Group
- Tooltip
- Trace
- Typography
install 41s
compile 38s
images 3m 52sImage optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead.
"use client"
import * as React from "react""use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import type { UIDataTypes, UIMessage } from "ai"
import {
ArrowUpRightIcon,
CircleAlertIcon,
CircleCheckIcon,
GlobeIcon,
LoaderCircleIcon,
} from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"
import { Badge } from "@/components/ui/badge"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
import { Message, MessageContent } from "@/components/ui/message"
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace"
type ChatMessage = UIMessage<
unknown,
UIDataTypes,
{
searchWeb: {
input: { query: string }
output: { results: { title: string; url: string }[] }
}
readBuildLog: {
input: { deployment: string }
output: { log: string }
}
searchCode: {
input: { query: string }
output: { files: string[] }
}
}
>
type StepPart = Extract<
ChatMessage["parts"][number],
{ type: "tool-searchWeb" | "tool-readBuildLog" | "tool-searchCode" }
>
const chat = createChat<ChatMessage>()
.user("Why is the checkout deploy so slow?")
.assistant(({ writer }) => {
writer
.tool("readBuildLog", { input: { deployment: "dpl_8Kx2" } })
.sleep(900)
.output({
log: "install 41s\ncompile 38s\nimages 3m 52s",
})
writer
.tool("searchWeb", { input: { query: "next.js image cache key" } })
.sleep(900)
.output({
results: [
{
title: "Image component | nextjs.org",
url: "https://nextjs.org/docs/app/api-reference/components/image",
},
{
title: "Build cache | vercel.com",
url: "https://vercel.com/docs/deployments/troubleshoot-a-build",
},
],
})
writer
.tool("searchCode", { input: { query: "cacheKey" } })
.sleep(900)
.output({ files: ["next.config.ts", "scripts/optimize-images.ts"] })
writer.text(
"Image optimization takes almost four minutes because its cache key includes the commit hash. Key it on the image directory instead."
)
})
const transcript = chat.get()
const [question] = chat.get(1)
const transport = chat.transport({ delayMs: 20 })
function StatusIcon({ status }: { status?: "running" | "error" }) {
if (status === "running") {
return <LoaderCircleIcon className="animate-spin" />
}
return status === "error" ? <CircleAlertIcon /> : <CircleCheckIcon />
}
function Step({
title,
status,
defaultOpen,
children,
}: {
title: string
status?: "running" | "error"
defaultOpen?: boolean
children?: React.ReactNode
}) {
const line = (
<TraceLine status={status}>
<TraceIcon>
<StatusIcon status={status} />
</TraceIcon>
<TraceTitle>{title}</TraceTitle>
</TraceLine>
)
if (!children) {
return line
}
return (
<TraceCollapsible defaultOpen={defaultOpen}>
<TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
<TraceCollapsibleContent>{children}</TraceCollapsibleContent>
</TraceCollapsible>
)
}
function StepRow({ part, streaming }: { part: StepPart; streaming: boolean }) {
const status =
part.state === "output-available"
? undefined
: part.state === "output-error" || !streaming
? "error"
: "running"
const verb = (running: string, done: string, failed: string) =>
status === "running" ? running : status === "error" ? failed : done
const error = part.state === "output-error" && (
<CodeBlock size="sm" variant="destructive">
<CodeBlockContent wrap className="max-h-64">
{part.errorText}
</CodeBlockContent>
</CodeBlock>
)
if (part.type === "tool-searchWeb") {
return (
<Step
status={status}
title={`${verb("Searching", "Searched", "Failed to search")} the web for ${part.input?.query}`}
>
{error ||
(part.state === "output-available" && (
<Trace>
{part.output.results.map((result) => (
<a
key={result.url}
href={result.url}
target="_blank"
rel="noreferrer"
>
<TraceLine>
<TraceIcon>
<GlobeIcon />
</TraceIcon>
<TraceTitle>
{result.title}
<span className="sr-only"> (opens in a new tab)</span>
</TraceTitle>
<TraceIcon>
<ArrowUpRightIcon />
</TraceIcon>
</TraceLine>
</a>
))}
</Trace>
))}
</Step>
)
}
if (part.type === "tool-readBuildLog") {
return (
<Step
status={status}
defaultOpen
title={`${verb("Reading", "Read", "Failed to read")} the build log for ${part.input?.deployment}`}
>
{error ||
(part.state === "output-available" && (
<CodeBlock size="sm">
<CodeBlockContent wrap className="max-h-64">
{part.output.log}
</CodeBlockContent>
</CodeBlock>
))}
</Step>
)
}
return (
<Step
status={status}
title={`${verb("Searching", "Searched", "Failed to search")} the code for ${part.input?.query}`}
>
{error ||
(part.state === "output-available" && (
<div className="flex flex-wrap gap-1.5">
{part.output.files.map((file) => (
<Badge key={file} variant="secondary" className="font-mono">
{file}
</Badge>
))}
</div>
))}
</Step>
)
}
function ChainOfThought({
steps,
streaming,
answering,
}: {
steps: StepPart[]
streaming: boolean
answering: boolean
}) {
const [open, setOpen] = React.useState<boolean>()
const running = streaming && !answering
const failed = steps.filter((part) => part.state === "output-error").length
const status = running ? "running" : failed > 0 ? "error" : undefined
return (
<Trace>
<TraceCollapsible open={open ?? running} onOpenChange={setOpen}>
<TraceCollapsibleTrigger>
<TraceLine status={status}>
<TraceIcon>
<StatusIcon status={status} />
</TraceIcon>
<TraceTitle>
{running
? "Researching"
: `Researched in ${steps.length} steps${failed > 0 ? `, ${failed} failed` : ""}`}
</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<Trace>
{steps.map((part) => (
<StepRow
key={part.toolCallId}
part={part}
streaming={streaming}
/>
))}
</Trace>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
)
}
export function ChainOfThoughtDemo() {
const { messages, sendMessage, setMessages, status } = useChat({
messages: transcript,
transport,
})
const busy = status === "submitted" || status === "streaming"
return (
<div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
{messages.map((message) => {
if (message.role === "user") {
return (
<Message key={message.id} align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{getMessageText(message)}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
)
}
const streaming = busy && message === messages.at(-1)
const steps = message.parts.filter(
(part) =>
part.type === "tool-searchWeb" ||
part.type === "tool-readBuildLog" ||
part.type === "tool-searchCode"
)
const text = getMessageText(message)
return (
<Message key={message.id}>
<MessageContent className="gap-4">
{steps.length > 0 && (
<ChainOfThought
steps={steps}
streaming={streaming}
answering={text.length > 0}
/>
)}
{text && <p>{text}</p>}
</MessageContent>
</Message>
)
})}
{!busy && (
<Button
variant="outline"
size="sm"
className="mt-auto self-start"
onClick={() => {
setMessages([])
sendMessage(question)
}}
>
Replay
</Button>
)}
</div>
)
}
Chain of Thought is a summary line that expands into the steps an agent took. The summary says what happened, like "Researched in 3 steps". The steps sit inside it, each one a line of its own.
Chain of Thought is built with Trace with a TraceCollapsible for the summary.
Installation#
Chain of Thought is built with the Trace, Code Block and Badge components.
pnpm dlx shadcn@latest add trace code-block badge
Install the required shadcn/ui dependencies:
pnpm dlx shadcn@latest add collapsible code-block badge
Copy and paste the following code into your project.
import * as React from "react"
import { cn } from "cn"
import { ChevronRightIcon } from "lucide-react"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
function Trace({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="trace"
className={cn(
"flex w-full min-w-0 flex-col gap-2 *:has-[>[data-slot=trace-line]]:flex *:has-[>[data-slot=trace-line]]:w-fit *:has-[>[data-slot=trace-line]]:max-w-full *:has-[>[data-slot=trace-line]]:min-w-0 *:has-[>[data-slot=trace-line]]:rounded-lg *:has-[>[data-slot=trace-line]]:text-left *:has-[>[data-slot=trace-line]]:outline-none *:has-[>[data-slot=trace-line]]:focus-visible:ring-3 *:has-[>[data-slot=trace-line]]:focus-visible:ring-ring/30",
className
)}
{...props}
/>
)
}
function TraceLine({
className,
status,
...props
}: React.ComponentProps<"span"> & {
status?: "running" | "error" | "pending"
}) {
return (
<span
data-slot="trace-line"
data-status={status}
className={cn(
"flex w-fit max-w-full min-w-0 items-center gap-2 text-sm text-muted-foreground transition-colors in-[a,button]:cursor-pointer in-[a:hover,button:hover]:text-foreground data-[status=error]:text-destructive data-[status=error]:in-[a:hover,button:hover]:text-destructive data-[status=pending]:opacity-60 data-[status=running]:*:data-[slot=trace-title]:shimmer",
className
)}
{...props}
/>
)
}
function TraceIcon({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="trace-icon"
aria-hidden="true"
className={cn(
"flex size-4 shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [[data-slot=trace-title]~&]:-ml-1",
className
)}
{...props}
/>
)
}
function TraceTitle({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="trace-title"
className={cn("min-w-0 truncate motion-reduce:shimmer-none", className)}
{...props}
/>
)
}
function TraceDescription({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="trace-description"
className={cn(
"shrink-0 text-muted-foreground/70 tabular-nums",
className
)}
{...props}
/>
)
}
function TraceCollapsible({
className,
...props
}: Omit<React.ComponentProps<typeof Collapsible>, "asChild" | "open"> &
(
| { open?: undefined }
| {
open: boolean
onOpenChange: NonNullable<
React.ComponentProps<typeof Collapsible>["onOpenChange"]
>
}
)) {
return (
<Collapsible
data-slot="trace-collapsible"
className={cn("flex w-full min-w-0 flex-col", className)}
{...props}
/>
)
}
function TraceCollapsibleTrigger({
className,
children,
...props
}: Omit<React.ComponentProps<typeof CollapsibleTrigger>, "asChild">) {
return (
<CollapsibleTrigger
data-slot="trace-collapsible-trigger"
className={cn(
"group/trace-collapsible-trigger flex w-fit max-w-full min-w-0 cursor-pointer items-center gap-1 rounded-lg text-left text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/30 has-[[data-status=error]]:text-destructive",
className
)}
{...props}
>
{children}
<TraceIcon className="transition-transform group-aria-expanded/trace-collapsible-trigger:rotate-90">
<ChevronRightIcon />
</TraceIcon>
</CollapsibleTrigger>
)
}
function TraceCollapsibleContent({
className,
children,
...props
}: Omit<React.ComponentProps<typeof CollapsibleContent>, "asChild">) {
return (
<CollapsibleContent
data-slot="trace-collapsible-content"
className="min-w-0 overflow-hidden duration-200 [--radix-accordion-content-height:var(--radix-collapsible-content-height)] data-open:animate-accordion-down data-closed:animate-accordion-up"
{...props}
>
<div
data-slot="trace-collapsible-content-inner"
className={cn(
"mt-2 mb-1 ml-[calc(--spacing(2)-1px)] min-w-0 border-l pr-1 pl-4 leading-relaxed wrap-break-word text-muted-foreground",
className
)}
>
{children}
</div>
</CollapsibleContent>
)
}
export {
Trace,
TraceLine,
TraceIcon,
TraceTitle,
TraceDescription,
TraceCollapsible,
TraceCollapsibleTrigger,
TraceCollapsibleContent,
}
Update the import paths to match your project setup.
Usage#
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace"<Trace>
<TraceCollapsible defaultOpen>
<TraceCollapsibleTrigger>
<TraceLine>
<TraceIcon>
<CircleCheckIcon />
</TraceIcon>
<TraceTitle>Researched in 3 steps</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<Trace>
<TraceLine>
<TraceIcon>
<CircleCheckIcon />
</TraceIcon>
<TraceTitle>Read the build log for dpl_8Kx2</TraceTitle>
</TraceLine>
<TraceLine>
<TraceIcon>
<CircleCheckIcon />
</TraceIcon>
<TraceTitle>Searched the web for next.js image cache key</TraceTitle>
</TraceLine>
<TraceLine>
<TraceIcon>
<CircleCheckIcon />
</TraceIcon>
<TraceTitle>Searched the code for cacheKey</TraceTitle>
</TraceLine>
</Trace>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>Steps#
Each step is a TraceLine. Set its status and write the title in the matching tense.
| Step | status | Title |
|---|---|---|
| Running | "running" | Searching for … |
| Done, with detail | none | Searched for … |
| Done, links out | none | Read the Image component docs |
| Failed | "error" | Failed to search for … |
Search Results#
When a step runs a web search, show the results as a Badge for each hostname in the step's content.
<TraceCollapsibleContent className="flex flex-wrap gap-1.5">
{results.map((result) => (
<Badge key={result.url} variant="secondary">
{new URL(result.url).hostname}
</Badge>
))}
</TraceCollapsibleContent>AI SDK#
Render each tool part as a step. running is true while tool parts stream and before the reply starts. Set the summary's status and title from the steps. The summary opens while the steps run, as in Trace.
const [open, setOpen] = React.useState<boolean>()
const running = streaming && !answering
const failed = steps.filter((part) => part.state === "output-error").length
<TraceCollapsible open={open ?? running} onOpenChange={setOpen}>
<TraceCollapsibleTrigger>
<TraceLine status={running ? "running" : failed > 0 ? "error" : undefined}>
<TraceTitle>
{running ? "Researching" : `Researched in ${steps.length} steps`}
</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<Trace>
{steps.map((part) => (
<StepLine key={part.toolCallId} part={part} streaming={streaming} />
))}
</Trace>
</TraceCollapsibleContent>
</TraceCollapsible>StepLine renders one tool part as a TraceLine, as in Tool.
Migrating from AI SDK Elements#
If you added ChainOfThought from AI SDK Elements, your project has a components/ai-elements/chain-of-thought.tsx wrapper. Paste this prompt into your coding agent to rebuild it on Trace and Badge. Every export keeps its name and props, so the code that uses it keeps working.
Migrate components/ai-elements/chain-of-thought.tsx from AI SDK Elements to the shadcn/ui Trace and Badge components.
Keep every export, with the same name and props, so the code that imports it keeps working. Only change how each part renders.
1. Install the components: npx shadcn@latest add trace badge
2. Read https://ui.shadcn.com/docs/ai-elements/radix/chain-of-thought.md and build Chain of Thought the same way.
3. Rebuild each part:
- ChainOfThought renders a Trace with a TraceCollapsible. Pass open, defaultOpen and onOpenChange to the TraceCollapsible.
- ChainOfThoughtHeader renders a TraceCollapsibleTrigger with a TraceLine, a TraceIcon and a TraceTitle, like "Researched in 3 steps".
- ChainOfThoughtContent renders a TraceCollapsibleContent with a Trace for the steps.
- ChainOfThoughtStep renders a TraceLine. Its icon goes in a TraceIcon, its label in a TraceTitle and its description in a TraceDescription. Map status "active" to "running", "pending" to "pending", and "complete" to no status.
- ChainOfThoughtSearchResults renders a flex-wrap list, and ChainOfThoughtSearchResult a Badge with variant="secondary".
- Keep ChainOfThoughtImage as it is.
4. Remove the imports the file no longer uses.
5. Run the type checker and fix any errors.API Reference#
See Trace.