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

Use a conversation search to let readers find something said earlier in a long chat. It searches every message, including the ones a virtualized [Conversation](./conversation.mdx) hasn't rendered, counts the matches, scrolls to the current one and marks each message that holds one beside the scrollbar.

<Example caption="Type in the search field, or keep billing, then press Enter or Next to move to the next match and Shift+Enter or Previous to go back. Press Escape to clear the search, and again to close the bar.">
  <ConversationSearchExample />

  ```tsx tab="React"
  "use client";

  import { createConversationController } from "@kind-ui/agent-ui/core";
  import { memo, useState } from "react";
  import {
    Conversation,
    ConversationContent,
    ConversationMarks,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/conversation";
  import { ConversationSearch } from "@/components/ui/conversation-search";
  import { Markdown } from "@/components/ui/markdown";

  const messages = [
    { id: "m1", role: "user", text: "The nightly **billing** 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:\n\n- its median response time went from 4 to 41 seconds\n- it was slow, not down",
    },
    { id: "m5", role: "user", text: "So we just raise the timeout?" },
    {
      id: "m6",
      role: "assistant",
      text: "That gets tonight's run through, but the next slow night fails again. I'd **retry** each page with backoff and alert when a run takes longer than an hour.",
    },
    { id: "m7", role: "user", text: "Do that, and open a pull request against the billing service." },
    {
      id: "m8",
      role: "assistant",
      text: "Done. The pull request adds the retry and the alert, with a test that replays Wednesday's slow responses.",
    },
  ];

  type ChatMessage = (typeof messages)[number];

  const Row = memo(function Row({ message, index }: { message: ChatMessage; index: number }) {
    return (
      <ConversationRow value={message.id} index={index}>
        <div
          className={
            message.role === "user"
              ? "ms-auto w-fit max-w-[80%] rounded-2xl bg-[var(--kind-color-hover)] px-3.5 py-2"
              : undefined
          }
        >
          <Markdown source={message.text} />
        </div>
      </ConversationRow>
    );
  });

  export default function ConversationSearchExample() {
    const [controller] = useState(createConversationController);
    const [marks, setMarks] = useState<readonly number[]>([]);

    return (
      <div className="relative h-[360px] w-full max-w-xl">
        <ConversationSearch
          messages={messages}
          conversation={controller}
          defaultOpen
          defaultQuery="billing"
          onMarksChange={setMarks}
        />
        <Conversation
          aria-label="Conversation"
          messageCount={messages.length}
          controller={controller}
          marks={marks}
          className="h-full rounded-xl border border-[var(--kind-color-border)]"
        >
          <ConversationViewport>
            <ConversationContent>
              {messages.map((message, index) => (
                <Row key={message.id} message={message} index={index} />
              ))}
            </ConversationContent>
          </ConversationViewport>
          <ConversationMarks />
        </Conversation>
      </div>
    );
  }
  ```

  ```vue tab="Vue"
  <script setup lang="ts">
  import { createConversationController } from "@kind-ui/agent-ui/core";
  import { defineComponent, h, type PropType, shallowRef } from "vue";
  import {
    Conversation,
    ConversationContent,
    ConversationMarks,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/vue/conversation";
  import { ConversationSearch } from "@/components/ui/vue/conversation-search";
  import { Markdown } from "@/components/ui/vue/markdown";

  const messages = [
    { id: "m1", role: "user", text: "The nightly **billing** 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:\n\n- its median response time went from 4 to 41 seconds\n- it was slow, not down",
    },
    { id: "m5", role: "user", text: "So we just raise the timeout?" },
    {
      id: "m6",
      role: "assistant",
      text: "That gets tonight's run through, but the next slow night fails again. I'd **retry** each page with backoff and alert when a run takes longer than an hour.",
    },
    { id: "m7", role: "user", text: "Do that, and open a pull request against the billing service." },
    {
      id: "m8",
      role: "assistant",
      text: "Done. The pull request adds the retry and the alert, with a test that replays Wednesday's slow responses.",
    },
  ];

  type ChatMessage = (typeof messages)[number];

  // Its own component, so a new search renders no message whose props stayed the same.
  const Row = defineComponent({
    props: {
      message: { type: Object as PropType<ChatMessage>, required: true },
      index: { type: Number, required: true },
    },
    setup(props) {
      return () =>
        h(ConversationRow, { value: props.message.id, index: props.index }, () =>
          h(
            "div",
            {
              class:
                props.message.role === "user"
                  ? "ms-auto w-fit max-w-[80%] rounded-2xl bg-[var(--kind-color-hover)] px-3.5 py-2"
                  : undefined,
            },
            h(Markdown, { source: props.message.text }),
          ),
        );
    },
  });

  const controller = createConversationController();
  const marks = shallowRef<readonly number[]>([]);
  </script>

  <template>
    <div class="relative h-[360px] w-full max-w-xl">
      <ConversationSearch
        :messages="messages"
        :conversation="controller"
        default-open
        default-query="billing"
        @marks-change="(next: readonly number[]) => (marks = next)"
      />
      <Conversation
        aria-label="Conversation"
        :message-count="messages.length"
        :controller="controller"
        :marks="marks"
        class="h-full rounded-xl border border-[var(--kind-color-border)]"
      >
        <ConversationViewport>
          <ConversationContent>
            <Row v-for="(message, index) in messages" :key="message.id" :message="message" :index="index" />
          </ConversationContent>
        </ConversationViewport>
        <ConversationMarks />
      </Conversation>
    </div>
  </template>
  ```

  ```svelte tab="Svelte"
  <script lang="ts">
    import { createConversationController } from "@kind-ui/agent-ui/core";
    import {
      Conversation,
      ConversationContent,
      ConversationMarks,
      ConversationRow,
      ConversationViewport,
    } from "@/components/ui/svelte/conversation/index.js";
    import { ConversationSearch } from "@/components/ui/svelte/conversation-search/index.js";
    import { Markdown } from "@/components/ui/svelte/markdown/index.js";

    const messages = [
      { id: "m1", role: "user", text: "The nightly **billing** 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:\n\n- its median response time went from 4 to 41 seconds\n- it was slow, not down",
      },
      { id: "m5", role: "user", text: "So we just raise the timeout?" },
      {
        id: "m6",
        role: "assistant",
        text: "That gets tonight's run through, but the next slow night fails again. I'd **retry** each page with backoff and alert when a run takes longer than an hour.",
      },
      { id: "m7", role: "user", text: "Do that, and open a pull request against the billing service." },
      {
        id: "m8",
        role: "assistant",
        text: "Done. The pull request adds the retry and the alert, with a test that replays Wednesday's slow responses.",
      },
    ];

    const controller = createConversationController();
    let marks: readonly number[] = $state.raw([]);
  </script>

  <div class="relative h-[360px] w-full max-w-xl">
    <ConversationSearch
      {messages}
      conversation={controller}
      defaultOpen
      defaultQuery="billing"
      onMarksChange={(next) => (marks = next)}
    />
    <Conversation
      aria-label="Conversation"
      messageCount={messages.length}
      {controller}
      {marks}
      class="h-full rounded-xl border border-[var(--kind-color-border)]"
    >
      <ConversationViewport>
        <ConversationContent>
          {#each messages as message, index (message.id)}
            <ConversationRow value={message.id} {index}>
              <div
                class={message.role === "user"
                  ? "ms-auto w-fit max-w-[80%] rounded-2xl bg-[var(--kind-color-hover)] px-3.5 py-2"
                  : undefined}
              >
                <Markdown source={message.text} />
              </div>
            </ConversationRow>
          {/each}
        </ConversationContent>
      </ConversationViewport>
      <ConversationMarks />
    </Conversation>
  </div>
  ```

  ```tsx tab="Solid"
  import { createConversationController } from "@kind-ui/agent-ui/core";
  import { createSignal, For } from "solid-js";
  import {
    Conversation,
    ConversationContent,
    ConversationMarks,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/solid/conversation";
  import { ConversationSearch } from "@/components/ui/solid/conversation-search";
  import { Markdown } from "@/components/ui/solid/markdown";

  const messages = [
    { id: "m1", role: "user", text: "The nightly **billing** 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:\n\n- its median response time went from 4 to 41 seconds\n- it was slow, not down",
    },
    { id: "m5", role: "user", text: "So we just raise the timeout?" },
    {
      id: "m6",
      role: "assistant",
      text: "That gets tonight's run through, but the next slow night fails again. I'd **retry** each page with backoff and alert when a run takes longer than an hour.",
    },
    { id: "m7", role: "user", text: "Do that, and open a pull request against the billing service." },
    {
      id: "m8",
      role: "assistant",
      text: "Done. The pull request adds the retry and the alert, with a test that replays Wednesday's slow responses.",
    },
  ];

  export default function ConversationSearchExample() {
    const controller = createConversationController();
    const [marks, setMarks] = createSignal<readonly number[]>([]);

    return (
      <div class="relative h-[360px] w-full max-w-xl">
        <ConversationSearch
          messages={messages}
          conversation={controller}
          defaultOpen
          defaultQuery="billing"
          onMarksChange={setMarks}
        />
        <Conversation
          aria-label="Conversation"
          messageCount={messages.length}
          controller={controller}
          marks={marks()}
          class="h-full rounded-xl border border-[var(--kind-color-border)]"
        >
          <ConversationViewport>
            <ConversationContent>
              <For each={messages} keyed={(message) => message.id}>
                {(message, index) => (
                  <ConversationRow value={message().id} index={index()}>
                    <div
                      class={
                        message().role === "user"
                          ? "ms-auto w-fit max-w-[80%] rounded-2xl bg-[var(--kind-color-hover)] px-3.5 py-2"
                          : undefined
                      }
                    >
                      <Markdown source={message().text} />
                    </div>
                  </ConversationRow>
                )}
              </For>
            </ConversationContent>
          </ConversationViewport>
          <ConversationMarks />
        </Conversation>
      </div>
    );
  }
  ```
</Example>

## Installation [#installation]

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

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

```bash tab="Vue"
npx shadcn@latest add @kind-ui/conversation-search-vue
```

```bash tab="Svelte"
npx shadcn@latest add @kind-ui/conversation-search-svelte
```

```bash tab="Solid"
npx shadcn@latest add @kind-ui/conversation-search-solid
```

## Composition [#composition]

```text
ConversationSearch
├── ConversationSearchInput
│   └── ConversationSearchCount
├── ConversationSearchPrevious
├── ConversationSearchNext
└── ConversationSearchClose
```

`ConversationSearchInput` renders a UI SDK Input, and `ConversationSearchCount` inside it says where you are, like "3 of 12", or "0 of 0" in red when nothing matches. `ConversationSearchPrevious` and `ConversationSearchNext` move between matches, and `ConversationSearchClose` closes the bar. Render `ConversationSearch` without children to get all of them; the buttons draw their icons in CSS, so render them empty when you arrange the parts yourself.

## Usage [#usage]

### Connecting a Conversation [#connecting-a-conversation]

The bar floats over the top end of the conversation without taking room, so put `ConversationSearch` and `Conversation` in one box with `position: relative`. Make one controller with `createConversationController()` and pass it to Conversation's `controller` and the search's `conversation`: the search scrolls to a match and finds the rows to paint through it.

Pass `onMarksChange` a setter for Conversation's `marks`, and render `ConversationMarks` inside the Conversation to show where the matches are beside the scrollbar:

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

export function Chat({ messages }: { messages: { id: string; text: string }[] }) {
  const [controller] = useState(createConversationController);
  const [marks, setMarks] = useState<readonly number[]>([]);

  return (
    <div className="relative h-96">
      <ConversationSearch messages={messages} conversation={controller} onMarksChange={setMarks} />
      <Conversation messageCount={messages.length} controller={controller} marks={marks} className="h-full">
        <ConversationViewport>{/* rows */}</ConversationViewport>
        <ConversationMarks />
      </Conversation>
    </div>
  );
}
```

Render each row as a component wrapped in React's `memo`, so a change of `marks` renders only the marks, not every message and its Markdown.

### Messages [#messages]

Pass `messages` as `{ id, text }`, in the Conversation's order, so a match's index is its row's index. `text` is the message's Markdown, which the search reads as the text it renders: syntax, link targets and a shown image's alt text don't match, and no match runs across blocks, list items or table cells. Case and accents fold, so "cafe" finds "Café". A message that streams is searched again as it grows.

### Moving Between Matches [#moving-between-matches]

The search starts on the first match in the newest message that holds one, and moving scrolls its message into view. Next goes to the following match and wraps from the last to the first; Previous goes back. Both are disabled while nothing matches. The count is announced politely once typing pauses.

Matches are painted with the CSS Custom Highlight API, as `::highlight(kind-search)` and `::highlight(kind-search-current)`, so no markup is written into the messages. A browser without the API still counts, moves and marks the scrollbar.

### Opening and Closing [#opening-and-closing]

The bar is closed until you open it: pass `defaultOpen`, control it with `open` and `onOpenChange`, or give it a `shortcut`. Opening moves focus to the field. Closing keeps the search, takes the marks and highlights away, and moves focus back to what had it before the bar opened. Pass `defaultQuery` to start with a search, or control it with `query` and `onQueryChange`.

### Keyboard [#keyboard]

In the field, Enter goes to the next match and Shift+Enter to the previous one. F3 and Shift+F3 do the same anywhere in the bar. Escape clears the search, and a second Escape closes the bar.

### Shortcut [#shortcut]

The search registers no keys of its own by default. Pass `shortcut` to open it with a key, through UI SDK's shortcuts; pressing it while the bar is open moves focus back to the field:

```tsx
<ConversationSearch shortcut="mod+f" messages={messages} conversation={controller} onMarksChange={setMarks} />
```

`mod+f` replaces the browser's own find. That's worth it for a virtualized conversation, since the browser's find can't reach messages that aren't rendered and this search can.

## API Reference [#api-reference]

### ConversationSearchOptions

| Prop             | Type                                                                                                  | Description                                                                                                                                                                                        |
| ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages?`      | `ConversationSearchMessage[] \| undefined`                                                            | The conversation's messages, in its order, so a match's index is its message's index in the Conversation. Default: `[]`                                                                            |
| `conversation?`  | `ConversationController \| undefined`                                                                 | The Conversation's controller, from `createConversationController()`, to scroll to a match and paint it.                                                                                           |
| `query?`         | `string \| undefined`                                                                                 | The search. Passing it controls it: change it in `onQueryChange`.                                                                                                                                  |
| `defaultQuery?`  | `string \| undefined`                                                                                 | The search at first, when `query` isn't passed. Default: `""`                                                                                                                                      |
| `onQueryChange?` | `((query: string, details: ChangeDetails<ConversationSearchQueryChangeReason>) => void) \| undefined` | Called when the search changes, with why.                                                                                                                                                          |
| `open?`          | `boolean \| undefined`                                                                                | Whether the bar shows. Passing it controls it: change it in `onOpenChange`.                                                                                                                        |
| `defaultOpen?`   | `boolean \| undefined`                                                                                | Whether the bar shows at first, when `open` isn't passed. Default: `false`                                                                                                                         |
| `onOpenChange?`  | `((open: boolean, details: ChangeDetails<ConversationSearchOpenChangeReason>) => void) \| undefined`  | Called when the bar opens or closes, with why. Opening moves focus to the field; closing moves it back.                                                                                            |
| `label?`         | `string \| undefined`                                                                                 | Names the search. Default: `"Search in conversation"`                                                                                                                                              |
| `shortcut?`      | `string \| undefined`                                                                                 | Keys that open the bar, like `"mod+f"`, through UI SDK's shortcuts. None by default: `"mod+f"` replaces the browser's find, which can't reach messages a virtualized conversation hasn't rendered. |
| `onMarksChange?` | `((indexes: readonly number[]) => void) \| undefined`                                                 | Called with the indexes of the messages that hold a match whenever they change: pass them to Conversation's `marks`.                                                                               |
| `motion?`        | `"auto" \| "none" \| "reduced"`                                                                       | `"auto"` follows `prefers-reduced-motion`. Default: `"auto"`                                                                                                                                       |

Vue, Svelte and Solid take the same props. Controlled props and callbacks are spelled as each framework expects:

| React                    | Vue                              | Svelte                        | Solid                    |
| ------------------------ | -------------------------------- | ----------------------------- | ------------------------ |
| `query`, `onQueryChange` | `v-model:query`, `@query-change` | `bind:query`, `onQueryChange` | `query`, `onQueryChange` |
| `open`, `onOpenChange`   | `v-model:open`, `@open-change`   | `bind:open`, `onOpenChange`   | `open`, `onOpenChange`   |
| `onMarksChange`          | `@marks-change`                  | `onMarksChange`               | `onMarksChange`          |

### Agent [#agent]

An agent connected with `createAgent` finds the search by its `label` and reads `query` and `open`. It can `search` with any text, which opens the bar and searches as typing does; `next` and `previous` are offered while there are matches, and `close` while the bar is open.

### ConversationSearchAgentActions

| Prop       | Type                        | Description                                                                                   |
| ---------- | --------------------------- | --------------------------------------------------------------------------------------------- |
| `search`   | `(text: string) => boolean` | Opens the bar and searches for `text`, as typing does. Returns whether it was accepted.       |
| `next`     | `(() => void) \| undefined` | Moves to the next match, after the last back to the first. Only while there are matches.      |
| `previous` | `(() => void) \| undefined` | Moves to the previous match, before the first back to the last. Only while there are matches. |
| `close`    | `(() => void) \| undefined` | Closes the bar, keeping the search. Only while it's open.                                     |

<Caption>
  Runs in React, Vue, Svelte, Solid and Web Components. On `<kind-conversation-search>`, set `messages` and `conversation` (the controller you also set on the `<kind-conversation>`) as properties; the other props are kebab-case attributes. `onQueryChange` is the `querychange` event, `onOpenChange` is `openchange`, and `onMarksChange` is `markschange`, whose `detail.value` goes to the Conversation's `marks`. On `<kind-conversation>`, add a `kind-conversation-marks` and the element fills it with a `kind-conversation-mark` for each mark.
</Caption>
