# Composer

Draft and submit a message with optional context or attachments.

## Preview

composer-preview-1.jsx

```jsx
import { useState } from "react";
import {
  Composer,
  ComposerInput,
  ComposerToolbar,
  ComposerSubmit,
} from "@/components/ui/composer";
import { Message, MessageBody } from "@/components/ui/message";

export default function Example() {
  const [sent, setSent] = useState("");
  return (
    <div
      style={{
        display: "grid",
        gap: 12,
        width: "100%",
        maxWidth: 480,
      }}
    >
      {sent && (
        <Message actor="user">
          <MessageBody>{sent}</MessageBody>
        </Message>
      )}
      <Composer
        defaultValue="Summarize the release notes."
        description="AI can make mistakes. Check important details."
        onSubmit={({ text }) => setSent(text)}
      >
        <ComposerInput placeholder="Ask about the release" />
        <ComposerToolbar>
          <ComposerSubmit />
        </ComposerToolbar>
      </Composer>
    </div>
  );
}

var transcriptSegment = {
  id: "review-update",
  speaker: "Rina",
  start: 0,
  end: 3.2,
  text: "Keep the launch decision pending until both checks are complete.",
  words: [
    "Keep ",
    "the ",
    "launch ",
    "decision ",
    "pending ",
    "until ",
    "both ",
    "checks ",
    "are ",
    "complete.",
  ].map((text, index) => ({
    id: `word-${index}`,
    text,
    start: index * 0.32,
    end: (index + 1) * 0.32,
  })),
};

var initialEntries = [
  {
    id: "q1",
    actor: "user",
    text: "What changed in this release?",
    time: {
      dateTime: "2026-11-10T09:07:00+07:00",
      label: "Nov 10, 9:07 AM",
    },
  },
  {
    id: "a1",
    actor: "assistant",
    text: "Search now handles larger collections and keeps your position when results arrive.",
  },
  {
    id: "q2",
    actor: "user",
    text: "Does that affect existing integrations?",
    time: {
      dateTime: "2026-11-10T09:11:00+07:00",
      label: "Nov 10, 9:11 AM",
    },
  },
  {
    id: "a2",
    actor: "assistant",
    text: "The data and callback contracts stay the same. Existing integrations can adopt the improvements incrementally.",
  },
  {
    id: "q3",
    actor: "user",
    text: "What should we verify before shipping?",
    time: {
      dateTime: "2026-11-10T09:14:00+07:00",
      label: "Nov 10, 9:14 AM",
    },
  },
  {
    id: "a3",
    actor: "assistant",
    text: "Check keyboard navigation, empty results and a response arriving while someone reads earlier messages.",
  },
  {
    id: "q4",
    actor: "user",
    text: "Who owns the final review?",
    time: {
      dateTime: "2026-11-10T09:16:00+07:00",
      label: "Nov 10, 9:16 AM",
    },
  },
  {
    id: "a4",
    actor: "assistant",
    text: "Mira owns the release review. Noah will verify the installed consumer.",
  },
];

var historyEntries = [
  ...initialEntries,
  ...[
    [
      "What is the rollout plan?",
      "Start with internal accounts, then enable the release for one region before expanding.",
    ],
    [
      "How do we measure success?",
      "Watch search completion, response latency and the number of interrupted sessions.",
    ],
    [
      "What happens if error rates increase?",
      "Pause the rollout and restore the previous path while the owner investigates.",
    ],
    [
      "What should support tell customers?",
      "Existing integrations keep working. Ask for the request ID if a search fails.",
    ],
    [
      "When can we remove the old path?",
      "After every region is stable and the support team has reviewed the incident queue.",
    ],
  ].flatMap(([prompt, reply], index) => [
    {
      id: `history-q${index}`,
      actor: "user",
      text: prompt,
      time: {
        dateTime: `2026-11-10T09:${20 + index * 2}:00+07:00`,
        label: `Nov 10, 9:${20 + index * 2} AM`,
      },
    },
    {
      id: `history-a${index}`,
      actor: "assistant",
      text: reply,
    },
  ]),
];

```

## Design guidance

Use Composer when people can send a message, stop a reply, or retry. For a text field submitted with other form fields, use Textarea. Keep attachments beside the draft. Place supporting summaries or approvals in the secondary region.

Keep one action row. Put add, attach and tool actions in ComposerToolbar.Start; put voice before send in ComposerToolbar.End. Use ComposerAction for quiet icon actions and ComposerSubmit for the solid send action; both keep the canonical 32px control size. Omit voice when the product has no speech input.

Show draft errors and failed sends in the status row under the card. Use Message for a sent message that needs retry. Put ongoing limits or outages in a Banner in the secondary region. Use Marker for conversation events such as a handoff.

Keep a Field.Label visible as the persistent name. Use a placeholder for a short typing prompt, or put an info icon beside the label with a [Tooltip](/components/tooltip) for an optional explanation. Keep required instructions available as persistent content. Use description for a persistent helper such as an accuracy disclaimer. Errors use the status row and the existing invalid panel border treatment.

### Accessibility

Composer is a form. Enter submits a valid draft, Shift+Enter inserts a newline, and composing or IME key code 229 never submits. Native naming, focus, disabled, read-only, error, and status attributes pass through to the textarea. Inline failed sends retain the draft and announce the error; feedbackPlacement="conversation" leaves transport feedback to Message. The optional description helper is centered below the editor and joins the textarea's accessible description. Use it for caller-owned notices such as “AI can make mistakes. Check important details.” The structural label ComposerDescription describes this prop slot; it is not another export.

**Also known as**

Chat input, Message input, Prompt input.

## Installation

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

```text
src/components/ui/chat-model.ts
src/components/ui/composer.tsx
src/components/ui/composer.css
src/components/ui/textarea.tsx
src/components/ui/textarea.css
src/components/ui/input-group.tsx
src/components/ui/foundation.css
```

## Basic usage

```tsx
import {
  Composer,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import type { ComposerSubmission } from "@/components/ui/chat-model";

export function MessageComposer({
  onSend,
}: {
  onSend: (submission: ComposerSubmission) => void | Promise<void>;
}) {
  return (
    <Composer onSubmit={onSend}>
      <ComposerInput aria-label="Message" placeholder="Ask anything…" />
      <ComposerToolbar>
        <ComposerSubmit />
      </ComposerToolbar>
    </Composer>
  );
}
```

Your application owns transport and streaming state. See the [native SDK examples](/ai-elements/chat#sdk-integration) for wiring messages, stop, approval and file delivery.

## Structures

- Composer (required form owner)
  - ComposerInput (required editor)
  - ComposerAttachments (optional)
  - ComposerToolbar (optional action row)
    - ComposerToolbar.Start (optional left group)
    - ComposerToolbar.End (optional right group)
  - ComposerAction (optional icon action)
  - ComposerSubmit (optional)
  - ComposerStatus (automatic status row)
  - ComposerDescription (description prop, optional)

Composer always uses the basic LayerCard with a 4px inset, including when its secondary region is empty. The primary surface contains the editor, attachments and toolbar. Place ready attachments in attachmentContent; use secondary for a summary, approval or persistent alert. Set secondaryPlacement="bottom" to place that retained region below the primary surface, and use secondaryVisible={false} to hide it without discarding its draft. ComposerAction and ComposerSubmit keep their canonical sizes; do not pass a size override.

## Examples

Start with a normal draft and attachment choices, then see how MessageEdit reuses this form; sending states and caller compositions follow, with speech input as an optional extension.

### Draft and attachments

#### Composer draft

Draft a request, choose a model, optionally add a file, and send it. The local example records the submitted content.

composer-composer-draft-2.jsx

```jsx
import { useRef as useRef3, useState as useState5 } from "react";
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";
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 [messages, setMessages] = useState5([]);
  const messageId = useRef3(0);
  const acknowledge = (submission) => {
    const files = submission.attachments.map((file) => ({
      type: "file",
      ...file,
    }));
    setMessages((current) => [
      ...current,
      {
        id: `user-${messageId.current++}`,
        actor: "user",
        parts: [
          ...files,
          {
            type: "text",
            text: submission.text,
          },
        ],
      },
    ]);
  };
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      {messages.map((message) => (
        <Message3 key={message.id} actor={message.actor}>
          <MessageBody3>
            <MessageParts2 parts={message.parts} />
          </MessageBody3>
        </Message3>
      ))}
      <ChatComposer
        defaultValue=""
        onSubmit={(submission) => {
          acknowledge(submission);
        }}
      />
    </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>
  );
});

```

composer-composer-draft-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)));
}

```

#### Message edit surface

MessageEdit composes Composer for an existing message. It keeps the original text as draft context, retains supplied attachments, and uses the same submit, cancel, pending and error surface. The surrounding application decides whether submit saves only the human message or performs the linked-reply transaction described in [message actions](/ai-elements/message-actions#edit).

composer-message-edit-surface-3.jsx

```jsx
import { useEffect, useRef, useState } from "react";
import { MessageEdit } from "@/components/ui/message-actions";
import { Message, MessageBody, MessageContent } from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { FileUpload } from "@/components/ui/file-upload";
import { ComposerAction, ComposerAttachments } from "@/components/ui/composer";
import { Plus } from "lucide-react";

export default function Example() {
  const [attachments, setAttachments] = useState([originalBrief]);
  const [saved, setSaved] = useState();
  const [editing, setEditing] = useState(true);
  const files = useRef(/* @__PURE__ */ new Map());
  const urls = useRef(/* @__PURE__ */ new Map());
  const addFile = (file) => {
    const id = crypto.randomUUID();
    const url = URL.createObjectURL(file);
    files.current.set(id, file);
    urls.current.set(id, url);
    return {
      id,
      name: file.name,
      mediaType: file.type || "application/octet-stream",
      size: file.size,
      url,
      status: "ready",
    };
  };
  useEffect(
    () => () => {
      urls.current.forEach((url) => URL.revokeObjectURL(url));
      urls.current.clear();
      files.current.clear();
    },
    [],
  );
  if (saved)
    return (
      <Message actor="user">
        <MessageContent>
          <MessageBody>
            <MessageParts
              parts={[
                {
                  type: "text",
                  id: "surface-saved-text",
                  text: saved.text,
                },
                ...saved.files.map((file) => ({
                  type: "file",
                  ...file,
                })),
              ]}
            />
          </MessageBody>
        </MessageContent>
      </Message>
    );
  if (!editing)
    return (
      <Message actor="user">
        <MessageContent>
          <MessageBody>
            <MessageParts
              parts={[
                {
                  type: "text",
                  id: "surface-original-text",
                  text: "Move the review to Thursday.",
                },
                {
                  type: "file",
                  ...originalBrief,
                },
              ]}
            />
          </MessageBody>
        </MessageContent>
      </Message>
    );
  const removeAttachment = (attachment) => {
    const url = urls.current.get(attachment.id);
    if (url) URL.revokeObjectURL(url);
    urls.current.delete(attachment.id);
    files.current.delete(attachment.id);
    setAttachments((current) =>
      current.filter((item) => item.id !== attachment.id),
    );
  };
  const attachmentContent = <ComposerAttachments onRemove={removeAttachment} />;
  return (
    <FileUpload.Root
      multiple
      maxFiles={4}
      selectedCount={attachments.length}
      aria-label="Edit message attachments"
      onFilesSelect={({ accepted }) =>
        setAttachments((current) => [...current, ...accepted.map(addFile)])
      }
    >
      <FileUpload.Input />
      <MessageEdit
        defaultValue="Move the review to Friday and keep the original brief attached."
        originalText="Move the review to Thursday."
        originalAuthor="Rina"
        attachments={attachments}
        attachmentContent={attachmentContent}
        submitLabel="Save changes"
        onCancel={() => {
          attachments.forEach(removeAttachment);
          setEditing(false);
        }}
        onSubmit={(text, submission) => {
          setSaved({
            text,
            files: submission?.attachments ?? attachments,
          });
          setEditing(false);
        }}
        toolbarStart={
          <FileUpload.Trigger
            render={
              <ComposerAction
                aria-label="Add files"
                icon={<Plus size={14} aria-hidden="true" />}
              />
            }
          />
        }
      />
    </FileUpload.Root>
  );
}

var originalBrief = {
  id: "review-brief",
  name: "review-brief.pdf",
  mediaType: "application/pdf",
  size: 184320,
  status: "ready",
};

```

#### Field label

Keep the caller-owned Field.Label at the top of the primary composer panel. Field.Control connects it to the native textarea; a short typing prompt belongs in ComposerInput's placeholder, which disappears as the user types while the label remains. Use Field.Description for important persistent requirements, not optional help. Errors remain in ComposerStatus within the Composer and use its invalid panel border treatment.

composer-field-label-4.jsx

```jsx
import { useState as useState5 } from "react";
import {
  Composer as Composer2,
  ComposerInput as ComposerInput2,
  ComposerSubmit as ComposerSubmit2,
  ComposerToolbar as ComposerToolbar2,
} from "@/components/ui/composer";
import { Field } from "@/components/ui/field";

export default function Example() {
  const { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Field.Root>
        <Composer2 onSubmit={onSubmit}>
          <Field.Label>Support request</Field.Label>
          <Field.Control
            render={<ComposerInput2 placeholder="Describe what you need." />}
          />
          <ComposerToolbar2>
            <ComposerSubmit2 />
          </ComposerToolbar2>
        </Composer2>
      </Field.Root>
      <DemoNote>{message}</DemoNote>
    </div>
  );
}

function DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

#### Model and attachment composition

Arrange a caller-owned model selection and ready file beside the submit action.

composer-model-and-attachment-composition-5.jsx

```jsx
import { useState as useState5 } from "react";
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 { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatComposer
        attachmentSize="default"
        defaultAttachments={[
          {
            ...receipt,
            size: 245760,
          },
          {
            ...invoice,
            size: 32768,
          },
        ]}
        onSubmit={onSubmit}
      />
      <DemoNote>{message}</DemoNote>
    </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 DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

var receipt = {
  id: "receipt",
  name: "receipt.pdf",
  mediaType: "application/pdf",
  status: "ready",
};

var invoice = {
  id: "invoice",
  name: "invoice.csv",
  mediaType: "text/csv",
  status: "ready",
};

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

composer-model-and-attachment-composition-5.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)));
}

```

#### Attachment-only

Submit a ready file when the text draft is empty.

composer-attachment-only-6.jsx

```jsx
import { useState as useState5 } from "react";
import {
  Composer as Composer2,
  ComposerAttachments as ComposerAttachments2,
} from "@/components/ui/composer";

export default function Example() {
  const [files, setFiles] = useState5([receipt]);
  const { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        attachments={files}
        onSubmit={onSubmit}
        onSubmitted={() => setFiles([])}
        attachmentContent={
          <ComposerAttachments2
            onRemove={(file) =>
              setFiles((current) =>
                current.filter((item) => item.id !== file.id),
              )
            }
          />
        }
      />
      <DemoNote>{message}</DemoNote>
    </div>
  );
}

function DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

var receipt = {
  id: "receipt",
  name: "receipt.pdf",
  mediaType: "application/pdf",
  status: "ready",
};

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

#### Prepared request and row sizing

Start with a prepared request and file while keeping the editor at two rows and capping it at four.

composer-prepared-request-and-row-sizing-7.jsx

```jsx
import { useState as useState5 } from "react";
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 { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatComposer
        defaultValue="Summarize the April receipt and flag any delivery mismatch."
        defaultAttachments={[
          {
            ...receipt,
            id: "prepared-receipt",
            name: "april-receipt.pdf",
            size: 24576,
          },
        ]}
        initialRows={2}
        maxRows={4}
        onSubmit={onSubmit}
      />
      <DemoNote>{message}</DemoNote>
    </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 DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

var receipt = {
  id: "receipt",
  name: "receipt.pdf",
  mediaType: "application/pdf",
  status: "ready",
};

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

composer-prepared-request-and-row-sizing-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)));
}

```

#### Long draft

Keep long content inside the autosizing field with internal scrolling at the maximum height.

composer-long-draft-8.jsx

```jsx
import { useState as useState5 } from "react";
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 { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatComposer
        defaultValue="Summarize the Thursday launch review for the mobile team. Keep the three open risks at the top, list owners for staging, rollout and support, and draft a short reply I can send to Marta before 16:00. Keep it calm and direct, with no extra introduction."
        onSubmit={onSubmit}
      />
      <DemoNote>{message}</DemoNote>
    </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 DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

composer-long-draft-8.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)));
}

```

### Submission states

#### Sending

Send a request in a conversation. Its acknowledgement completes automatically, while edits to a newer draft stay in the composer.

composer-sending-9.jsx

```jsx
import {
  useEffect as useEffect2,
  useRef as useRef2,
  useState as useState3,
} from "react";
import { Button } from "@/components/ui/button";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Message, MessageBody, MessageFooter } from "@/components/ui/message";
import { MessageParts } 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 [messages, setMessages] = useState3([]);
  const [failure, setFailure] = useState3(false);
  const [generating, setGenerating] = useState3(false);
  const chat = useRef2(null);
  const restoreComposerFocus = useRef2(false);
  const mounted = useRef2(true);
  const sequence = useRef2(0);
  const attempts = useRef2(/* @__PURE__ */ new Map());
  const generationAttempt = useRef2(0);
  const generationTimers = useRef2([]);
  const timers = useRef2(/* @__PURE__ */ new Map());
  useEffect2(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      attempts.current.clear();
      for (const [timer, resolve] of timers.current) {
        clearTimeout(timer);
        resolve();
      }
      timers.current.clear();
    };
  }, []);
  useEffect2(() => {
    return;
    const attempt = ++generationAttempt.current;
    const append = (text) => {
      if (!mounted.current || generationAttempt.current !== attempt) return;
      setMessages((current) =>
        current.map((message) =>
          message.id === "response"
            ? {
                ...message,
                parts: [
                  ...message.parts,
                  {
                    type: "text",
                    text,
                  },
                ],
              }
            : message,
        ),
      );
    };
    let started = false;
    const start = () => {
      if (started || !mounted.current || generationAttempt.current !== attempt)
        return;
      started = true;
      generationTimers.current = [
        setTimeout(() => append(" The item total matches the order."), 1500),
        setTimeout(
          () => append(" The delivery date needs one more check."),
          3000,
        ),
        setTimeout(() => {
          if (!mounted.current || generationAttempt.current !== attempt) return;
          setGenerating(false);
          setMessages((current) =>
            current.map((message) =>
              message.id === "response"
                ? {
                    ...message,
                    status: "complete",
                  }
                : message,
            ),
          );
        }, 45000),
      ];
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? null
        : new IntersectionObserver((entries) => {
            if (entries.some((entry) => entry.isIntersecting)) {
              start();
              observer?.disconnect();
            }
          });
    if (observer && chat.current) observer.observe(chat.current);
    else start();
  }, ["sending"]);
  useEffect2(() => {
    if (!failure && restoreComposerFocus.current) {
      restoreComposerFocus.current = false;
      if (document.activeElement === document.body)
        chat.current?.querySelector("textarea")?.focus();
    }
  }, [failure]);
  const wait = () =>
    new Promise((resolve) => {
      const timer = setTimeout(() => {
        timers.current.delete(timer);
        resolve();
      }, 650);
      timers.current.set(timer, resolve);
    });
  const retry = async (id) => {
    if (attempts.current.has(id)) return;
    const retryOwnedFocus = !!chat.current
      ?.querySelector(
        '[data-message-id="failed-request"] [data-slot="message-footer"]',
      )
      ?.contains(document.activeElement);
    const attempt = ++sequence.current;
    attempts.current.set(id, attempt);
    setMessages((current) =>
      current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "queued",
            }
          : message,
      ),
    );
    await wait();
    if (!mounted.current || attempts.current.get(id) !== attempt) return;
    attempts.current.delete(id);
    restoreComposerFocus.current =
      retryOwnedFocus &&
      (document.activeElement === document.body ||
        !!chat.current
          ?.querySelector(
            '[data-message-id="failed-request"] [data-slot="message-footer"]',
          )
          ?.contains(document.activeElement));
    setFailure(false);
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `response-${attempt}`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The receipt total matches the order. The delivery date is one day later than requested.",
          },
        ],
      },
    ]);
  };
  const submit = async (submission) => {
    const id = `request-${++sequence.current}`;
    setMessages((current) => [
      ...current,
      {
        id,
        actor: "user",
        status: "queued",
        parts: [
          ...submission.attachments.map((file) => ({
            ...file,
            type: "file",
          })),
          {
            type: "text",
            text: submission.text,
          },
        ],
      },
    ]);
    await wait();
    if (!mounted.current) return;
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `${id}-response`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The request has been received. I can help compare the receipt details.",
          },
        ],
      },
    ]);
  };
  const stop = () => {
    generationAttempt.current++;
    generationTimers.current.forEach(clearTimeout);
    generationTimers.current = [];
    setGenerating(false);
    setMessages((current) =>
      current.map((message) =>
        message.id === "response"
          ? {
              ...message,
              status: "stopped",
            }
          : message,
      ),
    );
  };
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Chat ref={chat} label="Receipt review">
        <ChatContent>
          <Conversation>
            <ConversationContent>
              {messages.map((message) => (
                <ConversationItem
                  key={message.id}
                  id={message.id}
                  message={message}
                  anchor={message.actor === "user"}
                >
                  <Message
                    actor={message.actor}
                    status={message.status}
                    data-message-id={message.id}
                  >
                    <MessageBody>
                      <MessageParts parts={message.parts} />
                    </MessageBody>
                    {message.id === "failed-request" &&
                    (message.status === "error" ||
                      message.status === "queued") ? (
                      <MessageFooter>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          loading={message.status === "queued"}
                          disabled={message.status === "queued"}
                          onClick={() => void retry(message.id)}
                        >
                          Retry
                        </Button>
                      </MessageFooter>
                    ) : null}
                    {message.status === "queued" &&
                    message.id !== "failed-request" ? (
                      <MessageFooter>
                        <span role="status">Sending…</span>
                      </MessageFooter>
                    ) : null}
                    {message.status === "streaming" && (
                      <span className="ui-sr-only" role="status">
                        Assistant response is in progress.
                      </span>
                    )}
                  </Message>
                </ConversationItem>
              ))}
              {failure ? (
                <ConversationItem id="failed-request-notice">
                  <Message actor="system" status="error">
                    <MessageBody>
                      <span role="status" aria-live="polite">
                        The message could not be sent.
                      </span>
                    </MessageBody>
                  </Message>
                </ConversationItem>
              ) : null}
            </ConversationContent>
          </Conversation>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            feedbackPlacement="conversation"
            defaultValue={
              "Check whether this receipt matches the original order."
            }
            status={generating ? "streaming" : "ready"}
            onStop={stop}
            onSubmit={submit}
          />
        </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>
  );
});

```

composer-sending-9.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)));
}

```

#### Stop stream

Show a partial assistant response while it generates. Stop ends the response and keeps the text already received.

composer-stop-stream-10.jsx

```jsx
import {
  useEffect as useEffect2,
  useRef as useRef2,
  useState as useState3,
} from "react";
import { Button } from "@/components/ui/button";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Message, MessageBody, MessageFooter } from "@/components/ui/message";
import { MessageParts } 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 [messages, setMessages] = useState3([
    {
      id: "request",
      actor: "user",
      status: "complete",
      parts: [
        {
          type: "text",
          text: "Check whether this receipt matches the original order.",
        },
      ],
    },
    {
      id: "response",
      actor: "assistant",
      status: "streaming",
      parts: [
        {
          type: "text",
          text: "I found the receipt. I\u2019m checking the delivery details\u2026",
        },
      ],
    },
  ]);
  const [failure, setFailure] = useState3(false);
  const [generating, setGenerating] = useState3(true);
  const chat = useRef2(null);
  const restoreComposerFocus = useRef2(false);
  const mounted = useRef2(true);
  const sequence = useRef2(0);
  const attempts = useRef2(/* @__PURE__ */ new Map());
  const generationAttempt = useRef2(0);
  const generationTimers = useRef2([]);
  const timers = useRef2(/* @__PURE__ */ new Map());
  useEffect2(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      attempts.current.clear();
      for (const [timer, resolve] of timers.current) {
        clearTimeout(timer);
        resolve();
      }
      timers.current.clear();
    };
  }, []);
  useEffect2(() => {
    const attempt = ++generationAttempt.current;
    const append = (text) => {
      if (!mounted.current || generationAttempt.current !== attempt) return;
      setMessages((current) =>
        current.map((message) =>
          message.id === "response"
            ? {
                ...message,
                parts: [
                  ...message.parts,
                  {
                    type: "text",
                    text,
                  },
                ],
              }
            : message,
        ),
      );
    };
    let started = false;
    const start = () => {
      if (started || !mounted.current || generationAttempt.current !== attempt)
        return;
      started = true;
      generationTimers.current = [
        setTimeout(() => append(" The item total matches the order."), 1500),
        setTimeout(
          () => append(" The delivery date needs one more check."),
          3000,
        ),
        setTimeout(() => {
          if (!mounted.current || generationAttempt.current !== attempt) return;
          setGenerating(false);
          setMessages((current) =>
            current.map((message) =>
              message.id === "response"
                ? {
                    ...message,
                    status: "complete",
                  }
                : message,
            ),
          );
        }, 45000),
      ];
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? null
        : new IntersectionObserver((entries) => {
            if (entries.some((entry) => entry.isIntersecting)) {
              start();
              observer?.disconnect();
            }
          });
    if (observer && chat.current) observer.observe(chat.current);
    else start();
    return () => {
      observer?.disconnect();
      generationAttempt.current++;
      generationTimers.current.forEach(clearTimeout);
      generationTimers.current = [];
    };
  }, ["generating"]);
  useEffect2(() => {
    if (!failure && restoreComposerFocus.current) {
      restoreComposerFocus.current = false;
      if (document.activeElement === document.body)
        chat.current?.querySelector("textarea")?.focus();
    }
  }, [failure]);
  const wait = () =>
    new Promise((resolve) => {
      const timer = setTimeout(() => {
        timers.current.delete(timer);
        resolve();
      }, 650);
      timers.current.set(timer, resolve);
    });
  const retry = async (id) => {
    if (attempts.current.has(id)) return;
    const retryOwnedFocus = !!chat.current
      ?.querySelector(
        '[data-message-id="failed-request"] [data-slot="message-footer"]',
      )
      ?.contains(document.activeElement);
    const attempt = ++sequence.current;
    attempts.current.set(id, attempt);
    setMessages((current) =>
      current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "queued",
            }
          : message,
      ),
    );
    await wait();
    if (!mounted.current || attempts.current.get(id) !== attempt) return;
    attempts.current.delete(id);
    restoreComposerFocus.current =
      retryOwnedFocus &&
      (document.activeElement === document.body ||
        !!chat.current
          ?.querySelector(
            '[data-message-id="failed-request"] [data-slot="message-footer"]',
          )
          ?.contains(document.activeElement));
    setFailure(false);
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `response-${attempt}`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The receipt total matches the order. The delivery date is one day later than requested.",
          },
        ],
      },
    ]);
  };
  const submit = async (submission) => {
    const id = `request-${++sequence.current}`;
    setMessages((current) => [
      ...current,
      {
        id,
        actor: "user",
        status: "queued",
        parts: [
          ...submission.attachments.map((file) => ({
            ...file,
            type: "file",
          })),
          {
            type: "text",
            text: submission.text,
          },
        ],
      },
    ]);
    await wait();
    if (!mounted.current) return;
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `${id}-response`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The request has been received. I can help compare the receipt details.",
          },
        ],
      },
    ]);
  };
  const stop = () => {
    generationAttempt.current++;
    generationTimers.current.forEach(clearTimeout);
    generationTimers.current = [];
    setGenerating(false);
    setMessages((current) =>
      current.map((message) =>
        message.id === "response"
          ? {
              ...message,
              status: "stopped",
            }
          : message,
      ),
    );
  };
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Chat ref={chat} label="Receipt review">
        <ChatContent>
          <Conversation>
            <ConversationContent>
              {messages.map((message) => (
                <ConversationItem
                  key={message.id}
                  id={message.id}
                  message={message}
                  anchor={message.actor === "user"}
                >
                  <Message
                    actor={message.actor}
                    status={message.status}
                    data-message-id={message.id}
                  >
                    <MessageBody>
                      <MessageParts parts={message.parts} />
                    </MessageBody>
                    {message.id === "failed-request" &&
                    (message.status === "error" ||
                      message.status === "queued") ? (
                      <MessageFooter>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          loading={message.status === "queued"}
                          disabled={message.status === "queued"}
                          onClick={() => void retry(message.id)}
                        >
                          Retry
                        </Button>
                      </MessageFooter>
                    ) : null}
                    {message.status === "queued" &&
                    message.id !== "failed-request" ? (
                      <MessageFooter>
                        <span role="status">Sending…</span>
                      </MessageFooter>
                    ) : null}
                    {message.status === "streaming" && (
                      <span className="ui-sr-only" role="status">
                        Assistant response is in progress.
                      </span>
                    )}
                  </Message>
                </ConversationItem>
              ))}
              {failure ? (
                <ConversationItem id="failed-request-notice">
                  <Message actor="system" status="error">
                    <MessageBody>
                      <span role="status" aria-live="polite">
                        The message could not be sent.
                      </span>
                    </MessageBody>
                  </Message>
                </ConversationItem>
              ) : null}
            </ConversationContent>
          </Conversation>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            feedbackPlacement="conversation"
            defaultValue={""}
            status={generating ? "streaming" : "ready"}
            onStop={stop}
            onSubmit={submit}
          />
        </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>
  );
});

```

composer-stop-stream-10.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)));
}

```

#### Failed send and retry

Keep the failed user message in the conversation, show a separate system notice, and retry from the message footer without sending a newer draft.

composer-failed-send-and-retry-11.jsx

```jsx
import {
  useEffect as useEffect2,
  useRef as useRef2,
  useState as useState3,
} from "react";
import { Button } from "@/components/ui/button";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Message, MessageBody, MessageFooter } from "@/components/ui/message";
import { MessageParts } 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 [messages, setMessages] = useState3([
    {
      id: "failed-request",
      actor: "user",
      status: "error",
      parts: [
        {
          type: "text",
          text: "Check whether this receipt matches the original order.",
        },
      ],
    },
  ]);
  const [failure, setFailure] = useState3(true);
  const [generating, setGenerating] = useState3(false);
  const chat = useRef2(null);
  const restoreComposerFocus = useRef2(false);
  const mounted = useRef2(true);
  const sequence = useRef2(0);
  const attempts = useRef2(/* @__PURE__ */ new Map());
  const generationAttempt = useRef2(0);
  const generationTimers = useRef2([]);
  const timers = useRef2(/* @__PURE__ */ new Map());
  useEffect2(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      attempts.current.clear();
      for (const [timer, resolve] of timers.current) {
        clearTimeout(timer);
        resolve();
      }
      timers.current.clear();
    };
  }, []);
  useEffect2(() => {
    return;
    const attempt = ++generationAttempt.current;
    const append = (text) => {
      if (!mounted.current || generationAttempt.current !== attempt) return;
      setMessages((current) =>
        current.map((message) =>
          message.id === "response"
            ? {
                ...message,
                parts: [
                  ...message.parts,
                  {
                    type: "text",
                    text,
                  },
                ],
              }
            : message,
        ),
      );
    };
    let started = false;
    const start = () => {
      if (started || !mounted.current || generationAttempt.current !== attempt)
        return;
      started = true;
      generationTimers.current = [
        setTimeout(() => append(" The item total matches the order."), 1500),
        setTimeout(
          () => append(" The delivery date needs one more check."),
          3000,
        ),
        setTimeout(() => {
          if (!mounted.current || generationAttempt.current !== attempt) return;
          setGenerating(false);
          setMessages((current) =>
            current.map((message) =>
              message.id === "response"
                ? {
                    ...message,
                    status: "complete",
                  }
                : message,
            ),
          );
        }, 45000),
      ];
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? null
        : new IntersectionObserver((entries) => {
            if (entries.some((entry) => entry.isIntersecting)) {
              start();
              observer?.disconnect();
            }
          });
    if (observer && chat.current) observer.observe(chat.current);
    else start();
  }, ["failed"]);
  useEffect2(() => {
    if (!failure && restoreComposerFocus.current) {
      restoreComposerFocus.current = false;
      if (document.activeElement === document.body)
        chat.current?.querySelector("textarea")?.focus();
    }
  }, [failure]);
  const wait = () =>
    new Promise((resolve) => {
      const timer = setTimeout(() => {
        timers.current.delete(timer);
        resolve();
      }, 650);
      timers.current.set(timer, resolve);
    });
  const retry = async (id) => {
    if (attempts.current.has(id)) return;
    const retryOwnedFocus = !!chat.current
      ?.querySelector(
        '[data-message-id="failed-request"] [data-slot="message-footer"]',
      )
      ?.contains(document.activeElement);
    const attempt = ++sequence.current;
    attempts.current.set(id, attempt);
    setMessages((current) =>
      current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "queued",
            }
          : message,
      ),
    );
    await wait();
    if (!mounted.current || attempts.current.get(id) !== attempt) return;
    attempts.current.delete(id);
    restoreComposerFocus.current =
      retryOwnedFocus &&
      (document.activeElement === document.body ||
        !!chat.current
          ?.querySelector(
            '[data-message-id="failed-request"] [data-slot="message-footer"]',
          )
          ?.contains(document.activeElement));
    setFailure(false);
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `response-${attempt}`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The receipt total matches the order. The delivery date is one day later than requested.",
          },
        ],
      },
    ]);
  };
  const submit = async (submission) => {
    const id = `request-${++sequence.current}`;
    setMessages((current) => [
      ...current,
      {
        id,
        actor: "user",
        status: "queued",
        parts: [
          ...submission.attachments.map((file) => ({
            ...file,
            type: "file",
          })),
          {
            type: "text",
            text: submission.text,
          },
        ],
      },
    ]);
    await wait();
    if (!mounted.current) return;
    setMessages((current) => [
      ...current.map((message) =>
        message.id === id
          ? {
              ...message,
              status: "complete",
            }
          : message,
      ),
      {
        id: `${id}-response`,
        actor: "assistant",
        status: "complete",
        parts: [
          {
            type: "text",
            text: "The request has been received. I can help compare the receipt details.",
          },
        ],
      },
    ]);
  };
  const stop = () => {
    generationAttempt.current++;
    generationTimers.current.forEach(clearTimeout);
    generationTimers.current = [];
    setGenerating(false);
    setMessages((current) =>
      current.map((message) =>
        message.id === "response"
          ? {
              ...message,
              status: "stopped",
            }
          : message,
      ),
    );
  };
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Chat ref={chat} label="Receipt review">
        <ChatContent>
          <Conversation>
            <ConversationContent>
              {messages.map((message) => (
                <ConversationItem
                  key={message.id}
                  id={message.id}
                  message={message}
                  anchor={message.actor === "user"}
                >
                  <Message
                    actor={message.actor}
                    status={message.status}
                    data-message-id={message.id}
                  >
                    <MessageBody>
                      <MessageParts parts={message.parts} />
                    </MessageBody>
                    {message.id === "failed-request" &&
                    (message.status === "error" ||
                      message.status === "queued") ? (
                      <MessageFooter>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          loading={message.status === "queued"}
                          disabled={message.status === "queued"}
                          onClick={() => void retry(message.id)}
                        >
                          Retry
                        </Button>
                      </MessageFooter>
                    ) : null}
                    {message.status === "queued" &&
                    message.id !== "failed-request" ? (
                      <MessageFooter>
                        <span role="status">Sending…</span>
                      </MessageFooter>
                    ) : null}
                    {message.status === "streaming" && (
                      <span className="ui-sr-only" role="status">
                        Assistant response is in progress.
                      </span>
                    )}
                  </Message>
                </ConversationItem>
              ))}
              {failure ? (
                <ConversationItem id="failed-request-notice">
                  <Message actor="system" status="error">
                    <MessageBody>
                      <span role="status" aria-live="polite">
                        The message could not be sent.
                      </span>
                    </MessageBody>
                  </Message>
                </ConversationItem>
              ) : null}
            </ConversationContent>
          </Conversation>
        </ChatContent>
        <ChatFooter>
          <ChatComposer
            feedbackPlacement="conversation"
            defaultValue={""}
            status={generating ? "streaming" : "ready"}
            onStop={stop}
            onSubmit={submit}
          />
        </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>
  );
});

```

composer-failed-send-and-retry-11.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)));
}

```

#### Delivery failure

A rejected send keeps the draft and reports the failure in the helper row below the card. Retry with the same send action. The persistent description stays visible.

composer-delivery-failure-12.jsx

```jsx
import { useRef as useRef3, useState as useState5 } from "react";
import {
  Composer as Composer2,
  ComposerInput as ComposerInput2,
  ComposerSubmit as ComposerSubmit2,
  ComposerToolbar as ComposerToolbar2,
} from "@/components/ui/composer";

export default function Example() {
  const attempts = useRef3(0);
  const [sent, setSent] = useState5("");
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        defaultValue="Check whether the totals match."
        description="AI can make mistakes. Check important details."
        onSubmit={() => {
          if (attempts.current++ === 0)
            return Promise.reject(
              new Error(
                "The message service did not respond. Check your connection and try again.",
              ),
            );
          setSent("Message sent after retry.");
        }}
      >
        <ComposerInput2 />
        <ComposerToolbar2>
          <ComposerSubmit2 />
        </ComposerToolbar2>
      </Composer2>
      <DemoNote>{sent}</DemoNote>
    </div>
  );
}

function DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

```

#### Persistent limit

A rate limit is not a draft error. Show it in a Banner in the secondary region, keep the draft editable, and disable send until the window resets.

composer-persistent-limit-13.jsx

```jsx
import {
  Composer as Composer2,
  ComposerInput as ComposerInput2,
  ComposerSubmit as ComposerSubmit2,
  ComposerToolbar as ComposerToolbar2,
} from "@/components/ui/composer";
import { Banner } from "@/components/ui/banner";

export default function Example() {
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        defaultValue="Compare the April receipts."
        description="AI can make mistakes. Check important details."
        secondary={
          <Banner
            tone="warning"
            role="alert"
            width="fill"
            title="Rate limit reached"
          >
            You can send again at 14:40. Your draft is kept.
          </Banner>
        }
        onSubmit={() => undefined}
      >
        <ComposerInput2 />
        <ComposerToolbar2>
          <ComposerSubmit2 disabled />
        </ComposerToolbar2>
      </Composer2>
    </div>
  );
}

```

#### Disabled

Preserve the disabled draft while preventing edits and actions.

composer-disabled-14.jsx

```jsx
import { Composer as Composer2 } from "@/components/ui/composer";

export default function Example() {
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        defaultValue="This draft is unavailable"
        disabled
        onSubmit={() => undefined}
      />
    </div>
  );
}

```

#### Read-only

Keep an archived draft readable while preventing changes and sending.

composer-read-only-15.jsx

```jsx
import { Composer as Composer2 } from "@/components/ui/composer";

export default function Example() {
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        defaultValue="This archived draft stays readable."
        readOnly
        onSubmit={() => undefined}
      />
    </div>
  );
}

```

#### Blocked attachment

Keep a failed file visible and prevent sending until the caller removes or replaces it.

composer-blocked-attachment-16.jsx

```jsx
import { useState as useState5 } from "react";
import {
  Composer as Composer2,
  ComposerAttachments as ComposerAttachments2,
  ComposerInput as ComposerInput2,
  ComposerSubmit as ComposerSubmit2,
  ComposerToolbar as ComposerToolbar2,
} from "@/components/ui/composer";

export default function Example() {
  const [files, setFiles] = useState5([
    {
      ...receipt,
      status: "error",
      error: "Remove the failed receipt before sending.",
    },
  ]);
  const { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2
        defaultValue="Review this receipt"
        attachments={files}
        onSubmit={onSubmit}
        attachmentContent={
          <ComposerAttachments2 onRemove={() => setFiles([])} />
        }
      >
        <ComposerInput2 />
        <ComposerToolbar2>
          <ComposerSubmit2 />
        </ComposerToolbar2>
      </Composer2>
      <DemoNote>
        {message ||
          (files.length
            ? null
            : "Attachment removed. The draft is ready to send.")}
      </DemoNote>
    </div>
  );
}

function DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

var receipt = {
  id: "receipt",
  name: "receipt.pdf",
  mediaType: "application/pdf",
  status: "ready",
};

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

### Composer composition

#### Attached task progress

Attach a caller-owned checklist when the request needs a few visible subtasks. The clock reports the actual completed count, and the rows can be collapsed without changing the draft.

composer-attached-task-progress-17.jsx

```jsx
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";
import { TodoList } from "@/components/ui/todo-list";

export default function Example() {
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatComposer
        defaultValue="Draft a concise weekly update from the latest team changes."
        onSubmit={() => undefined}
        secondary={<TodoList title="Weekly update" items={weeklyTasks} />}
      />
    </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>
  );
});

var weeklyTasks = [
  {
    id: "gather",
    label: "Gather changes",
    status: "complete",
  },
  {
    id: "draft",
    label: "Draft summary",
    status: "active",
  },
  {
    id: "review",
    label: "Review next steps",
    status: "pending",
  },
];

```

composer-attached-task-progress-17.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)));
}

```

#### Tool approval

Attach a pending decision above the editor. Deny and Allow once resolve the caller-owned approval state.

composer-tool-approval-18.jsx

```jsx
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";
import { useState as useState4 } from "react";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState4("pending");
  const [sent, setSent] = useState4(false);
  return (
    <PreviewWide>
      <ChatComposer
        defaultValue=""
        onSubmit={() => setSent(true)}
        secondary={
          <ToolApproval
            prompt="Save weekly update?"
            approvalId="save-weekly-update"
            state={state}
            onApprove={() => setState("approved")}
            onDeny={() => setState("denied")}
          >
            docs/weekly-update.md
          </ToolApproval>
        }
      />
      {sent ? <p role="status">Message sent.</p> : null}
    </PreviewWide>
  );
}

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 PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

composer-tool-approval-18.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)));
}

```

### Speech input

#### Voice note

Capture and pause with Audio recorder. Finish creates a local clip for review. Send uses Composer's submission contract. A rejected send keeps the audio and typed context. Discard removes only the clip. The typed draft can still be sent without microphone access. This example acknowledges delivery locally; pass onSend to connect application delivery.

composer-voice-note-19.jsx

```jsx
import * as React from "react";
import {
  AudioRecorder,
  useAudioRecorder,
} from "@/components/ui/audio-recorder";
import { AudioPlayer } from "@/components/ui/audio-player";
import { IconButton } from "@/components/ui/button";
import { Loader } from "@/components/ui/loader";
import { Mic, X } from "lucide-react";
import {
  Composer,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { Message, MessageBody } from "@/components/ui/message";

export default function Example() {
  const [draft, setDraft] = React.useState("");
  const [capture, setCapture] = React.useState(null);
  const [recordingState, setRecordingState] = React.useState("idle");
  const [sending, setSending] = React.useState(false);
  const mounted = React.useRef(false);
  const submitted = React.useRef(null);
  React.useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);
  const [sent, setSent] = React.useState([]);
  const urls = React.useRef(/* @__PURE__ */ new Set());
  const captureRef = React.useRef(capture);
  captureRef.current = capture;
  const nextId = React.useRef(0);
  React.useEffect(
    () => () => {
      for (const url of urls.current) URL.revokeObjectURL(url);
      urls.current.clear();
    },
    [],
  );
  const releaseDraft = () => {
    const previous = captureRef.current;
    if (previous) {
      URL.revokeObjectURL(previous.url);
      urls.current.delete(previous.url);
    }
    captureRef.current = null;
    setCapture(null);
  };
  const capturing = ["requesting", "recording", "paused", "stopping"].includes(
    recordingState,
  );
  return (
    <div className="voice-composition voice-composition--composer">
      {sent.map((message) => (
        <Message
          key={message.id}
          actor="user"
          aria-label={message.clip ? "Sent voice note" : "Sent message"}
          style={
            message.clip
              ? {
                  gridTemplateColumns: "minmax(0, 360px)",
                }
              : undefined
          }
        >
          <MessageBody>
            {message.text && <p>{message.text}</p>}
            {message.clip && (
              <AudioPlayer
                src={message.clip.url}
                duration={message.clip.seconds}
                label="Voice note"
              />
            )}
          </MessageBody>
        </Message>
      ))}
      <AudioRecorder
        label="Voice note"
        appearance="embedded"
        className="voice-composition__capture"
        onStateChange={(state) => {
          setRecordingState(state.status);
          if (state.status === "idle") releaseDraft();
        }}
        onRecordingComplete={(blob, seconds) => {
          releaseDraft();
          const url = URL.createObjectURL(blob);
          urls.current.add(url);
          const clip = {
            blob,
            seconds,
            url,
          };
          captureRef.current = clip;
          setCapture(clip);
        }}
      >
        <Composer
          label="Message"
          value={draft}
          onValueChange={setDraft}
          readOnly={capturing}
          attachments={
            capture
              ? [
                  {
                    id: "voice-draft",
                    name: "Voice note",
                    mediaType: capture.blob.type || "audio/webm",
                    url: capture.url,
                    size: capture.blob.size,
                    status: "ready",
                  },
                ]
              : []
          }
          attachmentContent={null}
          onSubmit={async (submission) => {
            const clip = captureRef.current;
            submitted.current = clip;
            setSending(true);
            try {
              if (clip) await undefined;
              else await undefined;
            } finally {
              if (mounted.current) setSending(false);
            }
            if (!mounted.current) return;
            setSent((items) => [
              ...items,
              {
                clip,
                text: submission.text,
                id: ++nextId.current,
              },
            ]);
          }}
          onSubmitted={() => {
            const snapshot = submitted.current;
            submitted.current = null;
            if (!snapshot || snapshot !== captureRef.current) return;
            captureRef.current = null;
            setCapture(null);
            setRecordingState("idle");
          }}
        >
          <VoiceCaptureControls
            hasCapture={Boolean(capture)}
            sending={sending}
          />
          <ComposerInput placeholder="Add context…" />
          <ComposerToolbar>
            <ComposerToolbar.Start>
              <VoiceToolbarRecordAction disabled={sending} />
            </ComposerToolbar.Start>
            <ComposerToolbar.End>
              <ComposerSubmit disabled={capturing} />
            </ComposerToolbar.End>
          </ComposerToolbar>
        </Composer>
      </AudioRecorder>
    </div>
  );
}

function VoiceCaptureControls({ hasCapture, sending }) {
  const recorder = useAudioRecorder();
  React.useEffect(() => {
    if (!hasCapture && recorder.status === "ready") recorder.discard();
  }, [hasCapture, recorder.discard, recorder.status]);
  let controls = null;
  if (recorder.status === "ready") {
    controls = (
      <div className="ui-audio-recorder__preview">
        <AudioRecorder.Preview variant="waveform">
          <AudioPlayer.ControlBar>
            <AudioPlayer.PlayPause size="icon-xs" />
            <AudioPlayer.Seek />
            <AudioPlayer.Time />
            <AudioPlayer.Mute size="icon-xs" />
          </AudioPlayer.ControlBar>
        </AudioRecorder.Preview>
        <AudioRecorder.DiscardButton />
      </div>
    );
  } else if (recorder.status === "requesting") {
    controls = (
      <>
        <span className="ui-audio-recorder__waiting">
          <Loader size={14} />
          Waiting for microphone
        </span>
        <IconButton
          type="button"
          variant="ghost"
          icon={<X />}
          aria-label="Cancel recording"
          onClick={recorder.cancel}
        />
      </>
    );
  } else if (["recording", "paused", "stopping"].includes(recorder.status)) {
    controls = (
      <>
        <AudioRecorder.Time />
        <div className="ui-audio-recorder__actions">
          {recorder.status === "stopping" ? (
            <Loader size={14} label="Finishing recording" />
          ) : (
            <>
              <AudioRecorder.PauseResume />
              <AudioRecorder.StopButton />
            </>
          )}
          <AudioRecorder.DiscardButton />
        </div>
      </>
    );
  }
  return controls ? (
    <div
      className="voice-composition__capture-controls"
      inert={sending || undefined}
    >
      {controls}
    </div>
  ) : null;
}

function VoiceToolbarRecordAction({ disabled }) {
  const recorder = useAudioRecorder();
  if (recorder.status !== "idle" && recorder.status !== "error") return null;
  return (
    <IconButton
      type="button"
      size="icon-xs"
      variant="ghost"
      disabled={disabled}
      aria-label={
        recorder.status === "error"
          ? "Try recording again"
          : "Record voice note"
      }
      icon={<Mic size={14} aria-hidden="true" />}
      onClick={recorder.record}
    />
  );
}

```

composer-voice-note-19.css

```css
/* apps/web/src/demos/ui/voice-compositions.css */
.voice-composition {
  width: min(100%, 520px);
  min-width: 0;
  color: var(--foreground);
  font: var(--font-size-base)/var(--leading-copy) var(--font-sans);
}
.voice-composition--composer {
  display: grid;
  gap: var(--space-4);
}
.voice-composition__capture {
  display: contents;
}
.voice-composition__capture > .ui-composer-toolbar {
  padding-inline-end: 0;
}
.voice-composition__capture .ui-audio-recorder__preview > .ui-button {
  width: var(--space-6);
  min-width: var(--space-6);
  height: var(--space-6);
  min-height: var(--space-6);
}
.voice-composition .ui-message-body {
  min-width: 0;
}

```

#### Dictation

Dictation becomes editable text. Finish stops recognition; Cancel restores the text from before dictation. The example uses the browser's optional SpeechRecognition API. Support and recognition service depend on the browser. Applications can supply their own ASR in the same composition. Capture status stays separate from Composer submission status.

composer-dictation-20.jsx

```jsx
import * as React from "react";
import { Mic, Square, X } from "lucide-react";
import { Button, IconButton } from "@/components/ui/button";
import {
  Composer,
  ComposerAction,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { Message, MessageBody } from "@/components/ui/message";

export default function Example() {
  const [draft, setDraft] = React.useState("");
  const [partial, setPartial] = React.useState("");
  const [status, setStatus] = React.useState("idle");
  const busy = status !== "idle";
  const [error, setError] = React.useState(null);
  const [messages, setMessages] = React.useState([]);
  const recognition = React.useRef(null);
  const before = React.useRef("");
  const cancel = () => {
    const active = recognition.current;
    recognition.current = null;
    active?.abort();
    setDraft(before.current);
    setPartial("");
    setStatus("idle");
  };
  React.useEffect(
    () => () => {
      const active = recognition.current;
      recognition.current = null;
      active?.abort();
    },
    [],
  );
  const start = () => {
    if (recognition.current) return;
    const browser = window;
    const Constructor =
      browser.SpeechRecognition ?? browser.webkitSpeechRecognition;
    if (!Constructor) {
      setError("Dictation is unavailable in this browser. You can still type.");
      return;
    }
    before.current = draft;
    setError(null);
    const active = new Constructor();
    recognition.current = active;
    let receivedText = false;
    active.continuous = true;
    active.interimResults = true;
    active.lang = document.documentElement.lang || "en-US";
    active.onstart = () => {
      if (recognition.current === active) setStatus("listening");
    };
    active.onresult = (event) => {
      if (recognition.current !== active) return;
      let final = "",
        interim = "";
      for (let index = 0; index < event.results.length; index++) {
        const result = event.results[index];
        if (result.isFinal) final += result[0].transcript;
        else interim += result[0].transcript;
      }
      setDraft(
        [before.current.trimEnd(), final.trim()].filter(Boolean).join(" "),
      );
      receivedText = final.trim().length > 0;
      setPartial(interim);
    };
    active.onerror = (event) => {
      if (recognition.current !== active) return;
      recognition.current = null;
      active.abort();
      setStatus("idle");
      setPartial("");
      const reasons = {
        "not-allowed":
          "Microphone access was denied. Allow access or type your message.",
        "service-not-allowed":
          "This browser cannot use its speech service. Open this page in Chrome or type your message.",
        network:
          "Cannot connect to the browser\u2019s speech service. Check your connection or try Chrome. Your text is kept.",
        "audio-capture":
          "No microphone is available. Check your microphone or type your message.",
        "no-speech": "No speech was detected. Try again. Your text is kept.",
        "language-not-supported":
          "The speech service does not support this language. You can still type.",
      };
      setError(
        reasons[event.error] ??
          `Dictation failed (${event.error}). Your text is kept.`,
      );
    };
    active.onend = () => {
      if (recognition.current !== active) return;
      recognition.current = null;
      setStatus("idle");
      setPartial("");
      if (!receivedText)
        setError("No speech text was received. Try again. Your text is kept.");
    };
    setStatus("starting");
    try {
      active.start();
    } catch {
      recognition.current = null;
      setStatus("idle");
      setError("Dictation could not start. You can still type.");
    }
  };
  const activity =
    status === "starting"
      ? "Starting dictation\u2026"
      : status === "stopping"
        ? "Finishing dictation\u2026"
        : "Listening\u2026";
  const displayedDraft = busy
    ? [draft.trimEnd(), partial.trim()].filter(Boolean).join(" ")
    : draft;
  return (
    <div className="voice-composition voice-composition--composer">
      {messages.map((text, index) => (
        <Message key={index} actor="user">
          <MessageBody>{text}</MessageBody>
        </Message>
      ))}
      <Composer
        label="Message"
        value={displayedDraft}
        onValueChange={setDraft}
        readOnly={busy}
        onSubmit={(submission) =>
          setMessages((items) => [...items, submission.text])
        }
      >
        <ComposerInput placeholder={busy ? activity : "Ask anything\u2026"} />
        {busy && (
          <span className="ui-sr-only" role="status">
            {activity}
          </span>
        )}
        <ComposerToolbar>
          <ComposerToolbar.End>
            {busy ? (
              <>
                {status !== "starting" && (
                  <Button
                    type="button"
                    variant="ghost"
                    leadingIcon={<Square />}
                    disabled={status === "stopping"}
                    onClick={() => {
                      setStatus("stopping");
                      recognition.current?.stop();
                    }}
                  >
                    Finish dictation
                  </Button>
                )}
                <IconButton
                  type="button"
                  aria-label="Cancel dictation"
                  icon={<X />}
                  variant="ghost"
                  size="icon"
                  className="ui-composer-action"
                  onClick={cancel}
                />
              </>
            ) : (
              <ComposerAction
                aria-label="Dictate message"
                icon={<Mic />}
                onClick={start}
              />
            )}
            <ComposerSubmit disabled={busy} />
          </ComposerToolbar.End>
        </ComposerToolbar>
      </Composer>
      {error && (
        <p className="voice-composition__draft" role="alert">
          {error}
        </p>
      )}
    </div>
  );
}

```

composer-dictation-20.css

```css
/* apps/web/src/demos/ui/voice-compositions.css */
.voice-composition {
  width: min(100%, 520px);
  min-width: 0;
  color: var(--foreground);
  font: var(--font-size-base)/var(--leading-copy) var(--font-sans);
}
.voice-composition--composer {
  display: grid;
  gap: var(--space-4);
}
.voice-composition .ui-message-body {
  min-width: 0;
}
.voice-composition__draft {
  margin: 0;
  color: var(--muted-foreground);
  white-space: pre-wrap;
  overflow-wrap: anywhere;
}

```

#### Caller-owned label

Use a native Label and ComposerInput id when the label is part of a larger form or layout; Composer does not add a label API.

composer-caller-owned-label-21.jsx

```jsx
import { useId, useState as useState5 } from "react";
import {
  Composer as Composer2,
  ComposerInput as ComposerInput2,
  ComposerSubmit as ComposerSubmit2,
  ComposerToolbar as ComposerToolbar2,
} from "@/components/ui/composer";
import { Label } from "@/components/ui/label";

export default function Example() {
  const inputId = useId();
  const { message, onSubmit } = useSendReceipt();
  return (
    <div
      data-preview-wide
      style={{
        width: "100%",
        maxInlineSize: 480,
      }}
    >
      <Composer2 onSubmit={onSubmit}>
        <Label
          style={{
            color: "var(--muted-foreground)",
            fontSize: "var(--font-size-2xs)",
            lineHeight: "var(--space-4)",
          }}
          htmlFor={inputId}
        >
          What should the assistant consider?
        </Label>
        <ComposerInput2
          style={{
            fontSize: "var(--font-size-sm)",
            lineHeight: "22px",
          }}
          id={inputId}
          placeholder="Add the key details…"
        />
        <ComposerToolbar2>
          <ComposerSubmit2 />
        </ComposerToolbar2>
      </Composer2>
      <DemoNote>{message}</DemoNote>
    </div>
  );
}

function DemoNote({ children }) {
  return children ? (
    <p
      className="ui-caption"
      role="status"
      style={{
        textAlign: "center",
        marginBlockStart: "var(--gap-list)",
      }}
    >
      {children}
    </p>
  ) : null;
}

function useSendReceipt() {
  const [message, setMessage] = useState5("");
  const onSubmit = ({ text, attachments }) => {
    setMessage(
      attachments.length
        ? `Sent ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}${text.trim() ? " with the message" : ""}.`
        : "Message sent.",
    );
  };
  return {
    message,
    onSubmit,
  };
}

```

## API reference

Composer properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| onSubmit (required) | (submission: ComposerSubmission) => void \| Promise<void> | — | Receives the exact draft and attachment snapshot. |
| onSubmitted | (submission: ComposerSubmission) => void | — | Runs after successful delivery and the draft reset check. Remove captured files here without clearing a newer draft. |
| value | string | — | Controls the draft value. |
| defaultValue | string | "" | Seeds an uncontrolled draft. |
| onValueChange | (text: string) => void | — | Receives controlled and uncontrolled draft edits. |
| attachments | readonly AttachmentFile[] | [] | Provides caller-owned attachment identities and upload states. |
| secondary | ReactNode | — | Places caller-owned task or approval content above the primary editor. Draft files stay inside the field; pass null to omit the secondary panel. |
| secondaryPlacement | top \| bottom | top | Places the secondary LayerCard region above or below the primary surface. |
| secondaryVisible | boolean | true | Hides a supplied secondary panel while keeping the draft and primary editor. |
| attachmentContent | ReactNode | — | Customizes the draft-file region inside the field; defaults to ComposerAttachments. Pass null to omit it. |
| description | ReactNode | — | Shows a centered persistent helper below the card and adds it to ComposerInput's accessible description. |
| initialRows | number | 1 | Sets the first native textarea row after positive-integer normalization. |
| maxRows | number | 8 | Caps native textarea growth after normalization; values below initialRows are raised. |
| feedbackPlacement | inline \| conversation | inline | Keeps transport feedback inline, or lets conversation messages show sending, generation and send failures. Validation feedback stays visible. |
| status | ready \| submitting \| streaming \| error | ready | Reports caller-owned runtime state. |
| onStop | () => void \| Promise<void> | — | Stops a streaming operation when supplied. |
| onRetry | () => void \| Promise<void> | — | Retries a failed operation when supplied. |
| disabled | boolean | false | Disables the input and actions. |
| readOnly | boolean | false | Keeps the draft readable without allowing changes or actions. |
| label | string | Message | Names the native ComposerInput unless it supplies its own accessible name. |
