# Message Branch

> React version switcher for AI chat replies: step through regenerated answers with ‹ 2 / 3 › buttons or Alt+Arrow keys, with a cross-fade and live count.

- Kind: Component (AI chat)
- Docs: https://ui.minidev.pro/docs/message-branch
- Source (registry JSON with the full file): https://ui.minidev.pro/r/message-branch.json
- License: MIT. One file, yours to edit after install.

## When to use

Wrap the assistant reply: pass every version in `versions` (or as children) and it shows one, with a compact selector underneath. The selector hides itself while there is only one version, and in uncontrolled mode a newly added version is shown straight away. Put MessageActions in `actions` to get the selector and the copy, retry and vote buttons on one row. For the "Not quite right?" footer use RegenerateBar.

## Installation

### shadcn CLI (copies the source into your project)

```bash
npx shadcn@latest add @minidev/message-branch
```

Writes `components/ui/message-branch.tsx` plus the MiniDev files it is built from (icon-button) and installs its npm dependencies. Older CLI versions: `npx shadcn@latest add https://ui.minidev.pro/r/message-branch.json`.

### npm package

```bash
npm i minidev-ui-kit lucide-react motion
```

Add the tokens to your global stylesheet once:

```css
@import "tailwindcss";
@import "minidev-ui-kit/styles.css";
@source "../node_modules/minidev-ui-kit";
```

Next.js also needs `transpilePackages: ["minidev-ui-kit"]` in next.config.

## Import

After the shadcn install:

```tsx
import { MessageBranch } from "@/components/ui/message-branch"
```

From the npm package:

```tsx
import { MessageBranch } from "minidev-ui-kit/ui/message-branch"
```

## Usage

```tsx
import { MessageBranch } from "@/components/ui/message-branch"

export function Example() {
  return (
    <MessageBranch />
  )
}
```

## Props

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `versions` | `React.ReactNode[]` | - | no | Every version of the reply, oldest first. When omitted, each child is one version. |
| `children` | `React.ReactNode` | - | no | Versions as children, used when `versions` is not passed. |
| `index` | `number` | - | no | Controlled index of the version shown (0-based). |
| `defaultIndex` | `number` | - | no | Starting index when uncontrolled. Defaults to the newest version. |
| `onIndexChange` | `(index: number) => void` | - | no | Fires with the new 0-based index when the user switches version. |
| `hideWhenSingle` | `boolean` | `true` | no | Hide the selector while there is only one version. |
| `label` | `string` | `"Response"` | no | What one version is called in the screen reader text: "Response 2 of 3", "Previous response". |
| `actions` | `React.ReactNode` | - | no | Rendered on the selector row after the switcher, for example MessageActions. |
| `className` | `string` | - | no |  |

## Examples

### Regenerate adds a version

Retry appends a reply; uncontrolled, the branch jumps to the new one. Alt+Left and Alt+Right switch while focus is inside.

```tsx
function RegenerateReply() {
  const [replies, setReplies] = React.useState([firstReply])
  return (
    <MessageBranch
      versions={replies.map((text) => (
        <p key={text} className="text-sm leading-[1.6] text-fg">{text}</p>
      ))}
      actions={
        <MessageActions onRetry={async () => setReplies((r) => [...r, await regenerate()])} />
      }
    />
  )
}
```

### Edited prompt, controlled

Branch the user's message with label="Prompt" and keep the index in state, so the reply below follows the prompt version. className="items-end" moves the switcher under the message.

```tsx
function EditedPrompt() {
  const [turn, setTurn] = React.useState(1)
  return (
    <div className="flex flex-col gap-3">
      <MessageBranch
        label="Prompt"
        index={turn}
        onIndexChange={setTurn}
        className="items-end"
        versions={turns.map((t) => (
          <p key={t.id} className="ml-auto w-fit max-w-[85%] rounded-2xl rounded-br-md border border-border bg-sunken px-3.5 py-2 text-sm text-fg">
            {t.prompt}
          </p>
        ))}
      />
      <Markdown>{turns[turn].reply}</Markdown>
    </div>
  )
}
```

### One version

With a single version the switcher hides itself and only the actions show. Pass hideWhenSingle={false} to keep "1 / 1".

```tsx
<MessageBranch
  versions={[<p key="a" className="text-sm leading-[1.6] text-fg">Helix Biotech paid INV-2029 this morning.</p>]}
  actions={<MessageActions onCopy={() => navigator.clipboard.writeText("Helix Biotech paid INV-2029 this morning.")} />}
/>
```

## Keyboard interactions

| Key | Action |
| --- | --- |
| `Tab` or `Shift+Tab` | Moves between the previous and next buttons and the rest of the row. |
| `Enter` or `Space` | On a chevron, shows the previous or next version. At either end the button is disabled but keeps focus. |
| `Alt+ArrowLeft` or `Alt+ArrowRight` | Anywhere inside the branch, shows the previous or next version. Ignored inside text fields, where it moves by word. |

## Accessibility

- The switcher is a `role="group"` named "Response versions" (from `label`). The chevrons are labelled "Previous response" and "Next response".
- The visible "2 / 3" is `aria-hidden`. A polite, atomic live region reads "Response 2 of 3" instead, so screen readers announce each switch.
- At the first or last version the chevron is disabled with `aria-disabled`, but it stays focusable, so focus does not drop to the page.
- Under reduced motion the cross-fade and the height change both use `{ duration: 0 }`, so the version swaps instantly.

## FAQ

### How do I show the new reply after the user clicks Regenerate?

Append it to `versions`. Uncontrolled, MessageBranch sees the count grow and shows the newest version. If you control `index`, set it yourself when you append, for example `setIndex(replies.length)`.

### How do I keep the chosen version after a reload?

Control it. Store the index with the message and pass `index` and `onIndexChange`. Without `index`, it starts on `defaultIndex`, which defaults to the newest version.

### Can the switcher sit in the same row as copy and retry?

Yes. Pass [`MessageActions`](https://ui.minidev.pro/docs/message-actions) as `actions` and it renders right after the "‹ 2 / 3 ›" switcher. While there is only one version the switcher hides itself and the actions stay.

### Should each version be a MessageBubble?

No. MessageBranch mounts the version again on every switch, and [`MessageBubble`](https://ui.minidev.pro/docs/message-bubble) plays a rise-in animation on mount, so it would run on top of the cross-fade. Wrap the whole branch instead: `<MessageBubble role="assistant"><MessageBranch versions={replies} /></MessageBubble>`.

## Rules for generating code

- Use semantic tokens only (bg, surface, sunken, border, fg, fg-muted, fg-subtle, ink, accent, success, warning, danger). Never raw hex or palette steps like blue-500.
- Shadows only from the set: shadow-xs, shadow-sm, shadow-raised, shadow-md, shadow-lg, shadow-overlay.
- Numbers use tabular-nums. Dark mode is the `dark` class on <html>; components never branch on theme.

## Dependencies

- npm: `lucide-react`, `motion`
- Built from: [icon-button](https://ui.minidev.pro/docs/icon-button/md)

## Related

- [Message Actions](https://ui.minidev.pro/docs/message-actions/md): A row of ghost icon buttons for chat replies: copy, retry, good response and bad response, each with an aria label and callback. Place it under AI messages.
- [Regenerate Bar](https://ui.minidev.pro/docs/regenerate-bar/md): Footer bar for AI answers with a Not quite right prompt, a Regenerate button with a refresh icon, and an optional Edit prompt action when onEdit is set.
- [Agent Trace](https://ui.minidev.pro/docs/agent-trace/md): React timeline of an AI agent run: each tool step shows pending, running, done or error, reports its duration and folds out details. The header sums up the run.
- [Ai Composer](https://ui.minidev.pro/docs/ai-composer/md): Chat input for AI apps with a multiline textarea, Enter to send, suggestion chips, attach button, model picker and a stop button while a response streams.
- [Artifact Preview](https://ui.minidev.pro/docs/artifact-preview/md): Framed preview for AI generated artifacts such as code, documents or UI, with a title bar, copy button and optional expand action for a full view.
- [Attachment Chip](https://ui.minidev.pro/docs/attachment-chip/md): Compact Tailwind file chip with a paperclip icon, truncated filename and an optional remove button, for attachments in chat composers, emails and forms.

---

All 557 components: https://ui.minidev.pro/llms.txt (full text: https://ui.minidev.pro/llms-full.txt).
