# Chat

Lay out a conversation with a transcript, status, and optional reply box.

## Preview

chat-preview-1.jsx

```jsx
import {
  useEffect as useEffect4,
  useRef as useRef4,
  useState as useState5,
} from "react";
import {
  Chat,
  ChatContent,
  ChatFooter,
  ChatHeader,
} from "@/components/ui/chat";
import {
  Conversation as Conversation3,
  ConversationContent as ConversationContent3,
  ConversationItem as ConversationItem3,
} from "@/components/ui/conversation";
import {
  Message as Message3,
  MessageBody as MessageBody3,
} from "@/components/ui/message";
import { MessageParts as MessageParts2 } from "@/components/ui/message-parts";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";

export default function Example() {
  const [items, setItems] = useState5([
    {
      id: "welcome-user",
      actor: "user",
      parts: [
        {
          type: "text",
          text: "Can you check the April receipt?",
        },
      ],
    },
    {
      id: "welcome-answer",
      actor: "assistant",
      parts: [
        {
          type: "text",
          text: "I found the April receipt. Ask about its total or delivery.",
        },
      ],
    },
  ]);
  const run = useRef4(0);
  const cancelStream = useRef4(() => {});
  useEffect4(
    () => () => {
      run.current += 1;
      cancelStream.current();
    },
    [],
  );
  return (
    <div data-preview-wide>
      <Chat label="Receipt support chat">
        <ChatHeader>
          <h2>Receipt support</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation3 label="Receipt conversation">
            <ConversationContent3>
              {items.map((item) => {
                return (
                  <ConversationItem3 key={item.id} id={item.id} message={item}>
                    <Message3 actor={item.actor} status={item.status}>
                      <MessageBody3>
                        <MessageParts2 parts={item.parts} />
                      </MessageBody3>
                    </Message3>
                  </ConversationItem3>
                );
              })}
            </ConversationContent3>
          </Conversation3>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            defaultValue="Keep the receipt context in the answer."
            onSubmit={(submission, context) => {
              cancelStream.current();
              const currentRun = ++run.current;
              const assistantId = `assistant-${currentRun}`;
              setItems((current) => [
                ...current.map((item) =>
                  item.status === "streaming"
                    ? {
                        ...item,
                        status: "stopped",
                      }
                    : item,
                ),
                userMessage(`user-${current.length}`, submission),
                {
                  id: assistantId,
                  actor: "assistant",
                  status: "streaming",
                  parts: [
                    {
                      type: "text",
                      text: "",
                    },
                  ],
                },
              ]);
              cancelStream.current = streamWords(
                localReply(submission, context),
                (text, done) => {
                  if (currentRun !== run.current) return;
                  setItems((current) =>
                    current.map((item) =>
                      item.id === assistantId
                        ? {
                            ...item,
                            status: done ? "complete" : "streaming",
                            parts: [
                              {
                                type: "text",
                                text,
                              },
                            ],
                          }
                        : item,
                    ),
                  );
                },
              );
            }}
          />
        </ChatFooter>
      </Chat>
    </div>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function localReply(submission, context) {
  const model =
    MODEL_OPTIONS.find(({ value }) => value === context.model)?.label ??
    context.model;
  const subject = submission.text.toLowerCase().includes("receipt")
    ? "the receipt"
    : "this receipt task";
  return `I\u2019ll use ${model} to help with ${subject}. The receipt details are ready.`;
}

function userMessage(id, submission) {
  const files = submission.attachments.map((file) => ({
    type: "file",
    ...file,
  }));
  return {
    id,
    actor: "user",
    parts: [
      ...files,
      {
        type: "text",
        text: submission.text,
      },
    ],
  };
}

function streamWords(text, onText) {
  const words = text.match(/\S+\s*/g) ?? [];
  let index = 0;
  let timer = 0;
  const next = () => {
    index = Math.min(words.length, index + 2);
    onText(words.slice(0, index).join(""), index === words.length);
    if (index < words.length) timer = window.setTimeout(next, 55);
  };
  next();
  return () => window.clearTimeout(timer);
}

```

chat-preview-1.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

/* apps/web/src/demos/component-thumbnails.css */

```

## Design guidance

Put your message history in ChatContent. Add ChatFooter when people can reply. Keep messages, transport, and run state in your app or SDK hook.

## Installation

For editable source, add Chat and Message parts with shadcn. Add only the adapter for the SDK you use. For package imports and styling, follow [AI interfaces setup](/libraries/ai#installation).

```sh
npx shadcn@latest add https://ghost-ui.com/r/chat.json
```

```sh
npx shadcn@latest add https://ghost-ui.com/r/message-parts.json
```

```sh
npx shadcn@latest add https://ghost-ui.com/r/chat-adapter-ai-sdk.json
```

```sh
npx shadcn@latest add https://ghost-ui.com/r/chat-adapter-tanstack.json
```

To copy the Vercel example, install its SDK packages.

```bash
npm install ai@7.0.138 @ai-sdk/react@4.0.141
```

For the TanStack example, use the [TanStack AI setup](/libraries/ai-runtime-tanstack#start). The previews use local transports. Connect your own server to run a real conversation.

Convert Composer attachments to the format your SDK expects. Upload files first when the provider needs a URL, then give that URL to the SDK hook. Your app supplies the upload flow and credentials.

## Basic usage

```tsx
import { Chat, ChatContent } from "@/components/ui/chat";

export function ChatExample() {
  return (
    <Chat label="Support chat">
      <ChatContent>Receipt found.</ChatContent>
    </Chat>
  );
}
```

Use ChatContent for the caller-owned transcript. Add ChatHeader, ChatFooter, or ChatStatus only when that task needs them. Add a Composer in the footer when the conversation accepts input.

Chat defaults to a 42rem height, capped by the viewport or the host's --available-height. The transcript fills the space left by the header and input dock. For a full-height application panel, give the parent a definite height and set style={{ blockSize: "100%", maxBlockSize: "100%" }} on Chat. Use an explicit blockSize for a compact embedded chat.

## Structures

- Chat
  - ChatHeader (optional)
  - ChatContent
  - ChatFooter (optional)
  - ChatStatus (optional)

## Examples

Compare human, assistant, and read-only modes, then review rich responses and questionnaire workflows.

### Human support chat

Keep the transcript and composer in one complete support task.

chat-human-support-chat-2.jsx

```jsx
import {
  useEffect as useEffect4,
  useRef as useRef4,
  useState as useState5,
} from "react";
import {
  Chat,
  ChatContent,
  ChatFooter,
  ChatHeader,
} from "@/components/ui/chat";
import {
  Conversation as Conversation3,
  ConversationContent as ConversationContent3,
  ConversationItem as ConversationItem3,
} from "@/components/ui/conversation";
import {
  Message as Message3,
  MessageBody as MessageBody3,
} from "@/components/ui/message";
import { MessageParts as MessageParts2 } from "@/components/ui/message-parts";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";

export default function Example() {
  const [items, setItems] = useState5([
    {
      id: "welcome-user",
      actor: "user",
      parts: [
        {
          type: "text",
          text: "Can you check the April receipt?",
        },
      ],
    },
    {
      id: "welcome-answer",
      actor: "assistant",
      parts: [
        {
          type: "text",
          text: "I found the April receipt. Ask about its total or delivery.",
        },
      ],
    },
  ]);
  const run = useRef4(0);
  const cancelStream = useRef4(() => {});
  useEffect4(
    () => () => {
      run.current += 1;
      cancelStream.current();
    },
    [],
  );
  return (
    <div data-preview-wide>
      <Chat label="Receipt support chat">
        <ChatHeader>
          <h2>Receipt support</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation3 label="Receipt conversation">
            <ConversationContent3>
              {items.map((item) => {
                return (
                  <ConversationItem3 key={item.id} id={item.id} message={item}>
                    <Message3 actor={item.actor} status={item.status}>
                      <MessageBody3>
                        <MessageParts2 parts={item.parts} />
                      </MessageBody3>
                    </Message3>
                  </ConversationItem3>
                );
              })}
            </ConversationContent3>
          </Conversation3>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            defaultValue="Keep the receipt context in the answer."
            onSubmit={(submission, context) => {
              cancelStream.current();
              const currentRun = ++run.current;
              const assistantId = `assistant-${currentRun}`;
              setItems((current) => [
                ...current.map((item) =>
                  item.status === "streaming"
                    ? {
                        ...item,
                        status: "stopped",
                      }
                    : item,
                ),
                userMessage(`user-${current.length}`, submission),
                {
                  id: assistantId,
                  actor: "assistant",
                  status: "streaming",
                  parts: [
                    {
                      type: "text",
                      text: "",
                    },
                  ],
                },
              ]);
              cancelStream.current = streamWords(
                localReply(submission, context),
                (text, done) => {
                  if (currentRun !== run.current) return;
                  setItems((current) =>
                    current.map((item) =>
                      item.id === assistantId
                        ? {
                            ...item,
                            status: done ? "complete" : "streaming",
                            parts: [
                              {
                                type: "text",
                                text,
                              },
                            ],
                          }
                        : item,
                    ),
                  );
                },
              );
            }}
          />
        </ChatFooter>
      </Chat>
    </div>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function localReply(submission, context) {
  const model =
    MODEL_OPTIONS.find(({ value }) => value === context.model)?.label ??
    context.model;
  const subject = submission.text.toLowerCase().includes("receipt")
    ? "the receipt"
    : "this receipt task";
  return `I\u2019ll use ${model} to help with ${subject}. The receipt details are ready.`;
}

function userMessage(id, submission) {
  const files = submission.attachments.map((file) => ({
    type: "file",
    ...file,
  }));
  return {
    id,
    actor: "user",
    parts: [
      ...files,
      {
        type: "text",
        text: submission.text,
      },
    ],
  };
}

function streamWords(text, onText) {
  const words = text.match(/\S+\s*/g) ?? [];
  let index = 0;
  let timer = 0;
  const next = () => {
    index = Math.min(words.length, index + 2);
    onText(words.slice(0, index).join(""), index === words.length);
    if (index < words.length) timer = window.setTimeout(next, 55);
  };
  next();
  return () => window.clearTimeout(timer);
}

```

chat-human-support-chat-2.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

/* apps/web/src/demos/component-thumbnails.css */

```

### Assistant stream and stop

Grow a deterministic local answer and stop it while it is streaming without losing the transcript.

chat-assistant-stream-and-stop-3.jsx

```jsx
import {
  useEffect as useEffect4,
  useRef as useRef4,
  useState as useState5,
} from "react";
import {
  Chat,
  ChatContent,
  ChatFooter,
  ChatHeader,
} from "@/components/ui/chat";
import {
  Conversation as Conversation3,
  ConversationContent as ConversationContent3,
  ConversationItem as ConversationItem3,
} from "@/components/ui/conversation";
import {
  Message as Message3,
  MessageBody as MessageBody3,
  MessageFooter as MessageFooter2,
} from "@/components/ui/message";
import { MessageParts as MessageParts2 } from "@/components/ui/message-parts";
import { Shimmer } from "@/components/ui/shimmer";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";

export default function Example() {
  const [state, setState] = useState5("ready");
  const [items, setItems] = useState5([
    {
      id: "stream-user",
      actor: "user",
      parts: [
        {
          type: "text",
          text: "Can you check the April receipt?",
        },
      ],
    },
    {
      id: "stream-answer",
      actor: "assistant",
      parts: [
        {
          type: "text",
          text: "I found it. Ask about its total or delivery.",
        },
      ],
    },
  ]);
  const timer = useRef4(undefined);
  const run = useRef4(0);
  const words =
    "I checked the April receipt. The total is $48.20. It was paid by card and is ready to share.".match(
      /\S+\s*/g,
    ) ?? [];
  useEffect4(
    () => () => {
      run.current += 1;
      if (timer.current) window.clearTimeout(timer.current);
    },
    [],
  );
  const start = (submission) => {
    run.current += 1;
    const currentRun = run.current;
    const responseId = `stream-answer-${currentRun}`;
    let index = 0;
    setState("streaming");
    setItems((current) => [
      ...current,
      userMessage(`stream-user-${currentRun}`, submission),
      {
        id: responseId,
        actor: "assistant",
        status: "streaming",
        parts: [
          {
            type: "text",
            text: "",
          },
        ],
      },
    ]);
    const next = () => {
      if (currentRun !== run.current) return;
      index = Math.min(words.length, index + 2);
      const text = words.slice(0, index).join("");
      setItems((current) =>
        current.map((item) =>
          item.id === responseId
            ? {
                ...item,
                status: index === words.length ? "complete" : "streaming",
                parts: [
                  {
                    type: "text",
                    text,
                  },
                ],
              }
            : item,
        ),
      );
      if (index < words.length) timer.current = window.setTimeout(next, 55);
      else setState("ready");
    };
    timer.current = window.setTimeout(next, 55);
  };
  const stop = () => {
    if (state !== "streaming") return;
    const responseId = `stream-answer-${run.current}`;
    run.current += 1;
    if (timer.current) window.clearTimeout(timer.current);
    setState("stopped");
    setItems((current) =>
      current.map((item) =>
        item.id === responseId
          ? {
              ...item,
              status: "stopped",
            }
          : item,
      ),
    );
  };
  return (
    <div data-preview-wide>
      <Chat label="Receipt support chat">
        <ChatHeader>
          <h2>Receipt support</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation3 label="Receipt conversation">
            <ConversationContent3>
              {items.map((item) => {
                const waiting =
                  item.actor === "assistant" &&
                  item.status === "streaming" &&
                  !item.parts.some(
                    (part) =>
                      part.type !== "source" &&
                      (part.type !== "text" || part.text.trim()),
                  );
                return (
                  <ConversationItem3 key={item.id} id={item.id} message={item}>
                    <Message3 actor={item.actor} status={item.status}>
                      <MessageBody3>
                        {waiting ? (
                          <Shimmer>Checking the receipt</Shimmer>
                        ) : (
                          <MessageParts2 parts={item.parts} />
                        )}
                        {item.actor === "assistant" &&
                        item.status === "streaming" ? (
                          <span
                            className="ui-sr-only"
                            role="status"
                            aria-live="polite"
                          >
                            Assistant response is in progress.
                          </span>
                        ) : null}
                      </MessageBody3>
                      {item.status === "stopped" ? (
                        <MessageFooter2>
                          <span role="status">Generation stopped.</span>
                        </MessageFooter2>
                      ) : null}
                    </Message3>
                  </ConversationItem3>
                );
              })}
            </ConversationContent3>
          </Conversation3>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            defaultValue="What is the receipt total?"
            feedbackPlacement="conversation"
            status={state === "streaming" ? "streaming" : "ready"}
            onStop={stop}
            onSubmit={start}
          />
        </ChatFooter>
      </Chat>
    </div>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function userMessage(id, submission) {
  const files = submission.attachments.map((file) => ({
    type: "file",
    ...file,
  }));
  return {
    id,
    actor: "user",
    parts: [
      ...files,
      {
        type: "text",
        text: submission.text,
      },
    ],
  };
}

```

chat-assistant-stream-and-stop-3.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

/* apps/web/src/demos/component-thumbnails.css */

```

### Read-only transcript

Show a completed transcript without a composer or dead input action.

chat-read-only-transcript-4.jsx

```jsx
import { Chat, ChatContent, ChatHeader } from "@/components/ui/chat";
import {
  Conversation as Conversation3,
  ConversationContent as ConversationContent3,
  ConversationItem as ConversationItem3,
} from "@/components/ui/conversation";
import {
  Message as Message3,
  MessageBody as MessageBody3,
} from "@/components/ui/message";
import { MessageParts as MessageParts2 } from "@/components/ui/message-parts";

export default function Example() {
  const items = [
    {
      id: "readonly-user",
      actor: "user",
      parts: [
        {
          type: "text",
          text: "Show the receipt details.",
        },
      ],
    },
    {
      id: "readonly-answer",
      actor: "assistant",
      parts: [
        {
          type: "text",
          text: "Order R-1048 \xB7 $48.20 \xB7 paid by card.",
        },
      ],
    },
  ];
  return (
    <div data-preview-wide>
      <Chat label="Receipt support chat">
        <ChatHeader>
          <h2>Receipt support</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation3 label="Receipt conversation">
            <ConversationContent3>
              {items.map((item) => {
                return (
                  <ConversationItem3 key={item.id} id={item.id} message={item}>
                    <Message3 actor={item.actor} status={item.status}>
                      <MessageBody3>
                        <MessageParts2 parts={item.parts} />
                      </MessageBody3>
                    </Message3>
                  </ConversationItem3>
                );
              })}
            </ConversationContent3>
          </Conversation3>
        </ChatContent>
      </Chat>
    </div>
  );
}

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

```

### Rich response

Compose one helpful answer with a citation, a useful file, and a caller-owned artifact.

chat-rich-response-5.jsx

```jsx
import { Chat, ChatContent, ChatHeader } from "@/components/ui/chat";
import {
  Conversation as Conversation3,
  ConversationContent as ConversationContent3,
  ConversationItem as ConversationItem3,
} from "@/components/ui/conversation";
import {
  Message as Message3,
  MessageBody as MessageBody3,
} from "@/components/ui/message";
import { MessageParts as MessageParts2 } from "@/components/ui/message-parts";
import { Table } from "@/components/ui/table";
import { useSyncExternalStore } from "react";

export default function Example() {
  const receiptUrl = useDemoSourceUrl("receipt-policy.html");
  const parts = [
    {
      type: "text",
      text: "The receipt is ready. The policy explains the delivery window.",
    },
    ...(receiptUrl
      ? [
          {
            type: "source",
            id: "receipt-policy",
            source: {
              id: "receipt-policy",
              type: "url",
              title: "Receipt policy",
              url: receiptUrl,
            },
          },
          {
            type: "citation-anchor",
            id: "receipt-anchor",
            sourceIds: ["receipt-policy"],
          },
        ]
      : []),
    {
      type: "file",
      id: "receipt-file",
      name: "receipt.pdf",
      mediaType: "application/pdf",
      size: 24576,
      status: "ready",
    },
    {
      type: "data",
      id: "receipt-artifact",
      name: "Receipt details",
      data: {
        order: "R-1048",
        total: "$48.20",
      },
    },
  ];
  return (
    <div data-preview-wide>
      <Chat label="Receipt support chat">
        <ChatHeader>
          <h2>Receipt details</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation3 label="Receipt conversation">
            <ConversationContent3>
              {[
                {
                  id: "rich-response",
                  actor: "assistant",
                  parts,
                },
              ].map((item) => {
                return (
                  <ConversationItem3 key={item.id} id={item.id} message={item}>
                    <Message3 actor={item.actor}>
                      <MessageBody3>
                        <MessageParts2
                          parts={item.parts}
                          renderers={{
                            data: artifactRenderer,
                          }}
                        />
                      </MessageBody3>
                    </Message3>
                  </ConversationItem3>
                );
              })}
            </ConversationContent3>
          </Conversation3>
        </ChatContent>
      </Chat>
    </div>
  );
}

var subscribe = () => () => {};

var serverOrigin = () => "";

var browserOrigin = () => window.location.origin;

function useDemoSourceUrl(filename) {
  return useDemoAssetUrl(`/examples/${filename}`);
}

function useDemoAssetUrl(path) {
  const origin = useSyncExternalStore(subscribe, browserOrigin, serverOrigin);
  return origin ? new URL(path, origin).href : undefined;
}

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function primitiveText(value) {
  if (typeof value === "string") return value.trim() ? value : null;
  if (typeof value === "number")
    return Number.isFinite(value) ? String(value) : null;
  if (typeof value === "boolean" || typeof value === "bigint")
    return String(value);
  return null;
}

function fieldLabel(key) {
  const label = key.replace(/[-_]+/g, " ").trim();
  return label
    ? label.replace(/\b\w/g, (character) => character.toUpperCase())
    : "Field";
}

function artifactRenderer(part) {
  if (part.type !== "data") return null;
  const title =
    typeof part.name === "string" && part.name.trim()
      ? part.name
      : "Receipt details";
  const rows = isRecord(part.data)
    ? Object.entries(part.data).flatMap(([key, value]) => {
        const text = primitiveText(value);
        return text === null
          ? []
          : [
              {
                key,
                text,
              },
            ];
      })
    : [];
  return (
    <Table layout="wrap" aria-label={title}>
      <Table.Header>
        <Table.Row>
          <Table.Head scope="col">Detail</Table.Head>
          <Table.Head scope="col">Value</Table.Head>
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {rows.length ? (
          rows.map(({ key, text }) => (
            <Table.Row key={key}>
              <Table.Head scope="row">{fieldLabel(key)}</Table.Head>
              <Table.Cell>{text}</Table.Cell>
            </Table.Row>
          ))
        ) : (
          <Table.EmptyRow colSpan={2}>
            Receipt details are unavailable.
          </Table.EmptyRow>
        )}
      </Table.Body>
    </Table>
  );
}

```

### Advisory questionnaire

Keep the questionnaire in its own conversation card while the message composer stays available. Send a message and confirm it does not answer or clear the questionnaire.

chat-advisory-questionnaire-6.jsx

```jsx
import {
  useEffect as useEffect2,
  useRef as useRef2,
  useState as useState3,
} from "react";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import { Message, MessageBody } from "@/components/ui/message";
import {
  Questionnaire,
  QuestionnaireRecord,
} from "@/components/ui/questionnaire";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";

export default function Example() {
  return <QuestionnaireChatDemo mode="advisory" />;
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

var designQuestions = [
  {
    id: "design-today",
    title: "How's your product's design today?",
    kind: "single",
    required: true,
    custom: {
      placeholder: "Type your answer\u2026",
      maxLength: 120,
    },
    options: [
      {
        value: "consistent",
        label: "Solid, we keep it consistent",
      },
      {
        value: "slipping",
        label: "Slipping as we ship",
      },
      {
        value: "patchwork",
        label: "A patchwork by now",
      },
      {
        value: "ai-built",
        label: "AI-built, needs a human eye",
      },
      {
        value: "early",
        label: "Barely any design yet",
      },
    ],
  },
  {
    id: "design-cost",
    title: "What's costing you most?",
    kind: "single",
    required: true,
    options: [
      {
        value: "slower-shipping",
        label: "Shipping takes too long",
      },
      {
        value: "feature-regressions",
        label: "Every new feature makes it worse",
      },
      {
        value: "inconsistent",
        label: "The product feels inconsistent",
      },
      {
        value: "team-alignment",
        label: "The team cannot align on decisions",
      },
    ],
  },
  {
    id: "design-needed",
    title: "What do you need?",
    kind: "multiple",
    required: true,
    minSelections: 1,
    options: [
      {
        value: "design-system",
        label: "Design system",
      },
      {
        value: "mvp",
        label: "MVP",
      },
      {
        value: "feature",
        label: "A key feature",
      },
      {
        value: "ui-refresh",
        label: "UI refresh",
      },
      {
        value: "ux-audit",
        label: "UX audit",
      },
      {
        value: "not-sure",
        label: "Not sure yet",
      },
    ],
  },
];

function message(id, actor, text) {
  return {
    id,
    actor,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

function QuestionnaireChatDemo({
  mode = "required",
  controlledAck = false,
  failFirst = false,
} = {}) {
  const [active, setActive] = useState3(true);
  const [requestId, setRequestId] = useState3(1);
  const [response, setResponse] = useState3();
  const [draft, setDraft] = useState3(
    "Start with a UX audit and keep our current design system.",
  );
  const [messages, setMessages] = useState3([
    message(
      "design-request",
      "assistant",
      "I can tailor the product design. The questions are optional; send a message whenever you\u2019re ready.",
    ),
  ]);
  const [attempts, setAttempts] = useState3(0);
  const [ackStatus, setAckStatus] = useState3("editing");
  const composerFormRef = useRef2(null);
  const dockRef = useRef2(null);
  const shouldRestoreFocus = useRef2(false);
  const submissionLock = useRef2(false);
  const mounted = useRef2(true);
  const requestIdentity = useRef2(1);
  const messageIdentity = useRef2(0);
  const replyIdentity = useRef2(0);
  const replyTimer = useRef2(undefined);
  useEffect2(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      requestIdentity.current += 1;
      replyIdentity.current += 1;
      submissionLock.current = false;
      if (replyTimer.current !== undefined)
        window.clearTimeout(replyTimer.current);
    };
  }, []);
  useEffect2(() => {
    if (active || true) return;
    shouldRestoreFocus.current = false;
    composerFormRef.current?.querySelector("textarea")?.focus();
  }, [active, false]);
  useEffect2(() => {
    return;
    const request = requestIdentity.current;
    setMessages((current) =>
      current.some((item) => item.id === `answer-${request}`)
        ? current
        : [
            ...current,
            {
              id: `answer-${request}`,
              actor: "user",
              parts: [
                {
                  type: "text",
                  text: "Here are my design choices.",
                },
                {
                  type: "data",
                  id: `design-record-${request}`,
                  name: "QuestionnaireRecord",
                  data: response,
                },
              ],
            },
          ],
    );
    setActive(false);
  }, [ackStatus, active, false, false, response]);
  const captureDockFocus = () => {
    shouldRestoreFocus.current = Boolean(
      dockRef.current?.contains(document.activeElement),
    );
  };
  const accept = async (next) => {
    if (submissionLock.current) return;
    submissionLock.current = true;
    const request = requestIdentity.current;
    setAttempts((value) => value + 1);
    await Promise.resolve();
    if (!mounted.current || request !== requestIdentity.current) return;
    captureDockFocus();
    setResponse(next);
    setAckStatus("submitted");
    setActive(false);
  };
  const submitMessage = (text) => {
    const clean = text.trim();
    if (!clean) return;
    const id = ++messageIdentity.current;
    const followup = active
      ? "The clarification stays open. I can use your message while it is pending."
      : ackStatus === "cancelled"
        ? "The questionnaire was cancelled. I can use your message."
        : "Thanks for sharing those optional details. I\u2019ll use them with your message.";
    if (replyTimer.current !== undefined)
      window.clearTimeout(replyTimer.current);
    const currentReply = ++replyIdentity.current;
    setMessages((current) => [
      ...current,
      message(`user-${id}`, "user", clean),
      {
        id: `assistant-${id}`,
        actor: "assistant",
        status: "streaming",
        parts: [
          {
            type: "text",
            text: "",
          },
        ],
      },
    ]);
    const words = followup.match(/\S+\s*/g) ?? [];
    let count = 0;
    const next = () => {
      if (!mounted.current || currentReply !== replyIdentity.current) return;
      count = Math.min(words.length, count + 2);
      const done = count === words.length;
      setMessages((current) =>
        current.map((item) =>
          item.id === `assistant-${id}`
            ? {
                ...item,
                status: done ? "complete" : "streaming",
                parts: [
                  {
                    type: "text",
                    text: words.slice(0, count).join(""),
                  },
                ],
              }
            : item,
        ),
      );
      if (!done) replyTimer.current = window.setTimeout(next, 55);
    };
    next();
  };
  const renderMessage = (item) => {
    const record = item.parts.find(
      (part) => part.type === "data" && part.name === "QuestionnaireRecord",
    );
    return (
      <ConversationItem key={item.id} id={item.id} message={item}>
        <Message actor={item.actor}>
          <MessageBody>
            {record ? (
              <QuestionnaireRecord
                questions={designQuestions}
                response={record.data}
                status={
                  item.id.startsWith("cancel-") ? "cancelled" : "submitted"
                }
              />
            ) : (
              item.parts.map((part) =>
                part.type === "text" ? (
                  <span key={part.id ?? part.text}>{part.text}</span>
                ) : null,
              )
            )}
          </MessageBody>
        </Message>
      </ConversationItem>
    );
  };
  const newRequest = () => {
    requestIdentity.current += 1;
    submissionLock.current = false;
    shouldRestoreFocus.current = false;
    setRequestId(requestIdentity.current);
    setResponse(undefined);
    setAckStatus("editing");
    setAttempts(0);
    setActive(true);
  };
  return (
    <div data-preview-wide>
      <Chat
        label={"Advisory design clarification"}
        inputPolicy={"allow"}
        pendingInput={false}
        inputMessage="Answer the questions to continue."
      >
        <ChatContent>
          <Conversation label="Design chat" initialPosition="end">
            <ConversationContent>
              {messages.map(renderMessage)}
              <ConversationItem
                id={`clarification-${requestId}`}
                message={message(
                  `clarification-${requestId}`,
                  "assistant",
                  "A few optional details can make this answer more useful.",
                )}
              >
                <Message actor="assistant">
                  <MessageBody>
                    {active ? (
                      <Questionnaire
                        key={`advisory-${requestId}`}
                        questions={designQuestions}
                        onSubmit={accept}
                      />
                    ) : response ? (
                      <>
                        <p>Thanks. These details will guide the answer.</p>
                        <QuestionnaireRecord
                          questions={designQuestions}
                          response={response}
                          status="submitted"
                        />
                      </>
                    ) : (
                      <QuestionnaireRecord
                        questions={designQuestions}
                        status="cancelled"
                      />
                    )}
                  </MessageBody>
                </Message>
              </ConversationItem>
            </ConversationContent>
          </Conversation>
        </ChatContent>
        <ChatFooter>
          {null}
          <div
            hidden={false}
            style={{
              width: "100%",
              minWidth: 0,
            }}
          >
            <ChatComposer
              ref={composerFormRef}
              value={draft}
              onValueChange={setDraft}
              onSubmit={(submission) => {
                submitMessage(submission.text);
              }}
            />
          </div>
          {!active ? (
            <Button type="button" variant="ghost" onClick={newRequest}>
              Ask another question
            </Button>
          ) : null}
          {!active && ackStatus === "cancelled" ? (
            <span role="status">
              Questionnaire cancelled. You can continue messaging.
            </span>
          ) : null}
        </ChatFooter>
      </Chat>
    </div>
  );
}

```

chat-advisory-questionnaire-6.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

### Required questionnaire dock

The pending questionnaire occupies the input dock. Try sending a message before answering; the request blocks it. Complete the answers and submit to restore the composer and add one response record. The Close icon inside the questionnaire dismisses this caller-permitted request and restores the saved message draft.

chat-required-questionnaire-dock-7.jsx

```jsx
import {
  useEffect as useEffect2,
  useRef as useRef2,
  useState as useState3,
} from "react";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import { Message, MessageBody } from "@/components/ui/message";
import {
  Questionnaire,
  QuestionnaireRecord,
} from "@/components/ui/questionnaire";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";

export default function Example() {
  return <QuestionnaireChatDemo mode="required" />;
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

var designQuestions = [
  {
    id: "design-today",
    title: "How's your product's design today?",
    kind: "single",
    required: true,
    custom: {
      placeholder: "Type your answer\u2026",
      maxLength: 120,
    },
    options: [
      {
        value: "consistent",
        label: "Solid, we keep it consistent",
      },
      {
        value: "slipping",
        label: "Slipping as we ship",
      },
      {
        value: "patchwork",
        label: "A patchwork by now",
      },
      {
        value: "ai-built",
        label: "AI-built, needs a human eye",
      },
      {
        value: "early",
        label: "Barely any design yet",
      },
    ],
  },
  {
    id: "design-cost",
    title: "What's costing you most?",
    kind: "single",
    required: true,
    options: [
      {
        value: "slower-shipping",
        label: "Shipping takes too long",
      },
      {
        value: "feature-regressions",
        label: "Every new feature makes it worse",
      },
      {
        value: "inconsistent",
        label: "The product feels inconsistent",
      },
      {
        value: "team-alignment",
        label: "The team cannot align on decisions",
      },
    ],
  },
  {
    id: "design-needed",
    title: "What do you need?",
    kind: "multiple",
    required: true,
    minSelections: 1,
    options: [
      {
        value: "design-system",
        label: "Design system",
      },
      {
        value: "mvp",
        label: "MVP",
      },
      {
        value: "feature",
        label: "A key feature",
      },
      {
        value: "ui-refresh",
        label: "UI refresh",
      },
      {
        value: "ux-audit",
        label: "UX audit",
      },
      {
        value: "not-sure",
        label: "Not sure yet",
      },
    ],
  },
];

function message(id, actor, text) {
  return {
    id,
    actor,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

function QuestionnaireChatDemo({
  mode = "required",
  controlledAck = false,
  failFirst = false,
} = {}) {
  const [active, setActive] = useState3(true);
  const [requestId, setRequestId] = useState3(1);
  const [response, setResponse] = useState3();
  const [draft, setDraft] = useState3(
    "Start with a UX audit and keep our current design system.",
  );
  const [messages, setMessages] = useState3([
    message(
      "design-request",
      "assistant",
      "I can tailor the product design. Answer three quick questions first.",
    ),
  ]);
  const [attempts, setAttempts] = useState3(0);
  const [ackStatus, setAckStatus] = useState3("editing");
  const composerFormRef = useRef2(null);
  const dockRef = useRef2(null);
  const shouldRestoreFocus = useRef2(false);
  const submissionLock = useRef2(false);
  const mounted = useRef2(true);
  const requestIdentity = useRef2(1);
  const messageIdentity = useRef2(0);
  const replyIdentity = useRef2(0);
  const replyTimer = useRef2(undefined);
  useEffect2(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      requestIdentity.current += 1;
      replyIdentity.current += 1;
      submissionLock.current = false;
      if (replyTimer.current !== undefined)
        window.clearTimeout(replyTimer.current);
    };
  }, []);
  useEffect2(() => {
    if (active || false || !shouldRestoreFocus.current) return;
    shouldRestoreFocus.current = false;
    composerFormRef.current?.querySelector("textarea")?.focus();
  }, [active, true]);
  useEffect2(() => {
    return;
    const request = requestIdentity.current;
    setMessages((current) =>
      current.some((item) => item.id === `answer-${request}`)
        ? current
        : [
            ...current,
            {
              id: `answer-${request}`,
              actor: "user",
              parts: [
                {
                  type: "text",
                  text: "Here are my design choices.",
                },
                {
                  type: "data",
                  id: `design-record-${request}`,
                  name: "QuestionnaireRecord",
                  data: response,
                },
              ],
            },
          ],
    );
    setActive(false);
  }, [ackStatus, active, false, true, response]);
  const captureDockFocus = () => {
    shouldRestoreFocus.current = Boolean(
      dockRef.current?.contains(document.activeElement),
    );
  };
  const accept = async (next) => {
    if (submissionLock.current) return;
    submissionLock.current = true;
    const request = requestIdentity.current;
    setAttempts((value) => value + 1);
    await Promise.resolve();
    if (!mounted.current || request !== requestIdentity.current) return;
    captureDockFocus();
    setResponse(next);
    setAckStatus("submitted");
    setActive(false);
    {
      setMessages((current) =>
        current.some((item) => item.id === `answer-${request}`)
          ? current
          : [
              ...current,
              {
                id: `answer-${request}`,
                actor: "user",
                parts: [
                  {
                    type: "text",
                    text: "Here are my design choices.",
                  },
                  {
                    type: "data",
                    id: `design-record-${request}`,
                    name: "QuestionnaireRecord",
                    data: next,
                  },
                ],
              },
            ],
      );
    }
  };
  const cancel = () => {
    captureDockFocus();
    requestIdentity.current += 1;
    submissionLock.current = false;
    setRequestId(requestIdentity.current);
    setAckStatus("cancelled");
    setActive(false);
  };
  const submitMessage = (text) => {
    const clean = text.trim();
    if (!clean) return;
    const id = ++messageIdentity.current;
    const followup = active
      ? "The clarification stays open. I can use your message while it is pending."
      : ackStatus === "cancelled"
        ? "The questionnaire was cancelled. I can use your message."
        : "Thanks for answering. I\u2019ll use those choices with your message.";
    if (replyTimer.current !== undefined)
      window.clearTimeout(replyTimer.current);
    const currentReply = ++replyIdentity.current;
    setMessages((current) => [
      ...current,
      message(`user-${id}`, "user", clean),
      {
        id: `assistant-${id}`,
        actor: "assistant",
        status: "streaming",
        parts: [
          {
            type: "text",
            text: "",
          },
        ],
      },
    ]);
    const words = followup.match(/\S+\s*/g) ?? [];
    let count = 0;
    const next = () => {
      if (!mounted.current || currentReply !== replyIdentity.current) return;
      count = Math.min(words.length, count + 2);
      const done = count === words.length;
      setMessages((current) =>
        current.map((item) =>
          item.id === `assistant-${id}`
            ? {
                ...item,
                status: done ? "complete" : "streaming",
                parts: [
                  {
                    type: "text",
                    text: words.slice(0, count).join(""),
                  },
                ],
              }
            : item,
        ),
      );
      if (!done) replyTimer.current = window.setTimeout(next, 55);
    };
    next();
  };
  const renderMessage = (item) => {
    const record = item.parts.find(
      (part) => part.type === "data" && part.name === "QuestionnaireRecord",
    );
    return (
      <ConversationItem key={item.id} id={item.id} message={item}>
        <Message actor={item.actor}>
          <MessageBody>
            {record ? (
              <QuestionnaireRecord
                questions={designQuestions}
                response={record.data}
                status={
                  item.id.startsWith("cancel-") ? "cancelled" : "submitted"
                }
              />
            ) : (
              item.parts.map((part) =>
                part.type === "text" ? (
                  <span key={part.id ?? part.text}>{part.text}</span>
                ) : null,
              )
            )}
          </MessageBody>
        </Message>
      </ConversationItem>
    );
  };
  const newRequest = () => {
    requestIdentity.current += 1;
    submissionLock.current = false;
    shouldRestoreFocus.current = false;
    setRequestId(requestIdentity.current);
    setResponse(undefined);
    setAckStatus("editing");
    setAttempts(0);
    setActive(true);
  };
  return (
    <div data-preview-wide>
      <Chat
        label={"Required design clarification"}
        inputPolicy={"block"}
        pendingInput={active}
        inputMessage="Answer the questions to continue."
      >
        <ChatContent>
          <Conversation label="Design chat" initialPosition="end">
            <ConversationContent>
              {messages.map(renderMessage)}
              {null}
            </ConversationContent>
          </Conversation>
        </ChatContent>
        <ChatFooter>
          {active ? (
            <div
              ref={dockRef}
              className="questionnaire-chat__dock"
              style={{
                display: "contents",
              }}
            >
              <Questionnaire
                key={`required-${requestId}`}
                appearance="composer"
                questions={designQuestions}
                status={undefined}
                response={undefined}
                onSubmit={accept}
                onCancel={cancel}
              />
            </div>
          ) : null}
          <div
            hidden={active}
            style={{
              width: "100%",
              minWidth: 0,
            }}
          >
            <ChatComposer
              ref={composerFormRef}
              value={draft}
              onValueChange={setDraft}
              onSubmit={(submission) => {
                submitMessage(submission.text);
              }}
            />
          </div>
          {!active ? (
            <Button type="button" variant="ghost" onClick={newRequest}>
              Ask another question
            </Button>
          ) : null}
          {!active && ackStatus === "cancelled" ? (
            <span role="status">
              Questionnaire cancelled. You can continue messaging.
            </span>
          ) : null}
        </ChatFooter>
      </Chat>
    </div>
  );
}

```

chat-required-questionnaire-dock-7.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

For recorded audio input, see the [voice-note composition](/ai-elements/composer#voice-note).

## Integrations

Vercel and TanStack AI own messages, transport, streaming and cancellation. Ghost UI owns normalized rendering and draft interaction. These offline previews use the real hooks; replace the local transport with your API connection in an application. The [shadcn AI SDK](https://ui.shadcn.com/docs/helpers/ai-sdk.md) and [TanStack](https://ui.shadcn.com/docs/helpers/tanstack-ai.md) helpers demonstrate the same boundary. These examples use the native transports supported by the versions listed above.

### Vercel AI SDK

The Vercel AI SDK hook owns messages, status, and the local streaming transport. This prepared follow-up uses the real useChat lifecycle and can be stopped while it streams.

chat-vercel-ai-sdk-8.jsx

```jsx
import { useChat as useAiSdkChat } from "@ai-sdk/react";
import { simulateReadableStream } from "ai";
import "@tanstack/ai-react";
import {
  Chat,
  ChatContent,
  ChatFooter,
  ChatHeader,
  ChatStatus,
} from "@/components/ui/chat";
import {
  Composer,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import {
  Conversation as Conversation2,
  ConversationContent as ConversationContent2,
  ConversationItem as ConversationItem2,
} from "@/components/ui/conversation";
import { Fragment } from "react";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageSender } from "@/components/ui/message-sender";
import { CitationList, CitationProvider } from "@/components/ui/citation";
import { MessageParts } from "@/components/ui/message-parts";
import { Shimmer } from "@/components/ui/shimmer";
import { useChatAdapter } from "@/lib/chat-runtime-react";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const { messages, sendMessage, regenerate, stop, status, error } =
    useAiSdkChat({
      messages: aiSdkMessages,
      transport: aiSdkTransport,
    });
  const runtime = useChatAdapter(
    aiSdkAdapter,
    {
      status,
      error,
      sendMessage,
      messages,
      regenerate,
      stop,
    },
    {
      identity: {
        threadId: "vercel-demo",
        revision: 0,
      },
    },
  );
  const { controller } = runtime;
  const normalized = runtime.messages.map((message2, index, all) =>
    status === "streaming" &&
    index === all.length - 1 &&
    message2.actor === "assistant"
      ? {
          ...message2,
          status: "streaming",
        }
      : message2,
  );
  const busy =
    controller.status === "streaming" || controller.status === "submitting";
  const lastAssistantId = [...normalized]
    .reverse()
    .find((message2) => message2.actor === "assistant")?.id;
  return (
    <div data-preview-wide>
      <Chat label="Vercel weekly product update chat">
        <ChatHeader>
          <h2>Weekly product update</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation2
            label="Weekly product update conversation"
            currentUserId="pm-rina"
            participants={chatParticipants}
            style={{
              "--conversation-height": "calc(var(--space-16) * 4)",
            }}
          >
            <ConversationContent2>
              {normalized.map((message2) => (
                <ConversationItem2
                  key={message2.id}
                  id={message2.id}
                  message={message2}
                >
                  <ActionConversationMessageView
                    item={message2}
                    pendingIndicator={<Shimmer>Preparing a response</Shimmer>}
                    actions={{
                      busy,
                      onRetry:
                        message2.id === lastAssistantId && controller.retry
                          ? () => {
                              void controller.retry?.();
                            }
                          : undefined,
                    }}
                  />
                </ConversationItem2>
              ))}
            </ConversationContent2>
          </Conversation2>
        </ChatContent>
        {error ? <ChatStatus kind="error" message={error.message} /> : null}
        <ChatFooter>
          <Composer
            label="Vercel weekly update prompt"
            defaultValue="Draft a short update with those points."
            status={controller.status}
            error={controller.error?.message}
            feedbackPlacement="conversation"
            onSubmit={async (submission) => {
              await controller.send(submission);
            }}
            onStop={() => controller.stop?.()}
          >
            <ComposerInput placeholder="Ask about the weekly update" />
            <ComposerToolbar>
              <ComposerSubmit
                aria-label={
                  controller.status === "streaming"
                    ? "Stop Vercel response"
                    : controller.status === "error"
                      ? "Retry with Vercel"
                      : "Send with Vercel"
                }
              />
            </ComposerToolbar>
          </Composer>
        </ChatFooter>
      </Chat>
    </div>
  );
}

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function ConversationMessageFrame({
  item,
  self,
  metadataAtRest,
  identity,
  editor,
  pendingIndicator,
  renderTimestamp,
  renderActions,
  renderMenu,
}) {
  const text = item.parts
    .flatMap((part) => (part.type === "text" ? [part.text] : []))
    .join("\n");
  const inlineHumanText =
    item.actor === "user" &&
    item.parts.length > 0 &&
    item.parts.every((part) => part.type === "text");
  const timestamp =
    renderTimestamp && item.createdAt ? new Date(item.createdAt) : undefined;
  const validTimestamp =
    timestamp && Number.isFinite(timestamp.getTime()) ? timestamp : undefined;
  const canRenderActions =
    item.status !== "queued" &&
    item.status !== "streaming" &&
    item.status !== "stopped";
  const footerActions =
    !editor && canRenderActions ? renderActions?.(text, validTimestamp) : null;
  const footerMetadata =
    !editor && validTimestamp && !footerActions
      ? renderTimestamp?.(validTimestamp)
      : null;
  const showFooter =
    !editor && (item.status === "stopped" || footerMetadata || footerActions);
  const waiting =
    item.actor === "assistant" &&
    item.status === "streaming" &&
    !item.parts.some(
      (part) =>
        part.type !== "source" && (part.type !== "text" || part.text.trim()),
    );
  const hasActivity = item.parts.some((part) => part.type === "activity");
  const content = (
    <Message
      actor={item.actor}
      self={self}
      metadataAtRest={metadataAtRest}
      senderId={item.author?.id}
      status={item.status}
    >
      {identity?.avatar}
      <MessageContent>
        {!hasActivity && identity?.header}
        {editor ?? (
          <MessageBody>
            {waiting && pendingIndicator ? (
              pendingIndicator
            ) : inlineHumanText ? (
              item.parts.map((part, index) =>
                part.type === "text" ? (
                  <Fragment key={part.id ?? `text-${index}`}>
                    {part.text}
                  </Fragment>
                ) : null,
              )
            ) : (
              <MessageParts
                parts={item.parts}
                sourceList={false}
                activityLabel={identity?.activityLabel}
              />
            )}
            {item.status === "streaming" ? (
              <span className="ui-sr-only" role="status" aria-live="polite">
                Assistant response is in progress.
              </span>
            ) : null}
            {item.status === "queued" ? (
              <span className="ui-sr-only" role="status" aria-live="polite">
                Message is being sent.
              </span>
            ) : null}
          </MessageBody>
        )}
        {showFooter ? (
          <ConversationMessageFooter
            status={
              item.status === "stopped" ? (
                <span role="status">Generation stopped.</span>
              ) : null
            }
            metadata={footerMetadata}
            actions={footerActions}
          />
        ) : null}
      </MessageContent>
    </Message>
  );
  return renderMenu && !editor ? renderMenu(text, content) : content;
}

function ConversationMessageFooter({ status, metadata, actions }) {
  return (
    <MessageFooter>
      {metadata}
      {status}
      {actions}
    </MessageFooter>
  );
}

function messageIdentity(item, renderActivityLabel) {
  if (!item.author) return;
  const { name, id, avatarUrl } = item.author;
  const kind =
    item.author.kind ?? (item.actor === "assistant" ? "agent" : "human");
  const label = name ?? (kind === "agent" ? "Agent" : "Unknown speaker");
  return {
    kind,
    avatar: (
      <MessageAvatar>
        <MessageSender
          name={name}
          kind={kind}
          seed={id ?? name ?? "unknown"}
          avatarUrl={avatarUrl}
          showName={false}
        />
      </MessageAvatar>
    ),
    header: <MessageHeader>{label}</MessageHeader>,
    activityLabel: item.parts.some((part) => part.type === "activity")
      ? renderActivityLabel?.(label)
      : undefined,
  };
}

function ActionConversationMessageFrame({ actions, sources, ...props }) {
  return (
    <ConversationMessageFrame
      {...props}
      renderActions={
        actions || sources
          ? (text, timestamp) => (
              <MessageActions
                text={text}
                {...actions}
                timestamp={timestamp}
                metadataPlacement={actions?.metadataPlacement ?? "inline"}
                sources={sources}
              />
            )
          : undefined
      }
      renderMenu={
        actions
          ? (text, content) => (
              <MessageActionMenu text={text} {...actions}>
                {content}
              </MessageActionMenu>
            )
          : undefined
      }
    />
  );
}

function ActionConversationMessageView({
  item,
  renderActivityLabel,
  ...props
}) {
  const sources = item.parts.flatMap((part) =>
    part.type === "source" ? [part.source] : [],
  );
  return (
    <ActionConversationMessageFrame
      {...props}
      item={item}
      identity={messageIdentity(item, renderActivityLabel)}
      sources={
        sources.length ? (
          <CitationProvider sources={sources} mode="provided">
            <CitationList mode="provided" />
          </CitationProvider>
        ) : undefined
      }
    />
  );
}

var initialExchange = [
  {
    id: "update-request",
    role: "user",
    text: "What should I include in this week's product update?",
  },
  {
    id: "update-summary",
    role: "assistant",
    text: "Lead with the shipped search improvements, then call out the one open rollout risk.",
  },
];

var authors = {
  "update-request": {
    id: "pm-rina",
    name: "Rina",
    kind: "human",
  },
  "update-summary": {
    id: "agent-summary",
    name: "Summary agent",
    kind: "agent",
    provider: {
      id: "local",
      name: "Local demo",
    },
  },
};

var metadataFor = (id) => ({
  author: authors[id],
  ...(id === "update-summary"
    ? {
        sources: [
          {
            id: "rollout-checklist",
            type: "document",
            title: "Rollout checklist",
            document: {
              name: "rollout-checklist.md",
              page: 2,
            },
          },
        ],
      }
    : {}),
});

var aiSdkMessages = initialExchange.map(({ text, ...message2 }) => ({
  ...message2,
  metadata: metadataFor(message2.id),
  parts: [
    {
      type: "text",
      text,
    },
  ],
}));

var tanStackMessages = initialExchange.map(({ text, ...message2 }) => ({
  ...message2,
  metadata: metadataFor(message2.id),
  parts: [
    {
      type: "text",
      content: text,
    },
  ],
}));

var deltas =
  "This week, we shipped faster search across the project list. The remaining risk is the staged rollout: we are checking error rates before expanding access.".match(
    /\S+\s*/g,
  ) ?? [];

var chatParticipants = [
  {
    id: "pm-rina",
    name: "Rina",
    kind: "human",
  },
  {
    id: "agent-summary",
    name: "Summary agent",
    kind: "agent",
  },
];

var aiSdkTransport = {
  async sendMessages() {
    const messageId = crypto.randomUUID();
    const chunks = [
      {
        type: "start",
        messageId,
      },
      {
        type: "text-start",
        id: messageId,
      },
      ...deltas.map((delta) => ({
        type: "text-delta",
        id: messageId,
        delta,
      })),
      {
        type: "text-end",
        id: messageId,
      },
      {
        type: "finish",
        finishReason: "stop",
      },
    ];
    return simulateReadableStream({
      chunks,
      chunkDelayInMs: 70,
    });
  },
  async reconnectToStream() {
    return null;
  },
};

var mapAuthor = (message2) => {
  const metadata = message2.metadata;
  const candidate =
    metadata && typeof metadata === "object" ? metadata.author : undefined;
  if (!candidate || typeof candidate !== "object") return undefined;
  const author = candidate;
  const provider =
    author.provider && typeof author.provider === "object"
      ? author.provider
      : undefined;
  const kind =
    author.kind === "human" || author.kind === "agent"
      ? author.kind
      : undefined;
  return {
    ...(typeof author.id === "string"
      ? {
          id: author.id,
        }
      : {}),
    ...(typeof author.name === "string"
      ? {
          name: author.name,
        }
      : {}),
    ...(kind
      ? {
          kind,
        }
      : {}),
    ...(provider
      ? {
          provider: {
            ...(typeof provider.id === "string"
              ? {
                  id: provider.id,
                }
              : {}),
            ...(typeof provider.name === "string"
              ? {
                  name: provider.name,
                }
              : {}),
          },
        }
      : {}),
  };
};

var aiSdkAdapter = createAiSdkAdapter({
  mapAuthor,
});

var tanStackAdapter = createTanStackAdapter({
  mapAuthor,
});

```

These SDK examples do not enable edit-and-regenerate: the native edit commands may replace a history prefix. A host can add MessageEdit only when it supplies a targeted transaction that preserves unrelated messages and replaces the explicitly linked reply. Native retry remains a separate SDK operation. Attachments remain caller-converted.

For approval and clarification actions, bind the SDK command with the exact tool or request identity from the normalized part. bindApproval needs the provider approval ID. bindClarification needs the request ID and revision plus its tool name and tool-call ID. A fulfilled command does not resolve a request by itself; the application must acknowledge it in its message state.

### TanStack AI

TanStack AI uses its own useChat hook and connection adapter. The same prepared weekly update streams through the TanStack connection and the hook's native stop command. Its legacy native edit path replaces the selected user message with the setMessages history prefix, then sends the replacement text; it is not a history-preserving edit-and-regenerate transaction. The current hook's reload retries only the latest assistant response; it does not expose arbitrary message retry.

chat-tanstack-ai-9.jsx

```jsx
import { EventType } from "@tanstack/ai";
import { useChat as useTanStackChat } from "@tanstack/ai-react";
import {
  Chat,
  ChatContent,
  ChatFooter,
  ChatHeader,
  ChatStatus,
} from "@/components/ui/chat";
import {
  Composer,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import {
  Conversation as Conversation2,
  ConversationContent as ConversationContent2,
  ConversationItem as ConversationItem2,
} from "@/components/ui/conversation";
import { Fragment } from "react";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageSender } from "@/components/ui/message-sender";
import { CitationList, CitationProvider } from "@/components/ui/citation";
import { MessageParts } from "@/components/ui/message-parts";
import { Shimmer } from "@/components/ui/shimmer";
import { useChatAdapter } from "@/lib/chat-runtime-react";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const { messages, setMessages, sendMessage, reload, stop, status, error } =
    useTanStackChat({
      threadId: "tanstack-demo",
      initialMessages: tanStackMessages,
      connection: tanStackConnection,
    });
  const runtime = useChatAdapter(
    tanStackAdapter,
    {
      status,
      error,
      sendMessage,
      messages,
      setMessages,
      stop,
      reload,
    },
    {
      identity: {
        threadId: "tanstack-demo",
        revision: 0,
      },
    },
  );
  const { controller } = runtime;
  const normalized = runtime.messages.map((message2, index, all) =>
    status === "streaming" &&
    index === all.length - 1 &&
    message2.actor === "assistant"
      ? {
          ...message2,
          status: "streaming",
        }
      : message2,
  );
  const busy =
    controller.status === "streaming" || controller.status === "submitting";
  const lastAssistantId = [...normalized]
    .reverse()
    .find((message2) => message2.actor === "assistant")?.id;
  return (
    <div data-preview-wide>
      <Chat label="TanStack weekly product update chat">
        <ChatHeader>
          <h2>Weekly product update</h2>
        </ChatHeader>
        <ChatContent>
          <Conversation2
            label="Weekly product update conversation"
            currentUserId="pm-rina"
            participants={chatParticipants}
            style={{
              "--conversation-height": "calc(var(--space-16) * 4)",
            }}
          >
            <ConversationContent2>
              {normalized.map((message2) => (
                <ConversationItem2
                  key={message2.id}
                  id={message2.id}
                  message={message2}
                >
                  <ActionConversationMessageView
                    item={message2}
                    renderTimestamp={messageTimestamp}
                    pendingIndicator={<Shimmer>Preparing a response</Shimmer>}
                    actions={{
                      busy,
                      onRetry:
                        message2.id === lastAssistantId && controller.retry
                          ? () => {
                              void controller.retry?.();
                            }
                          : undefined,
                    }}
                  />
                </ConversationItem2>
              ))}
            </ConversationContent2>
          </Conversation2>
        </ChatContent>
        {error ? <ChatStatus kind="error" message={error.message} /> : null}
        <ChatFooter>
          <Composer
            label="TanStack weekly update prompt"
            defaultValue="Draft a short update with those points."
            status={controller.status}
            error={controller.error?.message}
            feedbackPlacement="conversation"
            onSubmit={async (submission) => {
              await controller.send(submission);
            }}
            onStop={() => controller.stop?.()}
          >
            <ComposerInput placeholder="Ask about the weekly update" />
            <ComposerToolbar>
              <ComposerSubmit
                aria-label={
                  controller.status === "streaming"
                    ? "Stop TanStack response"
                    : controller.status === "error"
                      ? "Retry with TanStack"
                      : "Send with TanStack"
                }
              />
            </ComposerToolbar>
          </Composer>
        </ChatFooter>
      </Chat>
    </div>
  );
}

function message(id, actor, text, minute, author) {
  const createdAt = new Date(Date.UTC(2026, 9, 2, 9, minute, 0)).toISOString();
  return {
    id,
    actor,
    author,
    createdAt,
    parts: [
      {
        type: "text",
        text,
      },
    ],
  };
}

var BASIC_MESSAGES = [
  message(
    "basic-user",
    "user",
    "Could you send the latest receipt to my email?",
    0,
    {
      id: "rina",
      name: "Rina",
    },
  ),
  message(
    "basic-assistant",
    "assistant",
    "Yes. I found the receipt and can send it to the address on the account.",
    1,
    {
      id: "support",
      name: "Support",
    },
  ),
];

function ConversationMessageFrame({
  item,
  self,
  metadataAtRest,
  identity,
  editor,
  pendingIndicator,
  renderTimestamp,
  renderActions,
  renderMenu,
}) {
  const text = item.parts
    .flatMap((part) => (part.type === "text" ? [part.text] : []))
    .join("\n");
  const inlineHumanText =
    item.actor === "user" &&
    item.parts.length > 0 &&
    item.parts.every((part) => part.type === "text");
  const timestamp =
    renderTimestamp && item.createdAt ? new Date(item.createdAt) : undefined;
  const validTimestamp =
    timestamp && Number.isFinite(timestamp.getTime()) ? timestamp : undefined;
  const canRenderActions =
    item.status !== "queued" &&
    item.status !== "streaming" &&
    item.status !== "stopped";
  const footerActions =
    !editor && canRenderActions ? renderActions?.(text, validTimestamp) : null;
  const footerMetadata =
    !editor && validTimestamp && !footerActions
      ? renderTimestamp?.(validTimestamp)
      : null;
  const showFooter =
    !editor && (item.status === "stopped" || footerMetadata || footerActions);
  const waiting =
    item.actor === "assistant" &&
    item.status === "streaming" &&
    !item.parts.some(
      (part) =>
        part.type !== "source" && (part.type !== "text" || part.text.trim()),
    );
  const hasActivity = item.parts.some((part) => part.type === "activity");
  const content = (
    <Message
      actor={item.actor}
      self={self}
      metadataAtRest={metadataAtRest}
      senderId={item.author?.id}
      status={item.status}
    >
      {identity?.avatar}
      <MessageContent>
        {!hasActivity && identity?.header}
        {editor ?? (
          <MessageBody>
            {waiting && pendingIndicator ? (
              pendingIndicator
            ) : inlineHumanText ? (
              item.parts.map((part, index) =>
                part.type === "text" ? (
                  <Fragment key={part.id ?? `text-${index}`}>
                    {part.text}
                  </Fragment>
                ) : null,
              )
            ) : (
              <MessageParts
                parts={item.parts}
                sourceList={false}
                activityLabel={identity?.activityLabel}
              />
            )}
            {item.status === "streaming" ? (
              <span className="ui-sr-only" role="status" aria-live="polite">
                Assistant response is in progress.
              </span>
            ) : null}
            {item.status === "queued" ? (
              <span className="ui-sr-only" role="status" aria-live="polite">
                Message is being sent.
              </span>
            ) : null}
          </MessageBody>
        )}
        {showFooter ? (
          <ConversationMessageFooter
            status={
              item.status === "stopped" ? (
                <span role="status">Generation stopped.</span>
              ) : null
            }
            metadata={footerMetadata}
            actions={footerActions}
          />
        ) : null}
      </MessageContent>
    </Message>
  );
  return renderMenu && !editor ? renderMenu(text, content) : content;
}

function ConversationMessageFooter({ status, metadata, actions }) {
  return (
    <MessageFooter>
      {metadata}
      {status}
      {actions}
    </MessageFooter>
  );
}

function messageTimestamp(timestamp, inline = false) {
  return (
    <MessageMeta placement={inline ? "inline" : undefined}>
      <time dateTime={timestamp.toISOString()}>
        {timestamp.toLocaleTimeString([], {
          hour: "numeric",
          minute: "2-digit",
        })}
      </time>
    </MessageMeta>
  );
}

function messageIdentity(item, renderActivityLabel) {
  if (!item.author) return;
  const { name, id, avatarUrl } = item.author;
  const kind =
    item.author.kind ?? (item.actor === "assistant" ? "agent" : "human");
  const label = name ?? (kind === "agent" ? "Agent" : "Unknown speaker");
  return {
    kind,
    avatar: (
      <MessageAvatar>
        <MessageSender
          name={name}
          kind={kind}
          seed={id ?? name ?? "unknown"}
          avatarUrl={avatarUrl}
          showName={false}
        />
      </MessageAvatar>
    ),
    header: <MessageHeader>{label}</MessageHeader>,
    activityLabel: item.parts.some((part) => part.type === "activity")
      ? renderActivityLabel?.(label)
      : undefined,
  };
}

function ActionConversationMessageFrame({ actions, sources, ...props }) {
  return (
    <ConversationMessageFrame
      {...props}
      renderActions={
        actions || sources
          ? (text, timestamp) => (
              <MessageActions
                text={text}
                {...actions}
                timestamp={timestamp}
                metadataPlacement={actions?.metadataPlacement ?? "inline"}
                sources={sources}
              />
            )
          : undefined
      }
      renderMenu={
        actions
          ? (text, content) => (
              <MessageActionMenu text={text} {...actions}>
                {content}
              </MessageActionMenu>
            )
          : undefined
      }
    />
  );
}

function ActionConversationMessageView({
  item,
  renderActivityLabel,
  ...props
}) {
  const sources = item.parts.flatMap((part) =>
    part.type === "source" ? [part.source] : [],
  );
  return (
    <ActionConversationMessageFrame
      {...props}
      item={item}
      identity={messageIdentity(item, renderActivityLabel)}
      sources={
        sources.length ? (
          <CitationProvider sources={sources} mode="provided">
            <CitationList mode="provided" />
          </CitationProvider>
        ) : undefined
      }
    />
  );
}

var initialExchange = [
  {
    id: "update-request",
    role: "user",
    text: "What should I include in this week's product update?",
  },
  {
    id: "update-summary",
    role: "assistant",
    text: "Lead with the shipped search improvements, then call out the one open rollout risk.",
  },
];

var authors = {
  "update-request": {
    id: "pm-rina",
    name: "Rina",
    kind: "human",
  },
  "update-summary": {
    id: "agent-summary",
    name: "Summary agent",
    kind: "agent",
    provider: {
      id: "local",
      name: "Local demo",
    },
  },
};

var metadataFor = (id) => ({
  author: authors[id],
  ...(id === "update-summary"
    ? {
        sources: [
          {
            id: "rollout-checklist",
            type: "document",
            title: "Rollout checklist",
            document: {
              name: "rollout-checklist.md",
              page: 2,
            },
          },
        ],
      }
    : {}),
});

var aiSdkMessages = initialExchange.map(({ text, ...message2 }) => ({
  ...message2,
  metadata: metadataFor(message2.id),
  parts: [
    {
      type: "text",
      text,
    },
  ],
}));

var tanStackMessages = initialExchange.map(({ text, ...message2 }) => ({
  ...message2,
  metadata: metadataFor(message2.id),
  parts: [
    {
      type: "text",
      content: text,
    },
  ],
}));

var deltas =
  "This week, we shipped faster search across the project list. The remaining risk is the staged rollout: we are checking error rates before expanding access.".match(
    /\S+\s*/g,
  ) ?? [];

var chatParticipants = [
  {
    id: "pm-rina",
    name: "Rina",
    kind: "human",
  },
  {
    id: "agent-summary",
    name: "Summary agent",
    kind: "agent",
  },
];

var tanStackConnection = {
  async *connect(_messages, _data, signal, context) {
    const messageId = crypto.randomUUID();
    const threadId = context?.threadId ?? "weekly-update";
    const runId = context?.runId ?? crypto.randomUUID();
    yield {
      type: EventType.RUN_STARTED,
      threadId,
      runId,
    };
    yield {
      type: EventType.TEXT_MESSAGE_START,
      messageId,
      role: "assistant",
    };
    for (const delta of deltas) {
      await new Promise((resolve) => setTimeout(resolve, 70));
      if (signal?.aborted) return;
      yield {
        type: EventType.TEXT_MESSAGE_CONTENT,
        messageId,
        delta,
      };
    }
    yield {
      type: EventType.TEXT_MESSAGE_END,
      messageId,
    };
    yield {
      type: EventType.RUN_FINISHED,
      threadId,
      runId,
    };
  },
};

var mapAuthor = (message2) => {
  const metadata = message2.metadata;
  const candidate =
    metadata && typeof metadata === "object" ? metadata.author : undefined;
  if (!candidate || typeof candidate !== "object") return undefined;
  const author = candidate;
  const provider =
    author.provider && typeof author.provider === "object"
      ? author.provider
      : undefined;
  const kind =
    author.kind === "human" || author.kind === "agent"
      ? author.kind
      : undefined;
  return {
    ...(typeof author.id === "string"
      ? {
          id: author.id,
        }
      : {}),
    ...(typeof author.name === "string"
      ? {
          name: author.name,
        }
      : {}),
    ...(kind
      ? {
          kind,
        }
      : {}),
    ...(provider
      ? {
          provider: {
            ...(typeof provider.id === "string"
              ? {
                  id: provider.id,
                }
              : {}),
            ...(typeof provider.name === "string"
              ? {
                  name: provider.name,
                }
              : {}),
          },
        }
      : {}),
  };
};

var aiSdkAdapter = createAiSdkAdapter({
  mapAuthor,
});

var tanStackAdapter = createTanStackAdapter({
  mapAuthor,
});

```

## API reference

Chat properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| label | string | "Chat" | Names the conversation region. |
| inputPolicy | "allow" \| "block" | "allow" | Provides caller context for whether a pending request blocks input. |
| pendingInput | boolean | false | Marks an application-owned request as pending without interpreting composer text. |
| inputMessage | string | "Answer the questions above to continue." | Context text exposed to composed input controls when the policy blocks input. |

ChatStatus properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| kind | "error" \| "connection" \| "info" | "info" | Names the caller-owned status kind. |
| message | ReactNode | — | Provides the real error, connection, or informational status. |
| onRetry | () => void | — | Adds a caller-owned retry action when recovery is available. |

Chat, ChatHeader, ChatContent, ChatFooter, and ChatStatus forward native attributes to their section, header, div, footer, and div elements. Their refs are typed HTMLElement, HTMLElement, HTMLDivElement, HTMLElement, and HTMLDivElement, respectively. The frame parts accept children. ChatStatus.retryLabel defaults to "Retry"; its children take precedence over message. It renders nothing when both content and onRetry are absent. ChatStatus sets alert/assertive semantics for kind="error" and status/polite semantics otherwise.

ChatMessage.actor remains the runtime role (user, assistant, or system). Optional author carries caller-mapped participant identity; optional delivery carries caller-supplied receipt state. ChatController.editAndResubmit({ messageId, text }) exposes the adapter's native edit semantics and can replace later history; it does not promise to preserve unrelated messages. For that guarantee, the host must provide a separate targeted transaction before enabling MessageEdit. TanStack AI retry targets only the latest assistant response; Vercel AI SDK also accepts a targeted message ID.

Chat is a named section. ChatContent is a flexible region that keeps focus with its caller-owned controls. ChatStatus uses a polite status announcement, or an alert for an error. The frame does not invent a live region for streaming tokens and does not move focus.
