HextaUI

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

Category
AI
Components used
10
Files
4
Usage examples
2
Access
HextaUI Pro (55 blocks)
Source updated
Open in new tab

Part of HextaUI Pro, all 55 blocks, $79 one-time, Compare plans

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.

  1. Get HextaUI Pro

    One payment unlocks every block, including future ones. See pricing.

  2. Add the Pro registry to components.json

    components.json
    {
      "registries": {
        "@hextaui-pro": {
          "url": "https://hextaui.com/r/pro/{name}.json",
          "headers": {
            "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
          }
        }
      }
    }
  3. Add your token

    Create a token on your account page and put it in .env.local as HEXTAUI_PRO_TOKEN.

  4. Add the block

    pnpm dlx shadcn@latest add @hextaui-pro/chat-thread

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.

"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.

"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.

PartDescription
ChatThreadThe frame: scroller, checkpoints, empty state and composer slot.
ChatUserMessageYour message: attachments, bubble, time, versions, copy and edit.
ChatAssistantMessageA reply. Put Reasoning, ToolCalls and Markdown inside it; it adds the actions, error and stopped states.
ChatCheckpointA 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.
ChatDividerA labelled line between groups of messages.
ChatAttachments, ChatAction, ChatCopy, ChatBranchSwitch, ChatEditorThe pieces the messages use, exported for custom layouts.
PropTypeDefault
childrenMessages and dividers, in order.
ReactNode–
composerUsually Prompt Input. Centered when empty, docked at the bottom otherwise.
ReactNode–
emptyShown above the composer when there are no messages.
ReactNode–
busyMarks the conversation busy for assistive technology while a reply streams.
booleanfalse
hasOlderShows “Load earlier messages” at the top.
booleanfalse
loadingOlderShows a spinner on that button. The scroll position is restored once it turns false.
booleanfalse
onLoadOlderPrepend older messages here.
() => void–
onRestoreShows 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.
(checkpointId: string, options: { code: boolean }) => void | (() => void)–
PropTypeDefault
idStable id. Keep it the same across versions so the view doesn’t jump.
string–
textThe message. Also used for the checkpoint preview.
string–
pinScroll this message to the top when it appears. Set it on the message just sent.
booleanfalse
files{ id, name, size?, type?, url? }. Images with a url show as thumbnails.
ChatFile[]–
timeShown on hover, in the reader’s locale.
Date–
branch{ index, count, onChange } for the version arrows.
ChatBranch–
onEditShows Edit. Called with the new text when it changed.
(text: string) => void–
checkpoint{ id, label?, files? }. Shows a restore point before this message; files are the paths this turn changed.
ChatCheckpointData–
attachmentsCustom content above the bubble.
ReactNode–
PropTypeDefault
idStable id.
string–
childrenReasoning, ToolCalls, Markdown or anything else.
ReactNode–
textPlain text for Copy.
string–
streamingHides the actions until the reply finishes.
booleanfalse
lastKeeps the actions visible instead of showing them on hover.
booleanfalse
metaRight side of the action row, such as the model and effort.
ReactNode–
branchVersion arrows for retries.
ChatBranch–
feedbackThe current rating.
"up" | "down" | nullnull
onFeedbackShows the thumbs. Called with null when a rating is undone.
(feedback) => void–
onRetryShows Try again.
() => void–
errorShows the message with Try again instead of the actions.
string | null–
stoppedMarks a reply that was stopped early.
booleanfalse
PropTypeDefault
messageIdThe user message it sits before.
string–
checkpoint{ id, label?, files? }.
ChatCheckpointData–
labelFallback name for Restore and the toast, usually the message text.
string–
PropTypeDefault
childrenThe label, such as Today or “Switched to Nova 3 Max”.
ReactNode–
PropTypeDefault
messagesuseChat messages with data-checkpoint parts.
UIMessage[]–
checkpointIdReturns { kept, removed }: everything before the checkpoint’s user message, and that message onward. removed[0] is the message to put back in the composer.
string–
PropTypeDefault
messagesReturns a Map from user message id to its checkpoint, for ChatUserMessage. A part written again with the same id updates it in place.
UIMessage[]–
KeyAction
TabMoves through the messages’ actions. They appear on focus, not only on hover.
EnterSends an edited message.
ShiftEnterAdds a line while editing.
EscCancels an edit.
↑↓PgUpPgDnScroll the conversation when it has focus.
EnterRuns the focused choice in the restore confirm. Restore conversation and code is focused first.
EscCloses the restore confirm and returns focus to Restore.
  • 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.

Code

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