Task
Shows one piece of work as a titled group of steps that finish one after another.
Installation
pnpm dlx shadcn@latest add @silkware/ai-taskTo copy the pattern by hand, install the components it composes:
pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/message @silkware/traceThen the packages:
pnpm add ai @ai-sdk/react @shadcn/helpers lucide-reactCopy the source into components/ai-elements/task.tsx. The file also needs @/lib/ai:
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import type { UIMessage } from "ai"import { CircleAlertIcon, CircleCheckIcon, LoaderCircleIcon,} from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { Message, MessageContent } from "@/components/ui/message"import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage< unknown, { task: { title: string steps: { title: string; status: "done" | "running" | "error" }[] } }>
type TaskPart = Extract<ChatMessage["parts"][number], { type: "data-task" }>
type Status = "running" | "error" | undefined
const TASKS = [ { id: "find", title: ["Finding the project files", "Found the project files"], steps: [ ["Searching for generateMetadata", "Searched for generateMetadata"], ["Reading app/layout.tsx", "Read app/layout.tsx"], ["Reading app/page.tsx", "Read app/page.tsx"], ], }, { id: "update", title: ["Updating the page metadata", "Updated the page metadata"], steps: [ ["Editing app/layout.tsx", "Edited app/layout.tsx"], ["Editing app/page.tsx", "Edited app/page.tsx"], ], },]
function taskAt(task: (typeof TASKS)[number], done: number) { return { title: task.title[done < task.steps.length ? 0 : 1], steps: task.steps.slice(0, done + 1).map(([running, finished], index) => ({ title: index < done ? finished : running, status: index < done ? "done" : "running", })), } satisfies TaskPart["data"]}
const chat = createChat<ChatMessage>() .user("Add Open Graph metadata to the home page.") .assistant(({ writer }) => { TASKS.forEach((task) => { for (let done = 0; done <= task.steps.length; done++) { writer .data({ type: "data-task", id: task.id, data: taskAt(task, done) }) .sleep(900) } }) writer.text( "Added Open Graph defaults to app/layout.tsx and a title, description and image for the home page in app/page.tsx." ) })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function getStepStatus( status: TaskPart["data"]["steps"][number]["status"], streaming: boolean): Status { if (status === "done") { return undefined }
return status === "running" && streaming ? "running" : "error"}
function StatusIcon({ status }: { status: Status }) { if (status === "running") { return <LoaderCircleIcon className="animate-spin" /> }
return status === "error" ? <CircleAlertIcon /> : <CircleCheckIcon />}
function TaskRow({ task, streaming,}: { task: TaskPart["data"] streaming: boolean}) { const [open, setOpen] = React.useState<boolean>() const steps = task.steps.map((step) => ({ title: step.title, status: getStepStatus(step.status, streaming), })) const status = steps.some((step) => step.status === "error") ? "error" : steps.some((step) => step.status === "running") ? "running" : undefined
return ( <TraceCollapsible isExpanded={open ?? status === "running"} onExpandedChange={setOpen} > <TraceCollapsibleTrigger> <TraceLine status={status}> <TraceIcon> <StatusIcon status={status} /> </TraceIcon> <TraceTitle>{task.title}</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <Trace> {steps.map((step) => ( <TraceLine key={step.title} status={step.status}> <TraceTitle>{step.title}</TraceTitle> </TraceLine> ))} </Trace> </TraceCollapsibleContent> </TraceCollapsible> )}
export function TaskDemo() { 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 tasks = message.parts.filter((part) => part.type === "data-task") const text = getMessageText(message)
return ( <Message key={message.id}> <MessageContent className="gap-4"> {tasks.length > 0 && ( <Trace> {tasks.map((part) => ( <TaskRow key={part.id} task={part.data} streaming={streaming} /> ))} </Trace> )} {text && <p>{text}</p>} </MessageContent> </Message> ) })} {!busy && ( <Button variant="outline" size="sm" className="mt-auto self-start" onPress={() => { setMessages([]) sendMessage(question) }} > Replay </Button> )} </div> )}Usage
A task is a collapsible line with a status icon and a title, and the steps it has taken inside it. The status of the line follows its steps: error if any step failed, running while one is running, plain when all are done.
import { CircleAlertIcon, CircleCheckIcon, LoaderCircleIcon } from "lucide-react"
import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"<TraceCollapsible isExpanded={open ?? status === "running"} onExpandedChange={setOpen}> <TraceCollapsibleTrigger> <TraceLine status={status}> <TraceIcon> <StatusIcon status={status} /> </TraceIcon> <TraceTitle>{task.title}</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <Trace> {steps.map((step) => ( <TraceLine key={step.title} status={step.status}> <TraceTitle>{step.title}</TraceTitle> </TraceLine> ))} </Trace> </TraceCollapsibleContent></TraceCollapsible>open is undefined until the person toggles the task. Until then the task is open while it runs and closes when it finishes. After the person toggles it, their choice stays.
Examples
Failed step
A task whose last step failed. The line is in error, opens by default and says what failed. The step before it stays as a record of what did succeed.
AI SDK
Each task is a data part with its own id, so a conversation can hold several and each updates in place. The task carries a title and its steps:
import type { UIMessage } from "ai"
type ChatMessage = UIMessage< unknown, { task: { title: string steps: { title: string; status: "done" | "running" | "error" }[] } }>On the server, write the part again each time a step starts or ends:
writer.write({ type: "data-task", id: "update", data: { title: "Updating the page metadata", steps },})On the client, render one row per data-task part:
const tasks = message.parts.filter((part) => part.type === "data-task")
{tasks.map((part) => ( <TaskRow key={part.id} task={part.data} streaming={streaming} />))}A step the server still marks running after the stream ended did not finish. The demo turns it into an error step (getStepStatus) so the line never keeps shimmering on a dead stream.
Scripted streams in development
writer.data with the same id updates the part, so a task grows one step at a time:
const chat = createChat<ChatMessage>() .user("Add Open Graph metadata to the home page.") .assistant(({ writer }) => { for (let done = 0; done <= task.steps.length; done++) { writer.data({ type: "data-task", id: task.id, data: taskAt(task, done) }).sleep(900) } })Accessibility
| Key | Action |
|---|---|
| Enter | Opens or closes the steps of the focused task. |
| Space | Opens or closes the steps of the focused task. |
| Tab | Moves focus to the next task. |
The composed components provide:
- A trigger that is a real button with
aria-expanded, and a panel tied to it. - A visible focus ring on the trigger.
You provide:
- The state of a step in its title: "Searching for generateMetadata", "Searched for generateMetadata", "Failed to read app/page.tsx". The demo changes the verb from present to past when a step is done. The spinner and the error colour are not the only signal.
- A decorative icon.
StatusIconis a drawing next to a title that already says the state; do not add a label that repeats it. - A way to learn that a task finished. The line updates in place and is not announced. Say it in the answer text.
Guidelines
When to use
- To show one piece of the agent's work as it happens, such as finding files, then editing them.
- When the person might want to see the steps behind a result, but does not need them by default.
When not to use
- For a single call. Use a Tool line.
- For the whole job as a list of steps ahead. Use Plan.
- For a list of work still to do. Use Queue.
- For another agent doing the work. Use Subagent.
Content
- Title the task with the present participle while it runs ("Updating the supplier prices") and the past tense when it is done ("Updated the supplier prices").
- Name each step by the action and its object, and change its tense when it finishes.
- Say what failed and what was left untouched, in the step: "Failed to update 3 prices: supplier locked".
- Keep a task to about five steps. If it needs more, split it into two tasks.
Say what failed in the failing step and keep the steps that finished.
Don’t replace a failed task with the title "Something went wrong". The person cannot tell what was done.
Human in the loop
- A task reports work that is already happening. If a step changes something that cannot be undone, ask first with Confirmation; the task then shows the step after the answer.
- A failed step stops the task, and the agent says what it will do next. Do not retry a failed write without telling the person.
- Keep a finished task in the transcript, with its steps, so what the agent did stays reviewable.
Composition
| Component | What it does here |
|---|---|
| Trace | Lays out the task line, its steps and the collapsible, and carries the running and error status. |
| Message | Places the conversation in turns. |
| Bubble | Wraps the person's own message. |
| Button | The replay control of the demo. |
components/ai-elements/task.tsx exports TaskDemo, a scripted chat that streams two data-task parts and then the answer text. Copy TaskRow, StatusIcon and getStepStatus into your app and replace the scripted chat with useChat against your route.