Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Message Branch for UI SDK

Keep each version of a regenerated AI reply or an edited prompt, and flip between them with arrows and a 2 of 3 count. For React on UI SDK.

On this page11 sections

Message Branch keeps every version of one message and shows one at a time, with arrows and a "2 of 3" count to flip between them. Reach for it when a reply is regenerated or a prompt edited and the earlier version shouldn't vanish.

Each version wraps a whole Message, so it keeps its own layout and actions. To take the conversation back to an earlier turn instead, dropping what came after, use a Checkpoint.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

Message Branch anatomy: root, item, selector, previous, page, next

Usage

import { Message, MessageContent } from "@/components/ui/message";
import {
  MessageBranch, MessageBranchContent, MessageBranchItem,
  MessageBranchNext, MessageBranchPage, MessageBranchPrevious,
  MessageBranchSelector,
} from "@/components/ui/message-branch";
const versions = [
  { id: "docs", text: "Start with the tutorial at react.dev." },
  { id: "project", text: "Build a small app you'd use yourself." },
];

const Answer = () => (
  <MessageBranch>
    <MessageBranchContent>
      {versions.map((version) => (
        <MessageBranchItem key={version.id}>
          <Message>
            <MessageContent>{version.text}</MessageContent>
          </Message>
        </MessageBranchItem>
      ))}
    </MessageBranchContent>
    <MessageBranchSelector from="assistant">
      <MessageBranchPrevious />
      <MessageBranchPage />
      <MessageBranchNext />
    </MessageBranchSelector>
  </MessageBranch>
);

Every version goes in its own MessageBranchItem, which is how the branch counts it. The selector can sit anywhere inside MessageBranch, under the versions as here or in a message's footer.

Accessibility

The selector is a group named Versions, with two buttons named Previous version and Next version, and the "2 of 3" between them is a polite live region, so a screen reader reads the new count after each press. Versions that aren't showing carry the hidden attribute, so assistive technology skips them as well. Those names are in English. Pass your own aria-label to the selector and the buttons to translate them, and give MessageBranchPage a label function, which gets the version's number and the count and returns the text, such as "2 de 3".

Tab
Moves focus to the Previous version button, then the Next version button.
Shift+Tab
Moves focus back the other way.
Enter
On Previous version or Next version, shows the version before or after and updates the count.
Space
On Previous version or Next version, shows the version before or after and updates the count.

Demos

Regenerate

A reply about wrapping card layouts, with the selector beside Copy and Regenerate in its footer. It starts with one version, so no selector shows until the first Regenerate adds a second and switches to it through branch and onBranchChange. Wrap the whole Message in MessageBranch like this when the selector belongs among the reply's own actions. Copy writes the version on screen to the clipboard.

Preview width

Edited prompts

Two versions of a prompt for a launch email's subject line, each MessageBranchItem holding the prompt and the reply it got. defaultBranch opens on the later, shorter edit, and the selector sits in the prompt's MessageFooter, under the bubble on the end side. Use pairs like this when editing a prompt reruns the conversation from that point.

Preview width

AI SDK

regenerate drops the reply, and anything after it, from the chat's messages before it asks the model for a new one, so the old reply is gone unless you keep it. Save it before you call regenerate, under the id of the prompt it answers.

const { messages, regenerate } = useChat();
const [replaced, setReplaced] = useState<Record<string, UIMessage[]>>({});

function retry(prompt: UIMessage, reply: UIMessage) {
  setReplaced({
    ...replaced,
    [prompt.id]: [...(replaced[prompt.id] ?? []), reply],
  });
  regenerate({ messageId: reply.id });
}

The reply's versions are the ones you saved, then the reply itself. A regenerated reply comes back with a new id, so keying the branch on it remounts the branch on the newest version.

const versions = [...(replaced[prompt.id] ?? []), reply];

return (
  <MessageBranch defaultBranch={versions.length - 1} key={reply.id}>
    <MessageBranchContent>
      {versions.map((version) => (
        <MessageBranchItem key={version.id}>
          <Message>{/* the version's parts */}</Message>
        </MessageBranchItem>
      ))}
    </MessageBranchContent>
    <MessageBranchSelector from="assistant">
      <MessageBranchPrevious />
      <MessageBranchPage />
      <MessageBranchNext />
    </MessageBranchSelector>
  </MessageBranch>
);

Migrating from AI SDK Elements

AI SDK Elements keeps these parts in components/ai-elements/message.tsx, and an older project in components/ai-elements/branch.tsx as Branch, BranchMessages, BranchSelector, BranchPrevious, BranchNext and BranchPage. Run the command in Installation, then import the parts from @/components/ui/message-branch instead, under their MessageBranch names. What differs:

  • Wrap each version in a MessageBranchItem. Elements counted the children of MessageBranchContent, while here each version registers itself, so a version can sit in a fragment or come from a list.
  • defaultBranch and onBranchChange work as before, and branch makes the branch controlled.
  • from on MessageBranchSelector is optional. Set it to user to put the selector at the end.
  • The selector is a group of ghost buttons rather than a ButtonGroup, the buttons are named "Previous version" and "Next version", and MessageBranchPage is a live region.

FAQ

How do I show the versions of a regenerated reply in React?

Wrap them in MessageBranch: each version in a MessageBranchItem inside MessageBranchContent, and a MessageBranchSelector holding MessageBranchPrevious, MessageBranchPage and MessageBranchNext. Only the current version shows. The others stay in the page with the hidden attribute, so switching back is instant and each keeps its state.

The Usage snippet is the smallest version of this, and the Regenerate demo adds a version each time the reader asks for one.

Why does each Message Branch version need a MessageBranchItem?

Each item registers itself with the branch when it mounts, and the selector counts what registered, in the order the items sit in the page. That's why a version can come from a list, a fragment or a component of your own, and needn't be a direct child of MessageBranchContent.

Anything inside MessageBranchContent without an item around it isn't counted or hidden, so it shows under every version.

Why doesn't the Message Branch selector show?

It renders only once there are two versions or more. A reply that was never regenerated has one, so there are no arrows and no "1 of 1", and the message looks like any other. The first new version brings the selector in, as the Regenerate demo shows.

If there are two versions and still no selector, check that each one sits in its own MessageBranchItem. A selector placed outside MessageBranch throws an error rather than hiding.

How do I switch to the newest version after a regenerate?

Control it. Keep the index in state, pass it as branch, update it from onBranchChange, and set it to the new version's index when you add one, which is the length of your list before the new version. The Regenerate demo does exactly this.

Left uncontrolled, the branch stays on the version the reader was looking at. The AI SDK section shows another way: defaultBranch set to the last index, with the branch keyed on the newest reply's id so it remounts there.

Can Message Branch stop at the first and last version instead of wrapping?

As shipped, Next goes from the last version round to the first and Previous from the first to the last, as in AI SDK Elements, and both stay enabled while there are two versions or more. To stop at the ends, control branch and set disabled on MessageBranchPrevious while the first version shows and on MessageBranchNext while the last one does. Your value wins over the component's own.

Can people switch Message Branch versions with a keyboard and a screen reader?

Yes. Previous and Next are ordinary buttons, named Previous version and Next version, in a group named Versions, so Tab reaches them and Enter or Space presses them. The "2 of 3" between them is a polite live region, read after each press.

The versions that aren't showing have the hidden attribute, so a screen reader skips them too. The Accessibility section says how to translate the names.

Which Message Branch version shows before the page hydrates?

The first one. Versions register in the browser, so the server's HTML shows the first version and no selector. When defaultBranch points at another version, that one takes the first's place as the page hydrates, so on a slow connection the first version shows for a moment.

CSS hides the other versions in that HTML wherever the items sit inside MessageBranchContent, each in a wrapper element of its own included, so the thread never loads with every version stacked.

A thread rendered only in the browser, as most chat UIs are, shows the chosen version from its first frame, because the versions register before the browser paints.

How do I keep the earlier versions of an edited prompt?

Make each version a pair, the prompt as it was and the reply it got, both inside one MessageBranchItem. Put the selector in the prompt's MessageFooter, which lines it up under the bubble on the end side, and set defaultBranch to the last index to open on the latest edit, as the Edited prompts demo does.

Each item then carries its own selector, and a hidden version hides its selector with it. With the AI SDK, save the old prompt and reply before you send the edit, the same way you save a regenerated reply.

API Reference

MessageBranch

PropType
branch?number

The version shown, from 0, when controlled.

defaultBranch?number

The version shown at first, from 0, when uncontrolled.

Default
0
onBranchChange?(branch: number) → void

Called with the version's index, from 0, when the reader moves to it.

Parameters

branch – number

Returns
void
className?string

Merged with the part's classes.

MessageBranchContent

<div> data-slot="message-branch-content"

PropType
className?string

Merged with the part's classes.

MessageBranchItem

<div> data-slot="message-branch-item"

PropType
className?string

Merged with the part's classes.

AttributeType
data-pending?string

Present when pending is true.

data-state?string

"active" when active is true, otherwise "inactive".

MessageBranchSelector

data-slot="message-branch-selector"

PropType
from?"assistant" | "system" | "user"

Whose message it is, as AI SDK Elements takes it: a user's selector sits at the end.

Type
"assistant" | "system" | "user"
className?string

Merged with the part's classes.

AttributeType
data-from?string

Mirrors from.

MessageBranchPrevious

data-slot="message-branch-previous"

PropType
clickEffect?boolean

Apply a click effect to the button.

Default
true
debug?boolean

Logs every state change with its reason to the console, in development builds.

disabled?boolean

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Default
false
focusableWhenDisabled?boolean

Keeps a disabled button in the tab order with aria-disabled instead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing.

Default
false
isLoading?boolean

Show a loading indicator.

Default
false
onClick?( event: React.MouseEvent<HTMLButtonElement>, details?: ButtonActionDetails ) → unknown

Runs when the button is pressed. Return a Promise to keep it pending (data-pending) until it settles. details.source says how it was pressed; a wrapper passing the click on may leave it out.

Type
( event: React.MouseEvent<HTMLButtonElement>, details?: ButtonActionDetails ) → unknown
Parameters

event – React.MouseEvent<HTMLButtonElement>

details? – ButtonActionDetails

Returns
unknown
pendingAnnouncement?string

What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
type?"button" | "reset" | "submit"

What a native button does in a form: "submit" submits it and "reset" resets it. Ignored when the button renders as something else.

Type
"button" | "reset" | "submit"
Default
"button"
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MessageBranchNext

data-slot="message-branch-next"

PropType
clickEffect?boolean

Apply a click effect to the button.

Default
true
debug?boolean

Logs every state change with its reason to the console, in development builds.

disabled?boolean

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Default
false
focusableWhenDisabled?boolean

Keeps a disabled button in the tab order with aria-disabled instead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing.

Default
false
isLoading?boolean

Show a loading indicator.

Default
false
onClick?( event: React.MouseEvent<HTMLButtonElement>, details?: ButtonActionDetails ) → unknown

Runs when the button is pressed. Return a Promise to keep it pending (data-pending) until it settles. details.source says how it was pressed; a wrapper passing the click on may leave it out.

Type
( event: React.MouseEvent<HTMLButtonElement>, details?: ButtonActionDetails ) → unknown
Parameters

event – React.MouseEvent<HTMLButtonElement>

details? – ButtonActionDetails

Returns
unknown
pendingAnnouncement?string

What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Default
"Loading"
type?"button" | "reset" | "submit"

What a native button does in a form: "submit" submits it and "reset" resets it. Ignored when the button renders as something else.

Type
"button" | "reset" | "submit"
Default
"button"
render?ReactElement | ((props: object, state: object) => ReactElement)

Replace the host element or compose it with another component.

Type
ReactElement | ((props: object, state: object) => ReactElement)
className?string

Merged with the part's classes.

MessageBranchPage

<span> data-slot="message-branch-page"

PropType
label?(page: number, count: number) → React.ReactNode

The text, from the version shown (counting from 1) and how many there are. Return your own to translate it. The type's default: (page, count) => ${page} of ${count}``.

Type
(page: number, count: number) → React.ReactNode
Default
pageOf
Parameters

page – number

count – number

Returns
React.ReactNode
className?string

Merged with the part's classes.