# Connection Status (/docs/agent-ui/components/connection-status)

Use a connection status inside a [Conversation](./conversation.mdx) to say that replies can't arrive right now, and when the next try is. It floats over the top of the conversation, so it covers nothing below and moves nothing as it comes and goes.

<Example caption="Press Offline to drop the connection and disable the composer, or Reconnecting to count down to the next try. Press Retry in the pill, or Online, to get the connection back.">
  <ConnectionStatusExample />

  ```tsx tab="React"
  "use client";
  import { useState } from "react";
  import { Composer, ComposerInput, ComposerSubmit } from "@/components/ui/composer";
  import { ConnectionStatus } from "@/components/ui/connection-status";
  import {
    Conversation,
    ConversationContent,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/conversation";

  type Connection = "online" | "reconnecting" | "offline";

  const messages = [
    { id: "m1", role: "user", text: "Why did the deploy to staging stop halfway?" },
    {
      id: "m2",
      role: "assistant",
      text: "The migration step timed out waiting for a lock on the orders table. A long report query was holding it.",
    },
    { id: "m3", role: "user", text: "Can you rerun it once the query finishes?" },
  ];

  const states: Connection[] = ["online", "reconnecting", "offline"];

  const inFiveSeconds = () => new Date(Date.now() + 5000).toISOString();

  export default function ConnectionStatusExample() {
    const [state, setState] = useState<Connection>("reconnecting");
    const [retryAt, setRetryAt] = useState(inFiveSeconds);

    const choose = (next: Connection) => {
      if (next === "reconnecting") setRetryAt(inFiveSeconds());
      setState(next);
    };
    const retry = () =>
      new Promise<void>((resolve) => {
        setTimeout(() => {
          setState("online");
          resolve();
        }, 800);
      });

    return (
      <div className="flex w-full max-w-xl flex-col gap-3">
        <fieldset className="flex flex-wrap gap-1 self-start border-0 p-0 text-sm">
          <legend className="sr-only">Connection</legend>
          {states.map((option) => (
            <button
              key={option}
              type="button"
              aria-pressed={state === option}
              onClick={() => choose(option)}
              className="w-28 rounded-md border border-[var(--kind-color-border)] py-1 capitalize aria-pressed:bg-[var(--kind-color-hover)]"
            >
              {option}
            </button>
          ))}
        </fieldset>
        <Conversation
          aria-label="Conversation"
          messageCount={messages.length}
          className="h-56 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>
          <ConnectionStatus state={state} retryAt={retryAt} onRetry={retry} />
        </Conversation>
        <Composer aria-label="Message" disabled={state === "offline"}>
          <ComposerInput aria-label="Prompt" placeholder={state === "offline" ? "Offline" : "Ask anything"} />
          <ComposerSubmit />
        </Composer>
      </div>
    );
  }
  ```

  ```vue tab="Vue"
  <script setup lang="ts">
  import { ref } from "vue";
  import { Composer, ComposerInput, ComposerSubmit } from "@/components/ui/vue/composer";
  import { ConnectionStatus } from "@/components/ui/vue/connection-status";
  import {
    Conversation,
    ConversationContent,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/vue/conversation";

  type Connection = "online" | "reconnecting" | "offline";

  const messages = [
    { id: "m1", role: "user", text: "Why did the deploy to staging stop halfway?" },
    {
      id: "m2",
      role: "assistant",
      text: "The migration step timed out waiting for a lock on the orders table. A long report query was holding it.",
    },
    { id: "m3", role: "user", text: "Can you rerun it once the query finishes?" },
  ];

  const states: Connection[] = ["online", "reconnecting", "offline"];

  const inFiveSeconds = () => new Date(Date.now() + 5000).toISOString();

  const state = ref<Connection>("reconnecting");
  const retryAt = ref(inFiveSeconds());

  const choose = (next: Connection) => {
    if (next === "reconnecting") retryAt.value = inFiveSeconds();
    state.value = next;
  };
  const retry = () =>
    new Promise<void>((resolve) => {
      setTimeout(() => {
        state.value = "online";
        resolve();
      }, 800);
    });
  </script>

  <template>
    <div class="flex w-full max-w-xl flex-col gap-3">
      <fieldset class="flex flex-wrap gap-1 self-start border-0 p-0 text-sm">
        <legend class="sr-only">Connection</legend>
        <button
          v-for="option in states"
          :key="option"
          type="button"
          :aria-pressed="state === option"
          class="w-28 rounded-md border border-[var(--kind-color-border)] py-1 capitalize aria-pressed:bg-[var(--kind-color-hover)]"
          @click="choose(option)"
        >
          {{ option }}
        </button>
      </fieldset>
      <Conversation
        aria-label="Conversation"
        :message-count="messages.length"
        class="h-56 rounded-xl border border-[var(--kind-color-border)]"
      >
        <ConversationViewport>
          <ConversationContent>
            <ConversationRow v-for="(message, index) in messages" :key="message.id" :value="message.id" :index="index">
              <p
                :class="
                  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>
        <ConnectionStatus :state="state" :retry-at="retryAt" :on-retry="retry" />
      </Conversation>
      <Composer aria-label="Message" :disabled="state === 'offline'">
        <ComposerInput aria-label="Prompt" :placeholder="state === 'offline' ? 'Offline' : 'Ask anything'" />
        <ComposerSubmit />
      </Composer>
    </div>
  </template>
  ```

  ```svelte tab="Svelte"
  <script lang="ts">
    import { Composer, ComposerInput, ComposerSubmit } from "@/components/ui/svelte/composer/index.js";
    import { ConnectionStatus } from "@/components/ui/svelte/connection-status/index.js";
    import {
      Conversation,
      ConversationContent,
      ConversationRow,
      ConversationViewport,
    } from "@/components/ui/svelte/conversation/index.js";

    type Connection = "online" | "reconnecting" | "offline";

    const messages = [
      { id: "m1", role: "user", text: "Why did the deploy to staging stop halfway?" },
      {
        id: "m2",
        role: "assistant",
        text: "The migration step timed out waiting for a lock on the orders table. A long report query was holding it.",
      },
      { id: "m3", role: "user", text: "Can you rerun it once the query finishes?" },
    ];

    const states: Connection[] = ["online", "reconnecting", "offline"];

    const inFiveSeconds = () => new Date(Date.now() + 5000).toISOString();

    let connection: Connection = $state("reconnecting");
    let retryAt = $state(inFiveSeconds());

    const choose = (next: Connection) => {
      if (next === "reconnecting") retryAt = inFiveSeconds();
      connection = next;
    };
    const retry = () =>
      new Promise<void>((resolve) => {
        setTimeout(() => {
          connection = "online";
          resolve();
        }, 800);
      });
  </script>

  <div class="flex w-full max-w-xl flex-col gap-3">
    <fieldset class="flex flex-wrap gap-1 self-start border-0 p-0 text-sm">
      <legend class="sr-only">Connection</legend>
      {#each states as option (option)}
        <button
          type="button"
          aria-pressed={connection === option}
          onclick={() => choose(option)}
          class="w-28 rounded-md border border-[var(--kind-color-border)] py-1 capitalize aria-pressed:bg-[var(--kind-color-hover)]"
        >
          {option}
        </button>
      {/each}
    </fieldset>
    <Conversation
      aria-label="Conversation"
      messageCount={messages.length}
      class="h-56 rounded-xl border border-[var(--kind-color-border)]"
    >
      <ConversationViewport>
        <ConversationContent>
          {#each messages as message, index (message.id)}
            <ConversationRow value={message.id} {index}>
              <p
                class={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>
          {/each}
        </ConversationContent>
      </ConversationViewport>
      <ConnectionStatus state={connection} {retryAt} onRetry={retry} />
    </Conversation>
    <Composer aria-label="Message" disabled={connection === "offline"}>
      <ComposerInput aria-label="Prompt" placeholder={connection === "offline" ? "Offline" : "Ask anything"} />
      <ComposerSubmit />
    </Composer>
  </div>
  ```

  ```tsx tab="Solid"
  import { createSignal, For } from "solid-js";
  import { Composer, ComposerInput, ComposerSubmit } from "@/components/ui/solid/composer";
  import { ConnectionStatus } from "@/components/ui/solid/connection-status";
  import {
    Conversation,
    ConversationContent,
    ConversationRow,
    ConversationViewport,
  } from "@/components/ui/solid/conversation";

  type Connection = "online" | "reconnecting" | "offline";

  const messages = [
    { id: "m1", role: "user", text: "Why did the deploy to staging stop halfway?" },
    {
      id: "m2",
      role: "assistant",
      text: "The migration step timed out waiting for a lock on the orders table. A long report query was holding it.",
    },
    { id: "m3", role: "user", text: "Can you rerun it once the query finishes?" },
  ];

  const states: Connection[] = ["online", "reconnecting", "offline"];

  const inFiveSeconds = () => new Date(Date.now() + 5000).toISOString();

  export default function ConnectionStatusExample() {
    const [state, setState] = createSignal<Connection>("reconnecting");
    const [retryAt, setRetryAt] = createSignal(inFiveSeconds());

    const choose = (next: Connection) => {
      if (next === "reconnecting") setRetryAt(inFiveSeconds());
      setState(next);
    };
    const retry = () =>
      new Promise<void>((resolve) => {
        setTimeout(() => {
          setState("online");
          resolve();
        }, 800);
      });

    return (
      <div class="flex w-full max-w-xl flex-col gap-3">
        <fieldset class="flex flex-wrap gap-1 self-start border-0 p-0 text-sm">
          <legend class="sr-only">Connection</legend>
          <For each={states}>
            {(option) => (
              <button
                type="button"
                aria-pressed={state() === option ? "true" : "false"}
                onClick={() => choose(option)}
                class="w-28 rounded-md border border-[var(--kind-color-border)] py-1 capitalize aria-pressed:bg-[var(--kind-color-hover)]"
              >
                {option}
              </button>
            )}
          </For>
        </fieldset>
        <Conversation
          aria-label="Conversation"
          messageCount={messages.length}
          class="h-56 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()}>
                    <p
                      class={
                        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>
                )}
              </For>
            </ConversationContent>
          </ConversationViewport>
          <ConnectionStatus state={state()} retryAt={retryAt()} onRetry={retry} />
        </Conversation>
        <Composer aria-label="Message" disabled={state() === "offline"}>
          <ComposerInput aria-label="Prompt" placeholder={state() === "offline" ? "Offline" : "Ask anything"} />
          <ComposerSubmit />
        </Composer>
      </div>
    );
  }
  ```
</Example>

## Installation [#installation]

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

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

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

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

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

## Composition [#composition]

```text
ConnectionStatus
├── ConnectionStatusMark
├── ConnectionStatusText
└── ConnectionStatusRetry
```

`ConnectionStatus` renders these parts: a group named by its state's words. `ConnectionStatusMark` is the status mark, a spinner while connecting, reconnecting, resuming or retrying and a warning while offline. `ConnectionStatusText` shows the state's words, or the countdown while reconnecting, and `ConnectionStatusRetry` is the **Retry** button. To arrange the parts yourself, render them inside `ConnectionStatusRoot`.

## Usage [#usage]

### Placement [#placement]

Put the connection status inside the `Conversation`, beside its viewport. It's positioned over the top edge of the conversation, centered, so showing it changes no layout.

```tsx
<Conversation aria-label="Conversation" messageCount={messages.length}>
  <ConversationViewport>…</ConversationViewport>
  <ConnectionStatus state={state} />
</Conversation>
```

### States [#states]

Pass `state` as `"online"` (the default), `"connecting"`, `"reconnecting"` or `"offline"`. The pill shows **Connecting**, **Reconnecting** or **Offline** while the state isn't `online`, and fades out when it turns `online`, still showing the last state's words as it leaves.

After a reconnect, pass `resuming` while a stream picks up where it stopped. With `state="online"`, the pill shows **Resuming** until you set it back to `false`.

What the rest of the page does while the connection is down is up to you. The example disables the `Composer` while offline, so nothing is typed that can't be sent.

### Countdown [#countdown]

While `reconnecting`, pass `retryAt`, an ISO 8601 time, to count down to the next try: **Retrying in 5 s**. The number changes on each whole second and the pill shows **Reconnecting** once it reaches 0. Pass a new `retryAt` for each try.

```tsx
<ConnectionStatus state="reconnecting" retryAt={new Date(Date.now() + 5000).toISOString()} />
```

### Retry [#retry]

Pass `onRetry` to show **Retry** while the connection is down. It isn't shown while `resuming`, since the connection is back, and a retry still pending then no longer holds **Retry** in the next outage. Return a promise to show **Reconnecting** in place of **Retry** until it settles; change `state` once the connection is back. If **Retry** has focus when it hides or the pill leaves, focus moves on to the next element Tab reaches.

```tsx
<ConnectionStatus state={state} onRetry={() => reconnect()} />
```

### Announcements [#announcements]

The pill isn't a live region, so it never reads the countdown. When the connection drops, to `reconnecting` or `offline`, **Connection lost** is announced once, and when it's `online` again (or `resuming`), **Reconnected** is announced once. A connection that's already down as the page loads isn't announced. Pass `labels` to change any of these words, for another language or tone.

### Motion [#motion]

The pill fades in as it drops into place, and fades out where it is. Under `prefers-reduced-motion`, or with `motion="reduced"`, it only fades, and with `motion="none"` it comes and goes at once.

## API Reference [#api-reference]

### ConnectionStatusOptions

| Prop        | Type                                                                | Description                                                                                                                                                                                                                                                  |
| ----------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `state?`    | `"connecting" \| "offline" \| "online" \| "reconnecting"`           | Where the connection stands. The pill shows while it isn't `online`, and fades out when it turns `online`. Default: `"online"`                                                                                                                               |
| `resuming?` | `boolean \| undefined`                                              | Whether a stream is picking up after a reconnect. Shows "Resuming", without Retry, while `state` is `online`. Default: `false`                                                                                                                               |
| `retryAt?`  | `string \| undefined`                                               | When the next try starts (ISO 8601). While `reconnecting`, the pill counts down to it, and shows "Reconnecting" once it's past or when it can't be read.                                                                                                     |
| `onRetry?`  | `((details: ConnectionStatusRetryDetails) => unknown) \| undefined` | Called when Retry is pressed. Shows Retry while set and the connection is down (not `online` or resuming). Return a promise to show "Reconnecting", without Retry, until it settles; a rejection or a throw offers Retry again, and so does the next outage. |
| `labels?`   | `Partial<ConnectionStatusLabels> \| undefined`                      | The words to show and announce, for another language or tone. Each one left out keeps its English default.                                                                                                                                                   |
| `motion?`   | `"auto" \| "none" \| "reduced"`                                     | How the pill comes and goes: at full motion it drops in and fades out, a 120 ms fade with reduced motion, at once with `"none"`. `"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     |
| --------- | -------- | --------- | --------- |
| `onRetry` | `@retry` | `onRetry` | `onRetry` |

### Agent [#agent]

An agent connected with `createAgent` finds the connection status by its state's words, and sees its `phase` and whether a retry is `pending`. `retry()` does what **Retry** does, offered while `onRetry` is set, the pill shows and no retry is pending. It doesn't ask a person first.

### ConnectionStatusAgentActions

| Prop    | Type                                     | Description                                                                                                     |
| ------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `retry` | `((event?: Event) => void) \| undefined` | Calls `onRetry`, as Retry does. Offered while `onRetry` is set, the connection is down and no retry is pending. |

<Caption>
  Runs in React, Vue, Svelte, Solid and Web Components. On `<kind-connection-status>`, props are kebab-case attributes (`state="offline"`, `retry-at`) and `labels` is a property. The element adds its mark, words and Retry. The `can-retry` attribute shows Retry, which fires `connectionretry`: call `event.detail.waitUntil(promise)` to show **Reconnecting** until the promise settles.
</Caption>
