# Conversation (/docs/agent-ui/components/conversation)

Use a conversation to scroll the messages of a chat. It keeps the newest message in view while the reader is at the end, and lets go as soon as they scroll away.

<Example caption="Scroll up to read earlier messages, then press Jump to latest to return to the end and follow again.">
<h />

```tsx
import {
  Conversation,
  ConversationContent,
  ConversationJump,
  ConversationRow,
  ConversationViewport,
} from "@/components/ui/conversation";

const messages = [
  { id: "m1", role: "user", text: "The nightly export failed again. Can you take a look?" },
  { id: "m2", role: "assistant", text: "Sure. Which job is it, and when did it last succeed?" },
  { id: "m3", role: "user", text: "billing-export. It last succeeded on Tuesday." },
  {
    id: "m4",
    role: "assistant",
    text: "Since Wednesday, every run has stopped after 30 seconds waiting on the reports service. The service was slow, not down: its median response time went from 4 to 41 seconds.",
  },
  { id: "m5", role: "user", text: "So we just raise the timeout?" },
  {
    id: "m6",
    role: "assistant",
    text: "Raising it would get tonight's run through, but the job would still fail on the next slow night. I'd retry each page with backoff, cap the attempts at five, and alert when a run takes longer than an hour.",
  },
  { id: "m7", role: "user", text: "Do that, and open a pull request." },
  {
    id: "m8",
    role: "assistant",
    text: "Done. The pull request adds the retry and the alert, with a test that replays Wednesday's responses.",
  },
];

export default function ConversationExample() {
  return (
    <Conversation
      aria-label="Conversation"
      messageCount={messages.length}
      className="h-80 w-full max-w-xl rounded-xl border border-[var(--kind-color-border)]"
    >
      <ConversationViewport>
        <ConversationContent>
          {messages.map((message, index) => (
            <ConversationRow key={message.id} value={message.id} index={index}>
              <p
                className={
                  message.role === "user"
                    ? "ms-auto w-fit max-w-[80%] rounded-2xl bg-[var(--kind-color-hover)] px-3.5 py-2"
                    : undefined
                }
              >
                {message.text}
              </p>
            </ConversationRow>
          ))}
        </ConversationContent>
      </ConversationViewport>
      <ConversationJump />
    </Conversation>
  );
}
```
</Example>

## Installation [#installation]

```bash tab="React"
npx shadcn@latest add @kind-ui/conversation
```

```bash tab="Web Components"
npx shadcn@latest add @kind-ui/conversation-web
```

## Composition [#composition]

```text
Conversation
├── ConversationViewport
│   └── ConversationContent
│       └── ConversationRow
├── ConversationJump
└── ConversationEmpty
```

The viewport is the part that scrolls, and the content holds a `ConversationRow` for each message, with its `value` and `index`. `ConversationJump` renders a button that shows while the reader is away from the end. `ConversationEmpty` shows while there are no messages.

## Usage [#usage]

### Following New Messages [#following-new-messages]

Pass the number of messages as `messageCount`. While the reader is at the end, new messages and messages that grow as they stream stay in view. Once they scroll up, the conversation stops following and counts the messages that arrive. Scrolling back to the end follows again.

Each new row fades in once, when it mounts. A row that renders again, or a message that keeps streaming, doesn't replay it.

### Jump to Latest [#jump-to-latest]

While the reader is away from the end, `ConversationJump` shows **Jump to latest**, or the count, like **3 new messages**, once messages arrive. Pressing it scrolls to the end and follows again. The button writes its own text, so render it without children.

The conversation tells screen readers the new-message count politely as it grows. The viewport is a single Tab stop, so the keyboard can scroll the log even when nothing in it is focusable.

### Scrolling From Outside [#scrolling-from-outside]

Pass a `controller` from `createConversationController()` to scroll and read the conversation from your own code. Call its `scrollToEnd()` to jump to the newest message, for example after the person sends one. Before you add older messages above, call `prepend()`, so the reader keeps their place and the older messages aren't counted as new:

```tsx
import { createConversationController } from "@kind-ui/agent-ui/core";

const controller = createConversationController();

async function loadOlder() {
  const older = await fetchOlderMessages();
  controller.prepend();
  setMessages((messages) => [...older, ...messages]);
}
```

### Long Conversations [#long-conversations]

Pass `virtualize` to render only the rows in view. Render rows from the content's `rows`, keyed by index, and pass `rowKey` so each measured height stays with its message:

```tsx
<Conversation messageCount={messages.length} virtualize rowKey={(index) => messages[index].id}>
  <ConversationViewport>
    <ConversationContent>
      {({ rows }) =>
        rows.map((row) => (
          <ConversationRow key={row.index} value={row.key} index={row.index}>
            {messages[row.index].text}
          </ConversationRow>
        ))
      }
    </ConversationContent>
  </ConversationViewport>
  <ConversationJump />
</Conversation>
```

`virtualize` is read once, when the conversation mounts. Until a row is measured, it's `estimateRowHeight` tall.

## API Reference [#api-reference]

### ConversationOptions

| Prop                 | Type                                                    | Description                                                                                                                                      |
| -------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `messageCount?`      | `number \| undefined`                                   | How many messages the conversation holds. Drives the new-message count, the empty part and virtualization. Default: `0`                          |
| `virtualize?`        | `boolean \| undefined`                                  | Renders only the rows in view, with `createVirtualizer`. Read once, when the conversation mounts. Default: `false`                               |
| `estimateRowHeight?` | `number \| undefined`                                   | A row's height before it is measured, in pixels, with `virtualize`. Default: `120`                                                               |
| `rowKey?`            | `((index: number) => string) \| undefined`              | A stable key for the message at an index, so measured heights follow messages when the list changes, with `virtualize`. Default: `String(index)` |
| `onRowsChange?`      | `((rows: readonly VirtualItem[]) => void) \| undefined` | Called with the rows to render whenever they change, with `virtualize`.                                                                          |
| `controller?`        | `ConversationController \| undefined`                   | A handle from `createConversationController()`, to scroll and read the conversation from outside it.                                             |
| `motion?`            | `"auto" \| "none" \| "reduced"`                         | `"auto"` follows `prefers-reduced-motion`. Default: `"auto"`                                                                                     |

### Agent [#agent]

An agent connected with `createAgent` reads whether the conversation is `following` and its `newCount`. It can run this action, and press the jump control like a person would while it shows:

### ConversationAgentActions

| Prop          | Type         | Description                                                  |
| ------------- | ------------ | ------------------------------------------------------------ |
| `scrollToEnd` | `() => void` | Scrolls to the newest message and follows new content again. |

<Caption>
Runs in React and Web Components. On `<kind-conversation>`, each prop is a kebab-case attribute, so `messageCount` is `message-count`, `rowKey` and `controller` are properties, and each callback is a lowercase event, so `onRowsChange` fires `rowschange`. The element's `api` has the controller's methods: `scrollToEnd`, `prepend`, `isFollowing` and `getRows`.
</Caption>