<!-- generated by scripts/gen-docs.mjs from docs/system/composer.md. Edit the source and rerun. -->
# Composer

## Description
Writes the next message, or a question to an agent: the words, the people, agents, files and commands they name, any files that go with them, and the press that sends them, with a reason whenever it cannot send yet and a Stop while an answer streams.

`import { Composer, ComposerAttach, ComposerAttachments, ComposerInput, ComposerSend, useDraft } from "@/components/cobalt/ui/composer"`, source `registry/cobalt/ui/composer.tsx`, status `ready-with-gaps`. The text model is `registry/cobalt/lib/composer-text.ts`.
Foundation: `Base UI Field.Control`. Traps checked: `trap/field-form-enter`, `trap/submit-repeat`, `trap/disabled-drops-focus`, `trap/tooltip-disabled-trigger`, `trap/touch-input-zoom`, `trap/loading-label-swap`, `trap/loading-layout-shift`, `trap/field-label`, `trap/button-icon-name`, `trap/toast-errors`.

`trap/field-form-enter` is answered by the composer being a `form` with one submit, Send (Accessibility). `trap/submit-repeat` by a send that returned a promise holding the draft read-only and returning early until it settles, and by Enter ignoring key repeat (States). `trap/disabled-drops-focus` and `trap/tooltip-disabled-trigger` by Send using `aria-disabled`, so it keeps focus and its tooltip, with its reason also as its description (ARIA). `trap/touch-input-zoom` by the field's 16px text below 768px (Tokens). `trap/loading-label-swap` and `trap/loading-layout-shift` by Send keeping its 32px box and name while its glyph turns to a spinner (States). `trap/field-label` by `aria-label` or a `Field` around it, never the placeholder alone (Rules). `trap/button-icon-name` by every icon button's label (ARIA). `trap/toast-errors` by a failed send staying in the field with a message under it (States).

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| Base UI `Field.Control` as the textarea, so a `Field` around the composer labels and describes it | One reducer for the draft and the send, read as one phase (`idle`, `composing`, `suggesting`, `sending`, `streaming`, `failed`) on `data-state`; Tag's two shapes, one row when empty and the field over a row of tools once there are words or files, moved between in one motion with every height change carried by the same transition; the parts sorted by the root, so they can be written in any order; Enter to send, Shift+Enter for a line, Enter for a line on a touch screen, `sendKey="mod-enter"`; @ and / lists from a list or an async source, with a 150ms debounce, an abort per query, loading, empty and failed rows, on the combobox pattern with the focus kept in the field; a pick written into the text through the browser's own editing so Undo takes it back, drawn as a tint on a copy of the text under the field, deleted whole by Backspace or Delete, and never entered by the caret; a structured send (`text`, `mentions`, `command`, `segments`, `files`); files from the chooser, a paste or a drop, each ready, uploading with its share filling its `FileTypeIcon`, failed with the glyph as Retry, or refused with its reason; `maxLength` with a count near the limit; `disabled` with its reason in the field; Send held with its reason, a spinner after 250ms, Stop while streaming; `useDraft` to keep the words in this browser. Kept from Tag's composer: the two shapes and the motion between them, the plain-text chips, Escape closing the list for one word, refused files shown with why. Dropped from Tag: dictation, the window picker, the send journal, the + tray and the inset at rest |

The field stays a plain textarea rather than a `contenteditable`, because the browser already handles an input method's composition, Undo and Redo, a rich paste arriving as plain text, the caret, right-to-left text, autocorrect and dictation on a phone, and a screen reader reads "@Maya Chen" as the words it is. A token is recognised wherever its exact words still stand on their own, so an Undo that removes the words removes the token, and Redo brings both back.

### Shape
- At rest, with no words and no files: one row, 44px tall. The tools sit at the start, the field after them and Send at the end, with a corner concentric with the 32px buttons: 16px with the default corners, and half the height, a pill, when the controls are pills (`--r-composer`).
- Open, from the first character or file: the field takes the whole top and the tools and Send keep a row along the foot. The corner becomes a surface's (`--r-2xl`).
- Between them: the box grows on `--t-settle` with the tools riding its foot, the field slides to the start on the in-out curve so the words never cross the tools, and the corner eases with it. Each new line, the tray appearing and the box closing after a send move the same way.

## Examples
A direct message: Attach, the field and Send on one row, opening to the field over its tools as you write.

Real uses, 0 call sites (`rg -n "<Composer\b" app registry --glob '!registry/cobalt/ui/*'`).

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/composer/default.tsx` | default | A direct message. One row that grows with the text; Enter sends, Shift+Enter starts a line, and the draft is still there after a reload |
| `docs/system/examples/composer/in-assistant.tsx` | composition:Avatar | A research assistant. Type @ to bring in a person, an agent or a file, and / at the start for a command. Files upload as they are added, and Stop ends an answer while it streams |
| `docs/system/examples/composer/state-pending.tsx` | state:pending | A send that waits on the server. The draft stays in the field, read only, and Send shows a spinner in its own box until the answer comes |
| `docs/system/examples/composer/state-failed.tsx` | state:failure | A send that fails. The draft stays with the reason under the box, and sending again tries again; a line under the example says to press Send |
| `docs/system/examples/composer/dictation.tsx` | composition:ComposerDictate | A composer you can talk to. The mic beside Send opens the microphone: Cancel takes the tools' place, a waveform scrolls in from the right, and Stop writes what you said into the field to read before you send |
| `docs/system/examples/composer/state-held.tsx` | state:held | When it cannot send, it says why. A conversation that is closed says so in the field, and near the limit a count appears beside Send |

Example: A direct message. One row that grows with the text; Enter sends, Shift+Enter starts a line, and the draft is still there after a reload (`docs/system/examples/composer/default.tsx`)

```tsx
import { useState } from "react";

import {
  Composer,
  ComposerAttach,
  ComposerAttachments,
  ComposerInput,
  ComposerSend,
  useDraft,
} from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

export default function Example() {
  const [sent, setSent] = useState<string[]>([]);
  const draft = useDraft("example-dm-maya");
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col gap-3">
        <Composer
          {...draft}
          onSend={({ text, files }) =>
            setSent((list) => [...list, [text, ...files.map((file) => file.name)].filter(Boolean).join(", ")])
          }
        >
          <ComposerAttachments />
          <ComposerAttach accept="image/*,.pdf" maxSize={20_000_000} />
          <ComposerInput aria-label="Message Maya Chen" placeholder="Message Maya" />
          <ComposerSend />
        </Composer>
        <ul className="flex flex-col gap-1 text-sm text-muted-foreground" aria-live="polite">
          {sent.map((line, index) => (
            <li key={index}>Sent: {line}</li>
          ))}
        </ul>
      </div>
    </TooltipProvider>
  );
}
```

Example: A research assistant. Type @ to bring in a person, an agent or a file, and / at the start for a command. Files upload as they are added, and Stop ends an answer while it streams (`docs/system/examples/composer/in-assistant.tsx`)

```tsx
import { useEffect, useRef, useState } from "react";

import { BotIcon, FileIcon } from "@/components/cobalt/icon";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/cobalt/ui/avatar";
import {
  Composer,
  ComposerAttach,
  ComposerAttachments,
  ComposerInput,
  ComposerSend,
  type ComposerDraft,
  type ComposerItem,
} from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";
import { rankItems, type ComposerSegment } from "@/lib/cobalt/composer-text";

const person = (id: string, label: string, description: string, photo: string): ComposerItem => ({
  id,
  label,
  description,
  group: "People",
  icon: (
    <Avatar size="sm" decorative>
      <AvatarImage src={`/photos/${photo}`} />
      <AvatarFallback />
    </Avatar>
  ),
});
const agent = (id: string, label: string, description: string): ComposerItem => ({
  id,
  label,
  description,
  group: "Agents",
  icon: <BotIcon />,
});
const file = (id: string, label: string, description: string): ComposerItem => ({
  id,
  label,
  description,
  group: "Files",
  icon: <FileIcon />,
});

const everyone: ComposerItem[] = [
  person("maya", "Maya Chen", "Research lead", "portrait-1.webp"),
  person("daniel", "Daniel Okafor", "Data analyst", "portrait-2.webp"),
  person("sofia", "Sofia Reyes", "Product designer", "portrait-3.webp"),
  person("james", "James Whitaker", "Customer success", "portrait-4.webp"),
  person("priya", "Priya Nair", "Engineering", "portrait-5.webp"),
  agent("literature", "Literature agent", "Finds and reads papers"),
  agent("data", "Data agent", "Runs queries on the warehouse"),
  agent("citations", "Citation checker", "Checks every source"),
  file("survey", "q3-survey-results.csv", "CSV, 1.2 MB"),
  file("interviews", "interview-notes.pdf", "PDF, 840 KB"),
  file("churn", "churn-dashboard.png", "PNG, 310 KB"),
];

const commands: ComposerItem[] = [
  { id: "summarize", label: "summarize", description: "Sum up a file or a thread" },
  { id: "compare", label: "compare", description: "Set two sources side by side" },
  { id: "chart", label: "chart", description: "Draw a chart from a table" },
  { id: "cite", label: "cite", description: "Add sources to the last answer" },
  { id: "translate", label: "translate", description: "Translate into another language" },
];

// The stand-in server is out of reach while the browser is offline or the address has
// ?network=offline (the docs frame's Offline toggle sets it).
const offline = () => !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
const wait = (ms: number, signal?: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => (offline() ? reject(new Error("offline")) : resolve()), ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(new Error("aborted"));
    });
  });

// Each file goes up in ten steps over 1.5 seconds and says how far it is.
async function upload(_: File, { signal, progress }: { signal: AbortSignal; progress: (percent: number) => void }) {
  for (let step = 1; step <= 10; step++) {
    await wait(150, signal);
    progress(step * 10);
  }
}

async function findMentions(query: string, signal: AbortSignal) {
  await wait(300, signal);
  return rankItems(everyone, query).slice(0, 8);
}

const answer =
  "Across the 412 responses, the most common reason for leaving was onboarding that took more than a week. Daniel's churn dashboard shows the same pattern for accounts under 20 seats, and the interview notes name setup calls as the step people waited on longest.";

type Turn = { question: ComposerSegment[]; answer: string; stopped: boolean };

export default function Example() {
  const [turns, setTurns] = useState<Turn[]>([]);
  const [streaming, setStreaming] = useState(false);
  const timer = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
  useEffect(() => () => clearInterval(timer.current), []);

  function stop() {
    clearInterval(timer.current);
    setStreaming(false);
    setTurns((list) => list.map((turn, index) => (index === list.length - 1 ? { ...turn, stopped: true } : turn)));
  }

  function ask(draft: ComposerDraft) {
    const words = answer.split(" ");
    setTurns((list) => [...list, { question: draft.segments, answer: "", stopped: false }]);
    setStreaming(true);
    let shown = 0;
    timer.current = setInterval(() => {
      shown += 1;
      setTurns((list) =>
        list.map((turn, index) =>
          index === list.length - 1 ? { ...turn, answer: words.slice(0, shown).join(" ") } : turn,
        ),
      );
      if (shown >= words.length) {
        clearInterval(timer.current);
        setStreaming(false);
      }
    }, 70);
  }

  return (
    <TooltipProvider>
      <div className="flex w-full max-w-xl flex-col gap-4">
        {turns.length > 0 && (
          <ol className="flex flex-col gap-4 text-sm" aria-live="polite">
            {turns.map((turn, index) => (
              <li key={index} className="flex flex-col gap-2">
                <p className="self-end rounded-2xl bg-muted px-3 py-2">
                  {turn.question.map((segment, at) =>
                    segment.kind === "text" ? (
                      segment.text
                    ) : (
                      <span key={at} className="text-primary-ink">
                        {segment.text}
                      </span>
                    ),
                  )}
                </p>
                <p className="text-foreground">
                  {turn.answer}
                  {turn.stopped && <span className="text-muted-foreground"> Stopped.</span>}
                </p>
              </li>
            ))}
          </ol>
        )}
        <Composer
          mentions={findMentions}
          commands={commands}
          streaming={streaming}
          onStop={stop}
          onSend={ask}
        >
          <ComposerAttachments />
          <ComposerInput aria-label="Ask the research assistant" placeholder="Ask about your research" />
          <ComposerAttach accept=".pdf,.csv,.xlsx,image/*" maxSize={50_000_000} upload={upload} />
          <ComposerSend />
        </Composer>
      </div>
    </TooltipProvider>
  );
}
```

Example: A composer you can talk to. The mic beside Send opens the microphone: Cancel takes the tools' place, a waveform scrolls in from the right, and Stop writes what you said into the field to read before you send (`docs/system/examples/composer/dictation.tsx`)

```tsx
import { useState } from "react";

import {
  Composer,
  ComposerAttach,
  ComposerDictate,
  ComposerInput,
  ComposerSend,
} from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

export default function Example() {
  const [sent, setSent] = useState<string[]>([]);
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col gap-3">
        <Composer onSend={({ text }) => setSent((list) => [...list, text])}>
          <ComposerAttach accept="image/*" />
          <ComposerInput aria-label="Ask the assistant" placeholder="Ask anything" />
          <ComposerDictate />
          <ComposerSend />
        </Composer>
        <ul className="flex flex-col gap-1 text-sm text-muted-foreground" aria-live="polite">
          {sent.map((line, index) => (
            <li key={index}>Sent: {line}</li>
          ))}
        </ul>
      </div>
    </TooltipProvider>
  );
}
```

## Variants
Not applicable: one arrangement for a message and for a question to an agent. What differs is which parts you put in it.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | nothing written and no files | write, attach | `data-state="idle"`; Send at half strength with "Write a message first" as its tooltip and description | test |
| composing | words or files | press Send or Enter | Send at full strength, its tooltip "Send" and the key | test |
| suggesting | an @ word, or a / word at the start, with a source for it | move with the arrows, pick with Enter, Tab or a press, close with Escape | the list over the box; the field `aria-expanded` with the highlighted row as `aria-activedescendant` | test |
| suggestions loading | an async source slower than 250ms | keep typing | a spinner row, or the rows already there dimmed | by hand |
| suggestions failed | an async source that rejected | pick the row to ask again | "Suggestions did not load. Try again" as the one row | by hand |
| attached | files chosen, pasted or dropped | remove one, send | a compact `FileTile` per file, 48px tall and as wide as its name up to 16rem: a picture as its own thumbnail or its kind's glyph, the name cut in its middle, the kind and size through `bytes()`, and Remove; past the box's width the row scrolls sideways and the edge with more past it fades, as a chip row's does (measured: the tray 48px plus its 6px, the composer 44 to 134px, the tiles 0px of movement while four files uploaded) | by hand |
| uploading | `upload` running for a file | wait, remove it | a spinner on the file; Send held with "Wait for the files to upload" | by hand |
| refused | a file of another kind or over `maxSize` | dismiss it | the file with its reason in the destructive colour; it is never sent | by hand |
| held | `disabled`, past `maxLength`, or a file that did not upload | read why | the reason in the field for `disabled`; Send held with the reason; the count in the destructive colour | test |
| pending | `onSend` returned a promise that has not settled | wait | `data-state="sending"`, the field read-only, Send busy with a spinner after 250ms in its own box | by hand |
| failure | that promise rejected | edit and send again | `data-state="failed"`; the draft stays, and `error` under the box, read as an alert | by hand |
| streaming | `streaming` | write the next message, press Stop | Send is Stop in the same box, its glyph a square | test |
| dictating, starting | Dictate pressed, the microphone not yet live | cancel with Escape or Cancel | Cancel in the tools' place, the waveform pill empty, Stop at half strength | by hand |
| dictating, listening | the microphone live | speak, press Stop, press Send, cancel | the waveform, a clear pill, filling from the right with the voice's loudness and tapering at its round ends, Stop at full strength, "Listening" read once | by hand |
| dictating, writing out | Stop or Send pressed | wait, cancel | Stop busy with a spinner in its own box, "Writing it out" read once; then the words where the caret was when the mic was pressed, in place of a selection, spaced only where they need it, and for Send, sent | test |
| microphone refused | the browser or the person refused it | allow it and press Dictate again | "Allow the microphone to dictate" under the box, read as an alert | by hand |
| open | words or files in the draft | keep writing | the field on its own row over the tools, `data-open` on the box, the corner a surface's | test |
| focus-visible | Tab into the field | write | the accent edge and soft ring on the whole box; a click shows only the caret | by hand |

Example: A send that waits on the server. The draft stays in the field, read only, and Send shows a spinner in its own box until the answer comes (`docs/system/examples/composer/state-pending.tsx`)

```tsx
import { useState } from "react";

import { Composer, ComposerInput, ComposerSend } from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

const accept = () => new Promise<void>((resolve) => setTimeout(resolve, 2000));

export default function Example() {
  const [sent, setSent] = useState<string | null>(null);
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col gap-2">
        <Composer
          onSend={({ text }) => accept().then(() => setSent(text))}
          defaultValue={{ text: "Please move my booking to Friday at 10 AM.", tokens: [] }}
        >
          <ComposerInput aria-label="Message the front desk" placeholder="Message the front desk" />
          <ComposerSend />
        </Composer>
        <p className="px-1 text-sm text-muted-foreground" aria-live="polite">
          {sent ? `Sent: ${sent}` : "Press Send. The server answers after 2 seconds."}
        </p>
      </div>
    </TooltipProvider>
  );
}
```

Example: A send that fails. The draft stays with the reason under the box, and sending again tries again; a line under the example says to press Send (`docs/system/examples/composer/state-failed.tsx`)

```tsx
import { Composer, ComposerInput, ComposerSend } from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

// The stand-in server fails the first try and accepts the next.
let tries = 0;
const deliver = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => (++tries % 2 === 1 ? reject(new Error("offline")) : resolve()), 1200),
  );

export default function Example() {
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col gap-2">
        <Composer onSend={deliver} defaultValue={{ text: "Can you send the invoice for March?", tokens: [] }}>
          <ComposerInput aria-label="Message James Whitaker" placeholder="Message James" />
          <ComposerSend />
        </Composer>
        <p className="px-1 text-sm text-muted-foreground">Press Send. The first try fails, and the next goes through.</p>
      </div>
    </TooltipProvider>
  );
}
```

Example: When it cannot send, it says why. A conversation that is closed says so in the field, and near the limit a count appears beside Send (`docs/system/examples/composer/state-held.tsx`)

```tsx
import { Composer, ComposerAttach, ComposerInput, ComposerSend } from "@/components/cobalt/ui/composer";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

const nearLimit = {
  text: "Thanks for booking the garden room for Thursday. Check-in opens at 2 PM, the code for the side gate is on your confirmation, and parking is free after 6 PM on the street behind the building.",
  tokens: [],
};

export default function Example() {
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col gap-6">
        <Composer onSend={() => undefined} disabled="Daniel left this conversation">
          <ComposerAttach />
          <ComposerInput aria-label="Message Daniel Okafor" placeholder="Message Daniel" />
          <ComposerSend />
        </Composer>
        <Composer onSend={() => undefined} maxLength={200} defaultValue={nearLimit}>
          <ComposerInput aria-label="Reply to the guest" placeholder="Reply to the guest" />
          <ComposerSend />
        </Composer>
      </div>
    </TooltipProvider>
  );
}
```

### State precedence
- Streaming and composing: streaming wins Send, which is Stop; the field stays open for the next message and Enter does not send.
- Pending and failure: Not applicable: the promise settles one way.
- Failure and composing: both show. The message stays under the box until the draft changes.
- Suggesting and composing: both show. The list floats over the box and nothing in the box moves.
- Held and composing: held wins Send. Its tooltip says the reason instead of "Send".
- Dictating and open: both show. The draft stays on its row and the waveform takes the foot; at rest the waveform takes the field's row.
- Dictating and held: dictating wins Send, which finishes the dictation and sends what it wrote, or says why it cannot once the words are in.
- Attached and idle: attached wins. Ready files alone can be sent; refused ones do not count.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| the first character or file opens the box, and clearing it closes it | input | `--t-settle` on an arc: opening, `--curve-arc-out` for the height that carries the tools down and `--curve-arc-in` for the field's slide; closing, the two swap, so whichever gives way is fast and whichever takes its place is slow, and the words never reach the tools | height, padding-inline, border-radius | at once |
| a line is added or removed, the tray appears or goes | input | `--t-settle`, the arc's half for the direction | height | at once |
| keyboard focus reaches the field | input | `--t-settle` | box-shadow | the same |
| a press on Send, a tool or a remove button | input | `pressable`, `--t-press` | box-shadow tint | the same |
| Send turns into Stop and back | input | `IconSwap`, `--t-icon` | opacity, filter | the same fade |
| Dictate is pressed | input | `animate-arrive` for the waveform, `IconSwap` for the mic into Stop, `--t-fade` for Stop from half to full strength once the microphone is live | opacity, transform | the waveform holds still between samples |
| the voice is heard | announce | one bar per 50ms sample from the right, gliding one bar's pitch between samples | canvas | steps a bar per sample, without the glide |
| the @ or / list opens | announce | `--t-pop` from `@starting-style` | opacity | the same fade |
| the rows dim while a slower source answers | announce | `--t-fade` | opacity | the same |

## Props

<!-- Props generated from registry/cobalt/ui/composer.tsx with TypeScript by scripts/props-table.mjs -->
### Composer

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `onSend` | `(draft: ComposerDraft) => void \| Promise<unknown>` |  |  |
| `commands?` | `ComposerSource` |  | Commands offered after / at the start of the message. |
| `defaultValue?` | `ComposerValue` |  | The draft to start from, such as one `useDraft` kept. |
| `disabled?` | `string` |  | Why nothing can be written here, such as "Maya left the conversation". |
| `error?` | `string` | `"Not sent. Check your connection and try again."` | Said under the field when a send that returned a promise fails. |
| `labels?` | `Partial<ComposerLabels>` |  |  |
| `maxLength?` | `number` |  | The most characters a message can hold, counted as `maxlength` counts them; a quiet count shows near it. |
| `mentions?` | `ComposerSource` |  | People, agents or files offered after |
| `onStop?` | `(() => void)` |  |  |
| `onValueChange?` | `((value: ComposerValue) => void)` |  |  |
| `sendKey?` | `"enter" \| "mod-enter"` | `"enter"` | Which key sends: Enter, or Command or Control and Enter. |
| `streaming?` | `boolean` | `false` | A reply is on its way: Send becomes Stop. |

Also accepts every native `<form>` attribute.

### ComposerAttach

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `accept?` | `string` | `""` | The kinds of file it takes, as a file input reads them: "image/*,.pdf". |
| `label?` | `string` | `"Attach files"` |  |
| `maxSize?` | `number` |  | The largest file it takes, in bytes. |
| `refusedKind?` | `string` | `"Not accepted here"` |  |
| `refusedSize?` | `(max: number) => string` | `(max) => `Over ${bytes(max)}`` |  |
| `upload?` | `ComposerUpload` |  |  |

### ComposerAttachments

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `failedLabel?` | `string` | `fileTileLabels.failed` |  |
| `removeLabel?` | `(name: string) => string` | `fileTileLabels.remove` |  |
| `retryLabel?` | `(name: string) => string` | `fileTileLabels.retry` |  |
| `uploadingLabel?` | `string` | `"Uploading"` |  |

### ComposerDictate

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `cancelLabel?` | `string` | `"Cancel dictation"` |  |
| `failedLabel?` | `string` | `"Not written out. Try again"` | Said under the box when the words could not be written out. |
| `label?` | `string` | `"Dictate"` |  |
| `listeningLabel?` | `string` | `"Listening"` |  |
| `pendingLabel?` | `string` | `"Writing it out"` |  |
| `refusedLabel?` | `string` | `"Allow the microphone to dictate"` | Said under the box when the microphone is refused. |
| `stopLabel?` | `string` | `"Stop dictating"` |  |
| `transcribe?` | `ComposerTranscribe` |  |  |

### ComposerInput

No props of its own.

Also accepts every native `<textarea>` attribute.

### ComposerSend

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `emptyLabel?` | `string` | `"Write a message first"` | Why it is held off while there is nothing to send. |
| `label?` | `string` | `"Send"` |  |
| `pendingLabel?` | `string` | `"Sending"` |  |
| `stopLabel?` | `string` | `"Stop"` |  |

The tray, the field and the foot each hold their child's height through `useFollowHeight` from `registry/cobalt/lib/follow-height.ts`, the hook FieldError and InviteField share, so every change of height runs on the settle transition. The placeholder is drawn over the field on one line that ends in an ellipsis when it is cut, since a textarea's own placeholder ignores `text-overflow`; the native one stays, transparent, for a screen reader. `enterKeyHint` reads the pointer after mount, so the server and the first render agree on "send" and a touch screen then takes "enter". Put the parts inside in any order; the composer sorts them: `ComposerAttachments` on top, `ComposerInput` next, `ComposerSend` at the end of the foot, and anything else, such as `ComposerAttach`, at its start.

`onSend` gets `{ text, mentions, command, segments, files }`; return nothing to clear at once, or a promise to wait. `streaming` turns Send into Stop, which calls `onStop`. `mentions` and `commands` take a list of items, each `{ id, label, group, description, icon }`, or `(query, signal) => Promise<items>`. `maxLength` sets the limit and its count. `sendKey` picks `enter` or `mod-enter`. `disabled` is the reason nothing can be written. `defaultValue` and `onValueChange` hold `{ text, tokens }`, which `useDraft(key)` fills from this browser. `error` is said under the box when a send fails. `labels` holds the list's and the reasons' words.

`ComposerAttach` takes `accept`, `maxSize`, `upload`, `label`, `refusedKind` and `refusedSize`; its presence lets the composer take files. `upload(file, { signal, progress })` runs as each file is added; call `progress` with 0 to 100 and its glyph fills. `ComposerInput` passes every textarea attribute, such as `aria-label` and `placeholder`. `ComposerSend` takes `label`, `stopLabel`, `emptyLabel` and `pendingLabel`. `ComposerAttachments` takes `removeLabel`, `retryLabel`, `uploadingLabel` and `failedLabel`.

`ComposerDictate` goes beside Send, and the composer sorts it there. `transcribe(audio, { signal })` gets the recording and returns the words, for a host with its own speech to text; without it the browser's own recognition writes them, on the device where the browser has the language's model and otherwise through the browser's own service, and where a browser has neither, or no microphone, the button is not drawn. While it runs it hands the composer Cancel and a waveform through the context, and Send finishes it. It takes `label`, `stopLabel`, `cancelLabel`, `pendingLabel`, `listeningLabel`, `refusedLabel` and `failedLabel`.

## Usage

### When to use
- Writing the next message in a `Thread`.
- Asking an agent a question that can name people, agents and files, run a command, and stream its answer.

### When not to use
- A one-line search or filter. Use Input instead, or CommandPalette.
- A long form field such as a description. Use Textarea instead, inside a Field.

### Rules
- `rule/composer-send-at-once`: When the thread shows its own sending state, return nothing from `onSend` and append the message as pending, instead of awaiting the request in the composer, because the person can write the next message while the last one travels, and its status lives on its bubble. Evidence: person D39; principle heuristic: visibility of system status, the result shows where the message is. Check: review of every `onSend` beside a `Thread`.
  - Don't: `onSend={async (draft) => { await api.send(draft); setPosts(...) }}` beside a thread
  - Do: `onSend={(draft) => { append(draft, "pending"); deliver(id) }}`
- `rule/composer-name-the-field`: When placing a composer, name its field with `aria-label` or a `Field` label that says who it goes to, such as "Message Maya Chen", because a placeholder is gone once you type and a screen reader may never read it. Evidence: person D34; principle wcag: 3.3.2 Labels or instructions. Check: test `composer.test.tsx` and review of every `ComposerInput`.
  - Don't: `<ComposerInput placeholder="Type a message" />`
  - Do: `<ComposerInput aria-label="Message Maya Chen" placeholder="Message Maya" />`
- `rule/composer-stop-in-place`: When an agent's answer streams, pass `streaming` and `onStop` to the composer instead of drawing a Stop button somewhere else, because the press that started the answer is where the person reaches to end it, and Send cannot fire a second question meanwhile. Evidence: principle heuristic: user control and freedom, the person can end what they started from where they started it. Check: test `composer.test.tsx` checks Stop replaces Send while streaming.
  - Don't: `<Button onClick={stop}>Stop</Button>` above the composer
  - Do: `<Composer streaming={streaming} onStop={stop}>`

### Content
- Follows `rule/writing-placeholder-not-label`.
- `rule/composer-placeholder-names-person`: When writing the placeholder, use "Message" and the person's first name, in at most 3 words, instead of "Type a message", because it confirms who reads it at the moment of writing. Evidence: principle heuristic: match between the system and the real world. Check: review.
  - Don't: `placeholder="Type your message here..."`
  - Do: `placeholder="Message Maya"`

### Anti-slop
- `rule/composer-no-disabled-send`: When there is nothing to send, leave `ComposerSend` as it is, held off with `aria-disabled` and its reason, instead of a native `disabled` button, because a disabled button takes no focus and no hover, so its reason is never found. Evidence: principle wcag: 4.1.2 Name, role, value. Check: test `composer.test.tsx` checks Send carries `aria-disabled` and no `disabled` attribute.
  - Don't: `<Button type="submit" disabled={!text}>Send</Button>`
  - Do: `<ComposerSend />`
- `rule/composer-one-line-at-rest`: When placing the field, leave it one line tall at rest, 32px at every width, instead of giving it rows or a minimum height, because an empty box several lines tall reads as dead space and pushes the conversation up for nothing; it grows as the words arrive. Evidence: measured 32px fields in 44px boxes at rest, and 80px boxes open on one line, in docs/system/examples/composer at 1440 and 390, where the earlier prompt field was 56px with no words in it. Check: test `composer.test.tsx` checks one row and no minimum height.
  - Don't: `<ComposerInput rows={3} className="min-h-24" />`
  - Do: `<ComposerInput aria-label="Ask the research assistant" />`

### Limits
- `rule/composer-ten-lines`: When a draft runs past 240px, about 10 lines, let the field scroll inside its box instead of growing past it, because a taller composer pushes the thread above it out of view. Evidence: measured 10 lines of 20px text at `max-h-60` in docs/system/stress/composer.tsx at 1440. Check: probe in docs/system/stress/composer.tsx.
  - Don't: `<ComposerInput className="max-h-none" />`
  - Do: `<ComposerInput />`

## Accessibility
Rests on a native `form`, a `textarea` through Base UI `Field.Control`, and native buttons and file input. With a source for @ or /, the field is a combobox on the WAI-ARIA pattern: the focus stays in it and the highlighted row is its active descendant.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Enter | the field, with a fine pointer | sends; with `sendKey="mod-enter"` it starts a line | stays in the field, now empty | by hand |
| Shift+Enter | the field | starts a new line | stays in the field | by hand |
| Command+Enter or Control+Enter | the field | sends, on any device | stays in the field | by hand |
| Enter | the field, during an input method's composition | confirms the composition, never sends or picks | stays in the field | by hand |
| @ | the field, after a space or at the start | opens the mention list | stays in the field | by hand |
| / | the field, as the first character | opens the command list | stays in the field | by hand |
| Arrow Down and Arrow Up | the field, a list open | moves the highlight, wrapping | stays in the field | by hand |
| Enter or Tab | the field, a list open | picks the highlighted row: a token and a space go in place of the typed word | stays in the field, after the space | by hand |
| Escape | the field, a list open | closes it for that word | stays in the field | by hand |
| Backspace or Delete | the field, beside a token | removes the whole token; Undo brings it back | stays in the field | by hand |
| Arrow Left and Arrow Right | the field, beside a token | steps over the token to its other edge | stays in the field | by hand |
| Tab | the field, no list open | moves to Send; Shift+Tab to the tools before the field | the next button | by hand |
| Enter or Space | Attach | opens the file chooser | back to the field once files are chosen | by hand |
| Enter or Space | Stop | ends the answer | the field | by hand |
| Enter or Space | Dictate | opens the microphone; pressed again as Stop, writes the words in | stays on the button, then the field once the words are in | by hand |
| Escape | anywhere, while dictating | throws the dictation away | the field | by hand |
| Enter or Space | Remove on a file, or a failed file's glyph | removes it, or uploads it again | the field after Remove | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| composer | form | none | `aria-describedby` the error while it shows; `data-state` the phase | nothing | test |
| field | textbox, multi-line; combobox with a source | `aria-label`, or the `Field` label | `readonly` while a send waits; `disabled` with the reason as its placeholder; `aria-expanded`, `aria-controls`, `aria-activedescendant` with a source; `aria-describedby` the count with `maxLength` | its name and contents; a token reads as its words | test |
| list | listbox, its rows grouped | "Mention" or "Commands" | `aria-busy` while a source answers; each row an option with `aria-selected` | the highlighted row as it moves | by hand |
| list status | status | its text | visually hidden | "5 suggestions", "Nothing matches", or the failure, once | by hand |
| Send | button | `label`, "Send"; "Stop" while streaming | `aria-disabled` while held or waiting, `aria-busy` while waiting, `aria-describedby` the reason while held | "Send, dimmed, Write a message first" | test |
| Attach | button | its label | none | its name | test |
| file uploading | progressbar, the file's glyph | "Uploading" and the file's name | `aria-valuenow` while the upload reports its share | "Uploading notes.pdf, 40 percent" | by hand |
| Remove, Retry | button | the action and the file's name | none | "Remove passport.pdf, button" | by hand |
| Dictate | button | `label`, "Dictate"; `stopLabel`, "Stop dictating", while it runs | `aria-busy` and `aria-disabled` while the words are written out | "Dictate, button" | by hand |
| Cancel | button | `cancelLabel`, "Cancel dictation" | none | its name | by hand |
| waveform | none | none | `aria-hidden` | nothing; a polite live region says "Listening", then "Writing it out" | by hand |
| error | alert | its text | none | the error, once, when a send fails or a dictation cannot start | by hand |

## Tokens
| Part | State | Token |
|---|---|---|
| box | rest | `--input` at half, `--r-composer`, `--pad-composer`, `--control-sm` for its one row |
| box | open | `--r-2xl`, `--t-settle`, `--curve`, `--curve-in-out` |
| box | focus-visible | `--primary` edge and its 20 percent ring |
| box | a file dragged over | `--primary` inset edge |
| field | all | `--muted-foreground` for the placeholder, 16px text below 768px |
| token | in the text | `--primary` at 12 percent behind its words, `--r-xs` |
| list | open | `--popover`, `--r-3xl`, `--elev-floating`, `--pad-popup`; rows `--r-lg`, `--accent` when highlighted |
| Send, Stop | all | `--primary`, `--primary-foreground`, `--control-sm`, `--r-control` |
| files | attached | `--r-lg`, `--card`, `--outline-image`, the `--file-*` colours through `FileTypeIcon`; `--destructive` for a refusal |
| count, error | near or past the limit, failure | `--muted-foreground`, `--destructive` |

## Related
- Thread: the conversation the composer writes into.
- Combobox: one value picked from a list in a form field, where the composer's @ list names things inside a message.
- Textarea: a long field in a form, with no send.
- ImageField: a picture to upload, crop, replace or remove, such as an avatar or a cover.
