# Chat Thread

> The conversation view of an AI chat. Handles replies that stream, edit and retry, and versions of a reply you can switch between.

Canonical: https://hextaui.com/blocks/chat-thread
Last updated: 2026-10-29

## Overview

Chat Thread is the conversation around the composer: your messages, the model’s replies, and what you can do with them. It starts with your empty state and the composer centered, then docks the composer at the bottom once there are messages, without remounting it, so focus and draft text stay put.

The message you just sent moves to the top while its answer streams underneath, and the view follows new text until you scroll away. A rail of checkpoints on the right lets you jump between your messages, with a preview on hover. Older history loads from the top without the view moving.

Hover a message to copy, edit or try again. Edits and retries become versions you can switch between, and nothing is lost. Failed replies offer Try again, stopped replies say so, and thumbs up or down are one click. Inside each reply, Reasoning, ToolCalls and Markdown from the other blocks slot straight in.

Checkpoints before your messages are restore points. Restore says exactly what goes, such as “Removes this message and 3 later messages, and reverts 3 files”, dims those messages while you decide, and lets you keep your code with Conversation only. The later messages fold away, your message goes back into the composer to edit, and a toast offers Undo.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/chat-thread
```

## Usage

### With the AI SDK

Map useChat messages to the thread. Reasoning parts go to Reasoning, tool parts to ToolCalls and text to Markdown. Pin the latest user message, use regenerate for Try again, and send an edit again from that point.

```tsx
"use client"

import { useChat } from "@ai-sdk/react"
import { getToolName, isToolUIPart, type UIMessage } from "ai"

import { PromptInput, PromptInputActions, PromptInputBody, PromptInputSubmit, PromptInputTextarea } from "../prompt-input/prompt-input"
import { Reasoning } from "../thinking/reasoning"
import { ToolCalls } from "../tool-calls/tool-group"
import { getToolPartStatus } from "../tool-calls/tool-part"
import { Markdown } from "../markdown/markdown"
import { ChatAssistantMessage, ChatThread, ChatUserMessage } from "@/components/blocks/chat-thread/chat-thread"

function textOf(message: UIMessage) {
  return message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("")
}

export function Chat() {
  const { messages, status, sendMessage, regenerate, stop, setMessages } = useChat()
  const busy = status === "submitted" || status === "streaming"
  const lastUser = messages.findLastIndex((message) => message.role === "user")

  return (
    <ChatThread
      busy={busy}
      composer={
        <PromptInput status={status} onStop={stop} onSubmit={({ text }) => sendMessage({ text })}>
          <PromptInputBody>
            <PromptInputTextarea />
            <PromptInputActions>
              <PromptInputSubmit />
            </PromptInputActions>
          </PromptInputBody>
        </PromptInput>
      }
    >
      {messages.map((message, index) => {
        const last = index === messages.length - 1
        if (message.role === "user") {
          return (
            <ChatUserMessage
              key={message.id}
              id={message.id}
              text={textOf(message)}
              pin={index === lastUser}
              onEdit={(text) => {
                setMessages(messages.slice(0, index))
                sendMessage({ text })
              }}
            />
          )
        }
        const reasoning = message.parts.flatMap((part) => (part.type === "reasoning" ? [part.text] : [])).join("\n\n")
        const tools = message.parts.filter(isToolUIPart)
        const streaming = last && busy
        return (
          <ChatAssistantMessage
            key={message.id}
            id={message.id}
            text={textOf(message)}
            streaming={streaming}
            last={last}
            error={last && status === "error" ? "Something went wrong." : null}
            onRetry={last ? () => regenerate() : undefined}
          >
            {reasoning ? <Reasoning text={reasoning} streaming={streaming && !textOf(message)} /> : null}
            {tools.length > 0 ? (
              <ToolCalls
                calls={tools.map((part) => ({
                  id: part.toolCallId,
                  name: getToolName(part),
                  status: getToolPartStatus(part, { stopped: !streaming }),
                }))}
              />
            ) : null}
            <Markdown
              text={textOf(message)}
              streaming={streaming}
              sources={message.parts.flatMap((part) =>
                part.type === "source-url"
                  ? [{ id: part.sourceId, url: part.url, title: part.title ?? part.url }]
                  : []
              )}
            />
          </ChatAssistantMessage>
        )
      })}
    </ChatThread>
  )
}
```

### Restore points

Write a data-checkpoint part ({ id, label, files }) from the server when a reply starts, and write it again with the same id as files change. getCheckpoints maps them to user messages, restoreMessages splits the history, and the returned undoRestore brings it all back.

```tsx
"use client"

import * as React from "react"
import { useChat } from "@ai-sdk/react"
import type { UIMessage } from "ai"

import { PromptInput, PromptInputActions, PromptInputBody, PromptInputSubmit, PromptInputTextarea } from "../prompt-input/prompt-input"
import { Markdown } from "../markdown/markdown"
import {
  ChatAssistantMessage,
  ChatThread,
  ChatUserMessage,
  type ChatCheckpointData,
  type ChatRestoreOptions,
} from "@/components/blocks/chat-thread/chat-thread"
import { getCheckpoints, restoreMessages } from "@/components/blocks/chat-thread/checkpoints"

type AgentMessage = UIMessage<unknown, { checkpoint: ChatCheckpointData }>

function textOf(message: AgentMessage) {
  return message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("")
}

function revertFiles(checkpointId: string, undo = false) {
  return fetch(`/api/checkpoints/${checkpointId}`, { method: undo ? "DELETE" : "POST" })
}

export function Chat() {
  const { messages, status, sendMessage, stop, setMessages } = useChat<AgentMessage>()
  const [input, setInput] = React.useState("")
  const busy = status === "submitted" || status === "streaming"
  const checkpoints = getCheckpoints(messages)

  const restore = (checkpointId: string, { code }: ChatRestoreOptions) => {
    const before = messages
    const draft = input
    const { kept, removed } = restoreMessages(messages, checkpointId)
    setMessages(kept)
    setInput(removed[0] ? textOf(removed[0]) : "")
    if (code) void revertFiles(checkpointId)

    return function undoRestore() {
      setMessages(before)
      setInput(draft)
      if (code) void revertFiles(checkpointId, true)
    }
  }

  return (
    <ChatThread
      busy={busy}
      onRestore={busy ? undefined : restore}
      composer={
        <PromptInput
          value={input}
          onValueChange={setInput}
          status={status}
          onStop={stop}
          onSubmit={({ text }) => sendMessage({ text })}
        >
          <PromptInputBody>
            <PromptInputTextarea />
            <PromptInputActions>
              <PromptInputSubmit />
            </PromptInputActions>
          </PromptInputBody>
        </PromptInput>
      }
    >
      {messages.map((message, index) =>
        message.role === "user" ? (
          <ChatUserMessage
            key={message.id}
            id={message.id}
            text={textOf(message)}
            checkpoint={checkpoints.get(message.id)}
          />
        ) : (
          <ChatAssistantMessage
            key={message.id}
            id={message.id}
            text={textOf(message)}
            streaming={busy && index === messages.length - 1}
            last={index === messages.length - 1}
          >
            <Markdown text={textOf(message)} streaming={busy && index === messages.length - 1} />
          </ChatAssistantMessage>
        )
      )}
    </ChatThread>
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `ChatThread` | The frame: scroller, checkpoints, empty state and composer slot. |
| `ChatUserMessage` | Your message: attachments, bubble, time, versions, copy and edit. |
| `ChatAssistantMessage` | A reply. Put Reasoning, ToolCalls and Markdown inside it; it adds the actions, error and stopped states. |
| `ChatCheckpoint` | A restore point before a user message: a quiet line with the files that turn changed, and Restore with its confirm. ChatUserMessage renders it from checkpoint. |
| `ChatDivider` | A labelled line between groups of messages. |
| `ChatAttachments, ChatAction, ChatCopy, ChatBranchSwitch, ChatEditor` | The pieces the messages use, exported for custom layouts. |

## API reference

### ChatThread

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | – | Messages and dividers, in order. |
| `composer` | `ReactNode` | – | Usually Prompt Input. Centered when empty, docked at the bottom otherwise. |
| `empty` | `ReactNode` | – | Shown above the composer when there are no messages. |
| `busy` | `boolean` | `false` | Marks the conversation busy for assistive technology while a reply streams. |
| `hasOlder` | `boolean` | `false` | Shows “Load earlier messages” at the top. |
| `loadingOlder` | `boolean` | `false` | Shows a spinner on that button. The scroll position is restored once it turns false. |
| `onLoadOlder` | `() => void` | – | Prepend older messages here. |
| `onRestore` | `(checkpointId: string, options: { code: boolean }) => void \| (() => void)` | – | Shows Restore on checkpoints. Remove the later messages here and put the message back in the composer. Return a function to offer Undo in the toast, and mount Toaster once in your app. |

### ChatUserMessage

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | – | Stable id. Keep it the same across versions so the view doesn’t jump. |
| `text` | `string` | – | The message. Also used for the checkpoint preview. |
| `pin` | `boolean` | `false` | Scroll this message to the top when it appears. Set it on the message just sent. |
| `files` | `ChatFile[]` | – | { id, name, size?, type?, url? }. Images with a url show as thumbnails. |
| `time` | `Date` | – | Shown on hover, in the reader’s locale. |
| `branch` | `ChatBranch` | – | { index, count, onChange } for the version arrows. |
| `onEdit` | `(text: string) => void` | – | Shows Edit. Called with the new text when it changed. |
| `checkpoint` | `ChatCheckpointData` | – | { id, label?, files? }. Shows a restore point before this message; files are the paths this turn changed. |
| `attachments` | `ReactNode` | – | Custom content above the bubble. |

### ChatAssistantMessage

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | – | Stable id. |
| `children` | `ReactNode` | – | Reasoning, ToolCalls, Markdown or anything else. |
| `text` | `string` | – | Plain text for Copy. |
| `streaming` | `boolean` | `false` | Hides the actions until the reply finishes. |
| `last` | `boolean` | `false` | Keeps the actions visible instead of showing them on hover. |
| `meta` | `ReactNode` | – | Right side of the action row, such as the model and effort. |
| `branch` | `ChatBranch` | – | Version arrows for retries. |
| `feedback` | `"up" \| "down" \| null` | `null` | The current rating. |
| `onFeedback` | `(feedback) => void` | – | Shows the thumbs. Called with null when a rating is undone. |
| `onRetry` | `() => void` | – | Shows Try again. |
| `error` | `string \| null` | – | Shows the message with Try again instead of the actions. |
| `stopped` | `boolean` | `false` | Marks a reply that was stopped early. |

### ChatCheckpoint

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `messageId` | `string` | – | The user message it sits before. |
| `checkpoint` | `ChatCheckpointData` | – | { id, label?, files? }. |
| `label` | `string` | – | Fallback name for Restore and the toast, usually the message text. |

### ChatDivider

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | – | The label, such as Today or “Switched to Nova 3 Max”. |

### restoreMessages(messages, checkpointId)

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `messages` | `UIMessage[]` | – | useChat messages with data-checkpoint parts. |
| `checkpointId` | `string` | – | Returns { kept, removed }: everything before the checkpoint’s user message, and that message onward. removed[0] is the message to put back in the composer. |

### getCheckpoints(messages)

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `messages` | `UIMessage[]` | – | Returns a Map from user message id to its checkpoint, for ChatUserMessage. A part written again with the same id updates it in place. |

## Keyboard

| Key | Action |
| --- | --- |
| `Tab` | Moves through the messages’ actions. They appear on focus, not only on hover. |
| `Enter` | Sends an edited message. |
| `Shift` `Enter` | Adds a line while editing. |
| `Esc` | Cancels an edit. |
| `↑` `↓` `PgUp` `PgDn` | Scroll the conversation when it has focus. |
| `Enter` | Runs the focused choice in the restore confirm. Restore conversation and code is focused first. |
| `Esc` | Closes the restore confirm and returns focus to Restore. |

## Accessibility

- The conversation is a labelled region holding a log, so new messages are announced as they arrive and the region is marked busy while a reply streams.
- Every icon action has a label and tooltip. Thumbs use aria-pressed, Copy and feedback confirm through a polite live region, and errors use role=alert.
- Checkpoints are a navigation landmark of buttons named “Message 2: …”, and the current one has aria-current.
- Version arrows are a group named “Version 1 of 2”.
- The editor focuses itself with the caret at the end and returns to the message on Cancel. Enter waits while an input method is composing.
- Focus rings are never clipped by the scroller, and actions stay visible on touch screens.
- Restore buttons are named “Restore checkpoint: …” after their message and described by the checkpoint line. The confirm is a dialog that says exactly what will be removed and reverted, and the messages that will go are dimmed while it is open.
- After a restore, focus moves to the composer with the caret at the end, and the toast announces what was restored with an Undo button. With reduced motion, later messages fade out instead of folding away.

## Built with

The free HextaUI components Chat Thread is made from. Each one installs on its own.

- [Attachment](https://hextaui.com/docs/attachment) - File and image cards for uploads, with progress, states, actions, a full-card trigger and names that keep their extension.
- [Bubble](https://hextaui.com/docs/bubble) - Chat message bubbles with variants, grouped corners, reactions and room for interactive content.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Kbd](https://hextaui.com/docs/kbd) - Key caps for shortcuts that show the right symbols on every platform, read them out properly and press down with the real keys.
- [Marker](https://hextaui.com/docs/marker) - Quiet notes between content, like date dividers and system events, with sticky dates and times that read as Today or Yesterday.
- [Message](https://hextaui.com/docs/message) - A chat message row with an avatar, name, bubbles and status, where new messages rise in from the sender's side.
- [Message scroller](https://hextaui.com/docs/message-scroller) - A chat scroll area that follows new messages, keeps your place while you read back, and counts what you missed on the jump button.
- [Popover](https://hextaui.com/docs/popover) - A floating panel anchored to a trigger that resizes smoothly with its content and follows the trigger’s direction.
- [Toast](https://hextaui.com/docs/toast) - Brief messages that stack neatly, expand on hover, swipe away, and turn a loading state into success or error in place.
- [Tooltip](https://hextaui.com/docs/tooltip) - A short hint on hover or keyboard focus that opens after a brief rest, switches instantly between neighbours and shows shortcuts.

## Code

4 files, added to components/blocks/chat-thread.
