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

## Description
Shows one message in a conversation, from a person or from an assistant: what was said, the pictures and files sent with it, how people reacted, where it sits among the messages around it, and whether yours arrived.

`import { Message, MessageActions, MessageAnswer, MessageAside, MessageBubble, MessageContent, MessageDeleted, MessageFooter, MessageQuote, MessageStatus, MessageText, MessageThinking, MessageTime } from "@/components/cobalt/ui/message"`, source `registry/cobalt/ui/message.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/color-only-status`, `trap/link-cue`, `trap/hover-unguarded`, `trap/touch-hover-flash`, `trap/loading-label-swap`, `trap/loading-layout-shift`, `trap/toast-errors`, `trap/text-measure`, `trap/weight-shift`, `trap/reduced-motion-ignored`, `trap/motion-frequent`, `trap/live-region-double`, `trap/illustration-announced`, `trap/numbers-shift`, `trap/button-icon-name`.

The pictures, files and reactions inside a message are on this page too: `import { MessageFile, MessageImages } from "@/components/cobalt/ui/message-attachment"` (source `registry/cobalt/ui/message-attachment.tsx`) and `import { Reaction, ReactionAdd, Reactions } from "@/components/cobalt/ui/reactions"` (source `registry/cobalt/ui/reactions.tsx`). They live inside `MessageContent` and take their side's look from `Message`. `MessageFile` is a `FileTile` (`registry/cobalt/ui/file-tile.tsx`) in its `bubble` variant, the tile a composer and a drop list use too, in the bubble's fill and the run's corners, so its name is cut in the middle with the extension kept and its size is written by `bytes()`, "812 KB". Below 640px a message that carries a file takes the whole line instead of four fifths of it, so the tile has room for its name (measured at 390: "Q3 holdings by sector.xlsx" whole in a 288px tile, where a 248px column cut it). A file's glyph is `FileTypeIcon` (`registry/cobalt/ui/file-type-icon.tsx`), Tag's file glyph ported: a sheet in its kind's `--file-*` colour with a white mark, which draws its own upload. Their upload and delivery rules are pure functions in `registry/cobalt/lib/messages.ts`: `nextUpload`, `nextDelivery` and `nextReply`.

`trap/color-only-status` is answered by the words "Sending", "Sent", "Read" and "Not sent", "Upload failed" with the retry arrow in place of the file's mark, a file's kind in words beside its coloured glyph, and `aria-pressed` on your reaction (States, ARIA). `trap/link-cue` by the underline every address keeps at rest (Tokens). `trap/hover-unguarded` and `trap/touch-hover-flash` by `MessageAside`, which shows on hover only under `(hover: hover)`, also on focus inside the message, and is not drawn under a coarse pointer, where a `ContextMenu` carries the same actions (Rules). `trap/loading-label-swap` and `trap/loading-layout-shift` by the status line, which holds its line while "Sending" waits 250ms, by the file block, 56px in every upload state, and by thinking and the trace's summary sharing one 32px line (States). `trap/toast-errors` by a failure staying on its message, and on the file or picture that failed (Rules). `trap/text-measure` by the bubble's 28rem ceiling and the answer's 32rem (Limits). `trap/weight-shift` by every state keeping its weight. `trap/reduced-motion-ignored` and `trap/motion-frequent` by the arrival, a 4px rise only for a message that came while the thread was open, and the caret and dots holding still under reduced motion (Motion). `trap/live-region-double` by `aria-busy` on an answer while it streams, so the thread's log reads it once. `trap/illustration-announced` by every picture's `alt`. `trap/numbers-shift` by tabular figures on sizes, percentages and counts. `trap/button-icon-name` by every icon button's name: Retry uploading and the file's name, Copy answer, Add reaction.

### Foundation
Not applicable: hand-rolled, with Base UI `Toggle` under each reaction.

| Given by the foundation | Added by the team |
|---|---|
| Not applicable: hand-rolled from Tag's message, bubble runs, send status, media and file cards (`/Users/kaanaricioglu/tag/src/owner-ui/Message.svelte`, `bubble-runs.ts`, `SendStatus.svelte`, `MessageMedia.svelte`); Base UI `Toggle` for a reaction's `aria-pressed` | Two looks for people, yours in `--bubble-mine` and theirs in `--bubble`; an agent's message with no bubble, its answer as prose in a 32rem column, a caret while it streams, a thinking line and Copy, Retry and a rating under it; corners from the run position, eased on `--t-settle`; a quote at the concentric `--r-bubble-inner`; the time and actions in a side slot centred on the message body, with reactions and delivery in a separate row that keeps its room; the delivery line with Retry; a deleted placeholder. Pictures in a fixed grid that open in the `Lightbox`; files with Tag's glyph in their kind's colour; uploads drawn on what uploads, the file's colour rising inside its sheet and a ring over the photo, with Retry in their place when they fail; reactions as 28px toggles that wrap. Dropped from Tag: the agent-only blocks (offers, connector cards, provenance footers), "Send as new", the 15-second resend hold, and the in-bubble picture strip |

## Examples
A host's two messages in one run and your answer under them, read.

Real uses, 0 call sites (`rg -n "<Message\b" app registry --glob '!registry/cobalt/ui/*'`): the thread's examples render it, `docs/system/examples/thread/in-product.tsx` and `docs/system/examples/thread/in-assistant.tsx`.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/message/default.tsx` | default | Two people about a booking: theirs on the grey at the start, yours in ink at the end, a run's bubbles 2px apart |
| `docs/system/examples/message/default.tsx` | mine=false | Theirs, on the grey at the start of the line |
| `docs/system/examples/message/default.tsx` | mine=true | Yours, in ink at the end of the line |
| `docs/system/examples/message/default.tsx` | agent=false | A person's message, in a bubble |
| `docs/system/examples/message/agent.tsx` | agent=true | An assistant's reply in a research tool: no bubble, prose in its column, its trace closed above and Copy, Retry and a rating under it |
| `docs/system/examples/message/position-runs.tsx` | position=single | A message alone, every corner round |
| `docs/system/examples/message/position-runs.tsx` | position=first | The first of a run, its bottom corner on the sender's side tight |
| `docs/system/examples/message/position-runs.tsx` | position=middle | A middle message, both corners on the sender's side tight |
| `docs/system/examples/message/position-runs.tsx` | position=last | The last of a run, its top corner on the sender's side tight |
| `docs/system/examples/message/position-runs.tsx` | matrix:mine,position | Runs of one, two and three from each side |
| `docs/system/examples/message/state-streaming.tsx` | state:streaming | A reply as it is made: Thinking, the trace while it reads, the words with a caret, then Copy and Retry; Stop keeps what it said |
| `docs/system/examples/message/state-pictures.tsx` | state:pictures | A venue sends pictures: one keeps its own shape, four or more fill a square with a count of the rest; press any to open them all in the lightbox |
| `docs/system/examples/message/state-files.tsx` | state:files | Files as they arrive: Tag's glyph in each kind's colour, the extension kept when the name is cut, the kind and size, the block a link that downloads it |
| `docs/system/examples/message/state-upload.tsx` | state:uploading | Uploads drawn on what is uploading: the file's colour rising in its sheet, a ring over the photo; Retry in the place of the two that lose the network |
| `docs/system/examples/message/state-delivery.tsx` | state:failed | Read, and one not sent, kept with Retry; Retry sends it again |
| `docs/system/examples/message/state-reactions.tsx` | state:reactions | Reactions under a message: yours in ink, press one to take it back or add to it, and Add reaction for any other emoji |
| `docs/system/examples/message/state-quote.tsx` | state:quote | A reply with what it answers at the top of its bubble |
| `docs/system/examples/message/state-deleted.tsx` | state:deleted | A message taken back keeps its place as an outline that says so |
| `docs/system/examples/message/state-wrapping.tsx` | state:wrapping | A long address, a word with no break, emoji alone and line breaks |
| `docs/system/examples/message/in-context-menu.tsx` | composition:ContextMenu | Hover for the time and Add reaction; right click or long press for the same actions on a touch screen |

Example: Two people about a booking: theirs on the grey at the start, yours in ink at the end, a run's bubbles 2px apart (`docs/system/examples/message/default.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageBubble>Your room at Fjordstova is ready for Sunday.</MessageBubble>
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>Check-in is from 3 PM. You can leave your bags with us before then.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Thank you. We land at 8:40, so we will come by around 10.</MessageBubble>
          <MessageFooter>
            <MessageStatus status="read" />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: Runs of one, two and three from each side (`docs/system/examples/message/position-runs.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import type { RunPosition } from "@/lib/cobalt/messages";

const runs: { mine: boolean; texts: string[] }[] = [
  { mine: false, texts: ["The filing is in."] },
  { mine: true, texts: ["Which form?", "The 13F or the amendment?"] },
  { mine: false, texts: ["The 13F-HR for Q3.", "192 positions, up from 181.", "I put the new ones in the sheet."] },
  { mine: true, texts: ["Thanks, reading it now."] },
];

const place = (index: number, count: number): RunPosition =>
  count === 1 ? "single" : index === 0 ? "first" : index === count - 1 ? "last" : "middle";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {runs.flatMap((run, r) =>
        run.texts.map((text, i) => (
          <Message key={`${r}-${i}`} mine={run.mine} position={place(i, run.texts.length)}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
            </MessageContent>
          </Message>
        )),
      )}
    </div>
  );
}
```

Example: Hover for the time and Add reaction; right click or long press for the same actions on a touch screen (`docs/system/examples/message/in-context-menu.tsx`)

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

import { AddReactionIcon, CopyIcon } from "@/components/cobalt/icon";
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
} from "@/components/cobalt/ui/context-menu";
import { EmojiPickerPopover } from "@/components/cobalt/ui/emoji-picker";
import { IconButton } from "@/components/cobalt/ui/icon-button";
import { Message, MessageAside, MessageBubble, MessageContent, MessageTime } from "@/components/cobalt/ui/message";
import { Reaction, Reactions } from "@/components/cobalt/ui/reactions";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

// Emoji are written as escapes: the system's emoji ban scans source text.
const THUMBS = "\u{1F44D}";
const text = "The fee table is on page 12, under Schedule B.";

export default function Example() {
  const [reaction, setReaction] = useState<string | null>(null);
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col">
        <ContextMenu>
          <ContextMenuTrigger className="select-text" render={<Message author="Daniel Okafor" />}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
              {reaction && (
                <Reactions>
                  <Reaction emoji={reaction} count={1} pressed onPressedChange={() => setReaction(null)} names="You" />
                </Reactions>
              )}
            </MessageContent>
            <MessageAside>
              <MessageTime value="2026-10-17T14:05:00Z" timeZone="UTC" />
              <EmojiPickerPopover
                onPick={setReaction}
                trigger={<IconButton size="icon-sm" icon={<AddReactionIcon />} label="Add reaction" />}
              />
            </MessageAside>
          </ContextMenuTrigger>
          <ContextMenuContent label="Message actions">
            <ContextMenuItem onClick={() => setReaction(THUMBS)}>
              <AddReactionIcon aria-hidden="true" />
              React with a thumbs up
            </ContextMenuItem>
            <ContextMenuItem onClick={() => void navigator.clipboard?.writeText(text)}>
              <CopyIcon aria-hidden="true" />
              Copy text
            </ContextMenuItem>
          </ContextMenuContent>
        </ContextMenu>
      </div>
    </TooltipProvider>
  );
}
```

## Variants

### mine
- `false`: a message someone else sent: the grey `--bubble` at the start of the line. The default. Used at 0 call sites.
- `true`: a message you sent: the ink `--bubble-mine` at the end of the line. Used at 0 call sites.

Example: Theirs, on the grey at the start of the line (`docs/system/examples/message/default.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageBubble>Your room at Fjordstova is ready for Sunday.</MessageBubble>
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>Check-in is from 3 PM. You can leave your bags with us before then.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Thank you. We land at 8:40, so we will come by around 10.</MessageBubble>
          <MessageFooter>
            <MessageStatus status="read" />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: Yours, in ink at the end of the line (`docs/system/examples/message/default.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageBubble>Your room at Fjordstova is ready for Sunday.</MessageBubble>
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>Check-in is from 3 PM. You can leave your bags with us before then.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Thank you. We land at 8:40, so we will come by around 10.</MessageBubble>
          <MessageFooter>
            <MessageStatus status="read" />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

### agent
- `false`: a person's message, in bubbles. The default. Used at 0 call sites.
- `true`: an assistant's reply: no bubble, 20px above it, its column 32rem wide, holding a `Trace`, a `MessageAnswer` and `MessageActions`. Used at 0 call sites.

Example: A person's message, in a bubble (`docs/system/examples/message/default.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageBubble>Your room at Fjordstova is ready for Sunday.</MessageBubble>
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>Check-in is from 3 PM. You can leave your bags with us before then.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Thank you. We land at 8:40, so we will come by around 10.</MessageBubble>
          <MessageFooter>
            <MessageStatus status="read" />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: An assistant's reply in a research tool: no bubble, prose in its column, its trace closed above and Copy, Retry and a rating under it (`docs/system/examples/message/agent.tsx`)

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

import { RetryIcon, ThumbsDownIcon, ThumbsUpIcon } from "@/components/cobalt/icon";
import { CopyButton } from "@/components/cobalt/ui/copy-button";
import { IconButton } from "@/components/cobalt/ui/icon-button";
import { Message, MessageActions, MessageAnswer, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";
import { Trace, TraceStep } from "@/components/cobalt/ui/trace";

const answer =
  "Meridian Growth Partners IV closed at $1.5B on Nov 14, two weeks later than its first notice said. The amended Form D/A lists $640M sold by Oct 31, so the last six weeks brought in more than half of the fund.\n\nThe fee terms did not change: 2% for three years, then 1.5% of invested capital.";

export default function Example() {
  const [rating, setRating] = useState<"good" | "bad" | null>(null);
  const rate = (value: "good" | "bad") => setRating((current) => (current === value ? null : value));
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-2xl flex-col">
        <Message mine>
          <MessageContent>
            <MessageBubble>When did Meridian IV close, and at what size?</MessageBubble>
          </MessageContent>
        </Message>
        <Message agent author="Research assistant">
          <MessageContent>
            <Trace summary="Read 2 filings" duration="3.4 s">
              <TraceStep status="done" title="Read the Form D/A of Nov 15" duration="1.9 s" />
              <TraceStep status="done" title="Read the Form D of Aug 2" duration="1.5 s" />
            </Trace>
            <MessageAnswer>{answer}</MessageAnswer>
            <MessageActions>
              <CopyButton value={answer} size="icon-sm" label="Copy answer" />
              <IconButton size="icon-sm" icon={<RetryIcon />} label="Retry" />
              <IconButton
                size="icon-sm"
                icon={<ThumbsUpIcon />}
                label="Good answer"
                aria-pressed={rating === "good"}
                onClick={() => rate("good")}
                className="aria-pressed:text-foreground aria-pressed:[&_svg]:fill-current"
              />
              <IconButton
                size="icon-sm"
                icon={<ThumbsDownIcon />}
                label="Bad answer"
                aria-pressed={rating === "bad"}
                onClick={() => rate("bad")}
                className="aria-pressed:text-foreground aria-pressed:[&_svg]:fill-current"
              />
            </MessageActions>
          </MessageContent>
        </Message>
      </div>
    </TooltipProvider>
  );
}
```

### position
- `single`: a message with no other from the same person beside it, every corner round. The default. Used at 0 call sites.
- `first`: the first of a run, its bottom corner on the sender's side at `--r-bubble-joined`. Used at 0 call sites.
- `middle`: between two of a run, both corners on the sender's side tight. Used at 0 call sites.
- `last`: the last of a run, its top corner on the sender's side tight. Used at 0 call sites.

Example: A message alone, every corner round (`docs/system/examples/message/position-runs.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import type { RunPosition } from "@/lib/cobalt/messages";

const runs: { mine: boolean; texts: string[] }[] = [
  { mine: false, texts: ["The filing is in."] },
  { mine: true, texts: ["Which form?", "The 13F or the amendment?"] },
  { mine: false, texts: ["The 13F-HR for Q3.", "192 positions, up from 181.", "I put the new ones in the sheet."] },
  { mine: true, texts: ["Thanks, reading it now."] },
];

const place = (index: number, count: number): RunPosition =>
  count === 1 ? "single" : index === 0 ? "first" : index === count - 1 ? "last" : "middle";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {runs.flatMap((run, r) =>
        run.texts.map((text, i) => (
          <Message key={`${r}-${i}`} mine={run.mine} position={place(i, run.texts.length)}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
            </MessageContent>
          </Message>
        )),
      )}
    </div>
  );
}
```

Example: The first of a run, its bottom corner on the sender's side tight (`docs/system/examples/message/position-runs.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import type { RunPosition } from "@/lib/cobalt/messages";

const runs: { mine: boolean; texts: string[] }[] = [
  { mine: false, texts: ["The filing is in."] },
  { mine: true, texts: ["Which form?", "The 13F or the amendment?"] },
  { mine: false, texts: ["The 13F-HR for Q3.", "192 positions, up from 181.", "I put the new ones in the sheet."] },
  { mine: true, texts: ["Thanks, reading it now."] },
];

const place = (index: number, count: number): RunPosition =>
  count === 1 ? "single" : index === 0 ? "first" : index === count - 1 ? "last" : "middle";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {runs.flatMap((run, r) =>
        run.texts.map((text, i) => (
          <Message key={`${r}-${i}`} mine={run.mine} position={place(i, run.texts.length)}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
            </MessageContent>
          </Message>
        )),
      )}
    </div>
  );
}
```

Example: A middle message, both corners on the sender's side tight (`docs/system/examples/message/position-runs.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import type { RunPosition } from "@/lib/cobalt/messages";

const runs: { mine: boolean; texts: string[] }[] = [
  { mine: false, texts: ["The filing is in."] },
  { mine: true, texts: ["Which form?", "The 13F or the amendment?"] },
  { mine: false, texts: ["The 13F-HR for Q3.", "192 positions, up from 181.", "I put the new ones in the sheet."] },
  { mine: true, texts: ["Thanks, reading it now."] },
];

const place = (index: number, count: number): RunPosition =>
  count === 1 ? "single" : index === 0 ? "first" : index === count - 1 ? "last" : "middle";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {runs.flatMap((run, r) =>
        run.texts.map((text, i) => (
          <Message key={`${r}-${i}`} mine={run.mine} position={place(i, run.texts.length)}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
            </MessageContent>
          </Message>
        )),
      )}
    </div>
  );
}
```

Example: The last of a run, its top corner on the sender's side tight (`docs/system/examples/message/position-runs.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import type { RunPosition } from "@/lib/cobalt/messages";

const runs: { mine: boolean; texts: string[] }[] = [
  { mine: false, texts: ["The filing is in."] },
  { mine: true, texts: ["Which form?", "The 13F or the amendment?"] },
  { mine: false, texts: ["The 13F-HR for Q3.", "192 positions, up from 181.", "I put the new ones in the sheet."] },
  { mine: true, texts: ["Thanks, reading it now."] },
];

const place = (index: number, count: number): RunPosition =>
  count === 1 ? "single" : index === 0 ? "first" : index === count - 1 ? "last" : "middle";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {runs.flatMap((run, r) =>
        run.texts.map((text, i) => (
          <Message key={`${r}-${i}`} mine={run.mine} position={place(i, run.texts.length)}>
            <MessageContent>
              <MessageBubble>{text}</MessageBubble>
            </MessageContent>
          </Message>
        )),
      )}
    </div>
  );
}
```

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | rendered | read it, select its words, open its links | its words in a bubble on its side | test |
| hover | pointer over the message, under `(hover: hover)` | reach its time and actions | `MessageAside` fades in beside it with the time and its buttons | by hand |
| focus-within | Tab onto a link or button inside it | the same as hover | `MessageAside` shows, and the focused part's outline | by hand |
| pending | your message is on its way, `status="pending"` | wait, keep writing | "Sending" after 250ms, its line held from the start | test |
| sent | the server took it, `status="sent"` | nothing more | "Sent" under it | test |
| read | they opened it, `status="read"` | nothing more | "Read" under it | test |
| failed | the send failed, `status="failed"` | press Retry | "Not sent" and a Retry button under it, until it is sent or removed | test |
| thinking | an agent's reply before its first word, `MessageThinking` | wait, or Stop in the composer | "Thinking" with three dots in the 16px slot a trace's mark takes | test |
| streaming | `MessageAnswer streaming` | read as it comes, Stop | the words grow with a caret after the last one; `aria-busy` | test |
| stopped | the person stopped the reply | Retry | what it said so far, and "Stopped" under it | screenshot |
| pictures | `MessageImages` | press one to open the lightbox at it | the grid; "2 more" on the fourth when there are six | test |
| uploading | a file's or picture's `upload` is uploading | wait | the file's sheet grey with its colour rising from the bottom, or a ring over the photo on a slight shade; "Uploading, 42%" | test |
| upload failed | `upload` is failed | press Retry | the sheet stays grey, its mark becomes the retry arrow and the glyph the Retry button, "Upload failed"; a photo shows Retry over it and does not open | test |
| file ready | `MessageFile` with `href` and no upload | download it | the whole block is a link, a download glyph at its end | test |
| reactions | `Reactions` under the bubble | press one to add or take back yours, Add reaction | one chip per emoji with its count; yours in ink and "pressed" | test |
| quote | it answers another message | press the quote to go to that message | the quoted author and two lines in a tinted block at the top of the bubble | test |
| deleted | it was taken back | nothing | "This message was deleted" in an outline with no fill | test |
| wrapping | long words, another script, emoji alone or line breaks | read it | a long address or word breaks anywhere inside the bubble, each paragraph takes its own direction through `dir="auto"`, one to three emoji are 36px with no fill | screenshot |
| arrived | it came while the thread was open | read it | it rises 4px as it fades in, once | by hand |

Example: A reply as it is made: Thinking, the trace while it reads, the words with a caret, then Copy and Retry; Stop keeps what it said (`docs/system/examples/message/state-streaming.tsx`)

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

import { RetryIcon, StopIcon } from "@/components/cobalt/icon";
import { Button } from "@/components/cobalt/ui/button";
import { CopyButton } from "@/components/cobalt/ui/copy-button";
import { IconButton } from "@/components/cobalt/ui/icon-button";
import {
  Message,
  MessageActions,
  MessageAnswer,
  MessageBubble,
  MessageContent,
  MessageFooter,
  MessageThinking,
} from "@/components/cobalt/ui/message";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";
import { Trace, TraceStep, type TraceStatus } from "@/components/cobalt/ui/trace";
import { nextReply, type Reply, type ReplyEvent } from "@/lib/cobalt/messages";

const ANSWER =
  "Harbour Street added eleven positions in Q3, most of them short-dated Treasuries, and sold two regional banks outright. The book is 6% smaller by value, at $48.2B.";

type Step = { title: string; status: TraceStatus; duration?: string };

// The stand-in agent: what it does, and when, in milliseconds from the question.
const plan: { at: number; steps?: Step[]; event?: ReplyEvent }[] = [
  { at: 900, steps: [{ title: "Searching EDGAR", status: "running" }] },
  {
    at: 1900,
    steps: [
      { title: "Searched EDGAR", status: "done", duration: "1.0 s" },
      { title: "Reading the Q3 13F-HR", status: "running" },
    ],
  },
  {
    at: 3300,
    steps: [
      { title: "Searched EDGAR", status: "done", duration: "1.0 s" },
      { title: "Read the Q3 13F-HR", status: "done", duration: "1.4 s" },
    ],
  },
  ...ANSWER.split(/(?<= )/).map((word, index) => ({ at: 3400 + index * 55, event: { type: "words", text: word } as const })),
  { at: 3400 + ANSWER.split(" ").length * 55, event: { type: "finish" } },
];

export default function Example() {
  const [run, setRun] = useState(0);
  const [reply, setReply] = useState<Reply>({ status: "thinking" });
  const [steps, setSteps] = useState<Step[]>([]);

  useEffect(() => {
    setReply({ status: "thinking" });
    setSteps([]);
    const timers = plan.map(({ at, steps: next, event }) =>
      setTimeout(() => {
        if (next) setSteps(next);
        if (event) setReply((current) => nextReply(current, event));
      }, at),
    );
    return () => timers.forEach(clearTimeout);
  }, [run]);

  const working = reply.status === "thinking" || reply.status === "streaming";
  const text = reply.status === "thinking" ? "" : reply.text;
  const running = steps.find((step) => step.status === "running");
  const stop = () => setReply((current) => nextReply(current, { type: "stop" }));
  const again = () => setRun((count) => count + 1);

  return (
    <TooltipProvider>
      <div className="flex w-full max-w-2xl flex-col">
        <Message mine>
          <MessageContent>
            <MessageBubble>What changed in Harbour Street's book this quarter?</MessageBubble>
          </MessageContent>
        </Message>
        <Message agent author="Research assistant">
          <MessageContent>
            {steps.length === 0 ? (
              <MessageThinking />
            ) : (
              <Trace
                summary={running ? running.title : "Read 1 filing"}
                status={running ? "running" : "done"}
                {...(running ? {} : { duration: "2.4 s" })}
              >
                {steps.map((step, index) => (
                  <TraceStep key={index} {...step} />
                ))}
              </Trace>
            )}
            {text && <MessageAnswer streaming={reply.status === "streaming"}>{text}</MessageAnswer>}
            {reply.status === "stopped" && <MessageFooter>Stopped</MessageFooter>}
            <MessageActions>
              {working ? (
                <Button variant="ghost" size="sm" onClick={stop}>
                  <StopIcon data-icon="inline-start" className="size-3.5 fill-current" />
                  Stop
                </Button>
              ) : (
                <>
                  <CopyButton value={text} size="icon-sm" label="Copy answer" />
                  <IconButton size="icon-sm" icon={<RetryIcon />} label="Ask again" onClick={again} />
                </>
              )}
            </MessageActions>
          </MessageContent>
        </Message>
      </div>
    </TooltipProvider>
  );
}
```

Example: A venue sends pictures: one keeps its own shape, four or more fill a square with a count of the rest; press any to open them all in the lightbox (`docs/system/examples/message/state-pictures.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import { MessageImages, type MessageImage } from "@/components/cobalt/ui/message-attachment";

const photo = (file: string, alt: string, caption: string): MessageImage => ({
  src: `/photos/${file}`,
  alt,
  caption,
  width: 800,
  height: 800,
});

const hall = photo("gala-dinner.webp", "A long table set with glasses and candles", "The hall, set for 40");
const stage = photo("panel.webp", "The stage with four chairs under spotlights", "The stage, before the panel");
const microphone = photo("speaker-night.webp", "A microphone on a stand under the stage light", "The lectern microphone");
const reception = photo("career-night.jpg", "Guests talking at the reception", "Drinks in the foyer");
const snacks = photo("welcome-mixer.webp", "Bowls of snacks on the reception table", "What the caterer brings to the foyer");
const room = photo("assembly.jpg", "The lecture room under its skylight", "The lecture room upstairs");

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageImages images={[hall]} />
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>This is the hall as we would set it for your dinner.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Lovely. Where would the panel sit?</MessageBubble>
        </MessageContent>
      </Message>
      <Message position="first">
        <MessageContent>
          <MessageImages images={[stage, microphone, reception, snacks, room]} />
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>On the stage, with drinks in the foyer after.</MessageBubble>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: Files as they arrive: Tag's glyph in each kind's colour, the extension kept when the name is cut, the kind and size, the block a link that downloads it (`docs/system/examples/message/state-files.tsx`)

```tsx
import { Message, MessageContent } from "@/components/cobalt/ui/message";
import { MessageFile } from "@/components/cobalt/ui/message-attachment";

const files = [
  { name: "Harbour Street Master Fund, Q3 13F-HR holdings and changes.pdf", size: 2_400_000 },
  { name: "Q3 holdings by sector.xlsx", size: 812_000 },
  { name: "LP update, October.pptx", size: 14_200_000 },
  { name: "Data room export.zip", size: 268_000_000 },
];

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      {files.map((file, index) => (
        <Message key={file.name} position={index === 0 ? "first" : index === files.length - 1 ? "last" : "middle"}>
          <MessageContent>
            <MessageFile name={file.name} size={file.size} href={`#${index}`} />
          </MessageContent>
        </Message>
      ))}
    </div>
  );
}
```

Example: Uploads drawn on what is uploading: the file's colour rising in its sheet, a ring over the photo; Retry in the place of the two that lose the network (`docs/system/examples/message/state-upload.tsx`)

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

import { Message, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";
import { MessageFile, MessageImages } from "@/components/cobalt/ui/message-attachment";
import { nextUpload, type Upload, type UploadEvent } from "@/lib/cobalt/messages";

type Key = "sheet" | "deck" | "table" | "stage";

// The stand-in transport: how far each upload gets before the network drops it, on its first try.
const dropsAt: Record<Key, number | null> = { sheet: null, deck: 48, table: null, stage: 30 };
const start: Record<Key, Upload> = {
  sheet: { status: "uploading", progress: 0 },
  deck: { status: "uploading", progress: 0 },
  table: { status: "uploading", progress: 0 },
  stage: { status: "uploading", progress: 0 },
};

export default function Example() {
  const [uploads, setUploads] = useState(start);
  const tried = useRef(new Set<Key>());
  const send = (key: Key, event: UploadEvent) =>
    setUploads((current) => ({ ...current, [key]: nextUpload(current[key], event) }));

  // Every 250ms each upload under way moves on, until it is done or the network drops it.
  const latest = useRef(uploads);
  latest.current = uploads;
  useEffect(() => {
    const timer = setInterval(() => {
      for (const key of Object.keys(latest.current) as Key[]) {
        const upload = latest.current[key];
        if (upload.status !== "uploading") continue;
        const progress = (upload.progress ?? 0) + 6;
        const drop = tried.current.has(key) ? null : dropsAt[key];
        if (drop !== null && progress >= drop) {
          tried.current.add(key);
          send(key, { type: "fail" });
        } else send(key, progress >= 100 ? { type: "finish" } : { type: "progress", progress });
      }
    }, 250);
    return () => clearInterval(timer);
  }, []);

  const all = Object.values(uploads);
  const status = all.some((upload) => upload.status === "failed")
    ? "failed"
    : all.some((upload) => upload.status === "uploading")
      ? "pending"
      : "sent";
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message mine position="first">
        <MessageContent>
          <MessageFile name="Seating plan.xlsx" size={812_000} upload={uploads.sheet} href="#plan" />
        </MessageContent>
      </Message>
      <Message mine position="middle">
        <MessageContent>
          <MessageFile
            name="Dinner run of show.pptx"
            size={14_200_000}
            upload={uploads.deck}
            onRetry={() => send("deck", { type: "retry" })}
            href="#deck"
          />
        </MessageContent>
      </Message>
      <Message mine position="last">
        <MessageContent>
          <MessageImages
            images={[
              { src: "/photos/gala-dinner.webp", alt: "The table setting we liked", width: 800, height: 800, upload: uploads.table },
              { src: "/photos/panel.webp", alt: "The stage at last year's dinner", width: 800, height: 800, upload: uploads.stage },
            ]}
            onRetry={() => send("stage", { type: "retry" })}
          />
          <MessageFooter>
            <MessageStatus status={status} />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: Read, and one not sent, kept with Retry; Retry sends it again (`docs/system/examples/message/state-delivery.tsx`)

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

import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";
import { nextDelivery, type Delivery } from "@/lib/cobalt/messages";

export default function Example() {
  const [delivery, setDelivery] = useState<Delivery>("failed");
  const retry = () => {
    setDelivery((current) => nextDelivery(current, "retry"));
    setTimeout(() => setDelivery((current) => nextDelivery(current, "accept")), 900);
  };
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message mine>
        <MessageContent>
          <MessageBubble>The amendment moved the closing date to Nov 14.</MessageBubble>
          <MessageFooter>
            <MessageStatus status="read" />
          </MessageFooter>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>Can you check the fee table on page 12?</MessageBubble>
          <MessageFooter>
            <MessageStatus status={delivery} onRetry={retry} />
          </MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: Reactions under a message: yours in ink, press one to take it back or add to it, and Add reaction for any other emoji (`docs/system/examples/message/state-reactions.tsx`)

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

import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import { Reaction, ReactionAdd, Reactions } from "@/components/cobalt/ui/reactions";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";

// Emoji are written as escapes: the system's emoji ban scans source text.
const start = [
  { emoji: "\u{1F44D}", count: 3, mine: true, others: "Maya Chen and Daniel Okafor" },
  { emoji: "\u{1F440}", count: 1, mine: false, others: "James Whitaker" },
];

export default function Example() {
  const [reactions, setReactions] = useState(start);
  const toggle = (emoji: string, on: boolean) =>
    setReactions((list) => {
      const found = list.find((item) => item.emoji === emoji);
      if (!found) return [...list, { emoji, count: 1, mine: true, others: "" }];
      return list
        .map((item) => (item.emoji === emoji && item.mine !== on ? { ...item, mine: on, count: item.count + (on ? 1 : -1) } : item))
        .filter((item) => item.count > 0);
    });
  return (
    <TooltipProvider>
      <div className="flex w-full max-w-lg flex-col">
        <Message>
          <MessageContent>
            <MessageBubble>Harbour Street filed its 13F: 192 positions, up from 181.</MessageBubble>
            <Reactions>
              {reactions.map((item) => (
                <Reaction
                  key={item.emoji}
                  emoji={item.emoji}
                  count={item.count}
                  pressed={item.mine}
                  names={[item.others, item.mine ? "you" : ""].filter(Boolean).join(" and ")}
                  onPressedChange={(on) => toggle(item.emoji, on)}
                />
              ))}
              <ReactionAdd onPick={(emoji) => toggle(emoji, true)} />
            </Reactions>
          </MessageContent>
        </Message>
      </div>
    </TooltipProvider>
  );
}
```

Example: A reply with what it answers at the top of its bubble (`docs/system/examples/message/state-quote.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageQuote, MessageText } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message>
        <MessageContent>
          <MessageBubble>
            <MessageQuote author="You" onClick={() => document.getElementById("lift")?.scrollIntoView({ block: "center" })}>
              Is there a lift? We have two large suitcases.
            </MessageQuote>
            <MessageText>There is no lift, but Daniel will carry them up. The room is on the third floor.</MessageText>
          </MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>
            <MessageQuote author="Sofia Reyes">There is no lift, but Daniel will carry them up.</MessageQuote>
            <MessageText>That is kind of him, thank you.</MessageText>
          </MessageBubble>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: A message taken back keeps its place as an outline that says so (`docs/system/examples/message/state-deleted.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageDeleted, MessageFooter } from "@/components/cobalt/ui/message";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message position="first">
        <MessageContent>
          <MessageDeleted />
        </MessageContent>
      </Message>
      <Message position="last">
        <MessageContent>
          <MessageBubble>Sorry, wrong booking. Yours is the one for Oct 18.</MessageBubble>
          <MessageFooter>Edited</MessageFooter>
        </MessageContent>
      </Message>
    </div>
  );
}
```

Example: A long address, a word with no break, emoji alone and line breaks (`docs/system/examples/message/state-wrapping.tsx`)

```tsx
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";

// Emoji are written as escapes: the system's emoji ban scans source text.
const PARTY = "\u{1F389}\u{1F389}";

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col">
      <Message>
        <MessageContent>
          <MessageBubble>
            The signed link: https://files.example.com/share/9f2c1e7a4b8d4f0e9a3c5b6d7e8f9a0b1c2d3e4f/Q3-board-deck-revised-v12.pdf?expires=1760745600
          </MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>The fund is Kapitalverwaltungsgesellschaftsbeteiligungsfonds II, if you search for it.</MessageBubble>
        </MessageContent>
      </Message>
      <Message mine>
        <MessageContent>
          <MessageBubble>{PARTY}</MessageBubble>
        </MessageContent>
      </Message>
      <Message>
        <MessageContent>
          <MessageBubble>{"Directions:\n1. Leave the car where the road ends\n2. Take the trail up through the forest\n3. The lodge is the red house above the fjord"}</MessageBubble>
        </MessageContent>
      </Message>
    </div>
  );
}
```

### State precedence
- Pending, sent, read and failed: Not applicable: a message has one delivery at a time, from `nextDelivery`.
- Uploading, upload failed and file ready: Not applicable: an attachment has one upload at a time, from `nextUpload`.
- Failed and upload failed: both show. "Not sent" under the message, and Retry on the file or picture that failed, which sends it again.
- Thinking, streaming, stopped: Not applicable: a reply has one status at a time, from `nextReply`.
- Failed and hover: both show. "Not sent" and Retry stay under the bubble while the aside shows beside it.
- Quote and deleted: deleted wins. A taken-back message shows no quote, since `MessageDeleted` replaces the bubble.
- Reactions and deleted: deleted wins. A taken-back message keeps no reactions.
- Wrapping and quote: both show. The quote cuts to two lines and the words under it wrap.
- Arrived and anything else: both show. The arrival moves the whole message once; its states draw as they would at rest.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| a message arrives while the thread is open | announce | `animate-arrive`, `--t-arrive` 220ms on `--curve` | opacity, and translate from 4px | no animation; it is there at once |
| a message joins a run and a corner tightens | announce | `--t-settle` 300ms on `--curve` | border-radius | the corner changes at once |
| the aside shows on hover or focus | input | `--t-press` 140ms | opacity | the same fade, opacity only |
| an upload moves on | announce | `--t-settle` on `--curve` | the sheet's colour rising, transform translate on its clip; the photo ring's stroke-dashoffset | they jump to each value |
| an upload's share is not known yet | announce | `animate-pulse` on the grey sheet, `animate-spin` on the photo ring | opacity, rotate | they hold still |
| the caret while a reply streams, the thinking dots | announce | Tailwind `animate-pulse` | opacity | they hold still |
| a reaction or Retry is pressed | input | `pressable`, `--t-press` | box-shadow tint, background-color | the same |

## Props

<!-- Props generated from registry/cobalt/ui/message.tsx, registry/cobalt/ui/message-attachment.tsx, registry/cobalt/ui/reactions.tsx with TypeScript by scripts/props-table.mjs -->
### Message

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `agent?` | `boolean` | `false` | An assistant wrote it: prose across the thread, with no bubble. |
| `author?` | `string` |  | Who sent it, read before the message by a screen reader. |
| `mine?` | `boolean` | `false` | You sent it. |
| `position?` | `RunPosition` | `"single"` | `single` a message with no other from the same person beside it; `first` the first of a run; `middle` between two of a run; `last` the last of a run. |

Also accepts every native `<div>` attribute.

### MessageActions

No props of its own.

Also accepts every native `<div>` attribute.

### MessageAnswer

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `streaming?` | `boolean` | `false` | The words are still coming. |

Also accepts every native `<div>` attribute.

### MessageAside

No props of its own.

Also accepts every native `<div>` attribute.

### MessageBubble

No props of its own.

Also accepts every native `<div>` attribute.

### MessageContent

No props of its own.

Also accepts every native `<div>` attribute.

### MessageDeleted

No props of its own.

Also accepts every native `<p>` attribute.

### MessageFooter

No props of its own.

Also accepts every native `<div>` attribute.

### MessageQuote

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `author` | `string` |  |  |
| `children` | `ReactNode` |  | The words quoted, cut to two lines. |
| `className?` | `string` |  |  |
| `label?` | `string` | `"Reply to"` | Read before the author, so a screen reader knows this is a quote. |
| `onClick?` | `() => void` |  | Goes to the quoted message. |

### MessageStatus

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `status` | `Delivery` |  |  |
| `labels?` | `Partial<Record<Delivery \| "retry", string>>` |  |  |
| `onRetry?` | `() => void` |  |  |

### MessageText

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `children` | `string` |  |  |

Also accepts every native `<p>` attribute.

### MessageThinking

No props of its own.

Also accepts every native `<div>` attribute.

### MessageTime

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `value` | `string \| number \| Date` |  |  |
| `className?` | `string` |  |  |
| `locale?` | `string` | `"en-US"` |  |
| `timeZone?` | `string` |  |  |

### MessageFile

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `name` | `string` |  |  |
| `size` | `number` |  | In bytes. |
| `className?` | `string` |  |  |
| `href?` | `string` |  | Where it downloads from, once it is uploaded. |
| `labels?` | `Partial<MessageFileLabels>` |  |  |
| `mime?` | `string` |  | Its MIME type, which says its kind before its extension does. |
| `onRetry?` | `() => void` |  | Tries a failed upload again. |
| `upload?` | `Upload` |  | Its upload, from `nextUpload`. |

### MessageImages

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `images` | `readonly MessageImage[]` |  |  |
| `className?` | `string` |  |  |
| `labels?` | `Partial<MessageImagesLabels>` |  |  |
| `lightboxLabels?` | `Partial<LightboxLabels>` |  |  |
| `onRetry?` | `(index: number) => void` |  | Tries a failed picture's upload again, by its index. |

### UploadRing

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `label` | `string` |  |  |
| `className?` | `string` |  |  |
| `progress?` | `number` |  |  |

### Reactions

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `label?` | `string` | `"Reactions"` |  |

Also accepts every native `<div>` attribute.

### Reaction

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `count` | `number` |  |  |
| `emoji` | `string` |  |  |
| `onPressedChange` | `(pressed: boolean) => void` |  |  |
| `pressed` | `boolean` |  | You reacted with it. |
| `className?` | `string` |  |  |
| `label?` | `(count: number, emoji: string) => string` | `(n, e) => `${counted(n, { one: "person", other: "people" })} reacted with ${e}`` |  |
| `names?` | `string` |  | Who reacted, for the tooltip: "Maya Chen and you". |

### ReactionAdd

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `onPick` | `(emoji: string) => void` |  |  |
| `label?` | `string` | `"Add reaction"` |  |
| `pickerLabels?` | `Partial<EmojiPickerLabels>` |  |  |

`mine`, `agent` and `position` set the side, the look and the corners. `author` is read before the message by a screen reader. `MessageBubble` takes a string, or a `MessageQuote` and a `MessageText`. `MessageAnswer` takes the answer as a string and `streaming`. `MessageStatus` takes `status` (`pending`, `sent`, `read`, `failed`), `onRetry` and `labels`. `MessageTime` takes `value`, `locale` and `timeZone`. `MessageImages` takes `images` (`src`, `alt`, `width`, `height`, `caption`, `original` and `upload`), `onRetry` by index, `labels` and `lightboxLabels`. `MessageFile` takes `name`, `mime`, `size` in bytes, `href`, `upload`, `onRetry` and `labels`. `FileTypeIcon` takes `name`, `mime`, `upload` and `label`, for a file glyph anywhere else, such as the composer's attachments. `Reaction` takes `emoji`, `count`, `pressed`, `onPressedChange`, `names` and `label`; `ReactionAdd` takes `onPick`. `useMessageBlock` gives an attachment drawn elsewhere the same corners.

## Usage

### When to use
- A conversation between people: a guest and a host, two analysts about a filing, a customer and support.
- An assistant's reply in a research tool, with a `Trace` above its answer.
- Pictures, files and reactions sent in such a conversation, as part of the message that carries them.

### When not to use
- A list of events in order, such as a booking's history. Use Timeline instead.
- A one-line notice that something happened. Use Alert instead, or a toast from Toaster.
- A gallery or a listing's photos. Use MediaTile instead.
- Marking a thing to come back to. Use SaveToggle instead.

### Rules
- `rule/message-failure-stays`: When a send fails, keep the message in the thread with `MessageStatus status="failed"` and its Retry instead of removing it or calling `toast()`, because the words are the person's, and a failure that goes away with a toast loses them and hides which message did not arrive. Evidence: person D39; principle heuristic: help users recognize, diagnose and recover from errors, the error sits on the thing that failed. Check: review of every send handler for a `toast()` or a removal on failure.
  - Don't: `catch { setPosts((list) => list.filter((p) => p.id !== id)); toast("Message failed") }`
  - Do: `catch { setDelivery((d) => nextDelivery(d, "fail")) }` with `<MessageStatus status="failed" onRetry={retry} />`
- `rule/message-runs-from-thread-rows`: When rendering messages in a thread, take each `position` from `threadRows` instead of working it out per message, because a run depends on the messages on both sides, its time window and its day, and a position worked out alone leaves a tight corner facing nothing. Evidence: measured 9 run cases in registry/cobalt/lib/messages.test.ts, ported from Tag's tested bubble-runs model. Check: review of every `<Message` with a `position`.
  - Don't: `<Message position={prev?.from === m.from ? "last" : "single"} />`
  - Do: `threadRows(messages).map((row) => <Message position={row.position} />)`
- `rule/message-touch-actions`: When a message has actions in `MessageAside`, put the same actions in a `ContextMenu` around the message, because the aside shows on hover and is not drawn under a coarse pointer, so a phone would have no way to react. Evidence: principle heuristic: flexibility and efficiency of use, a long press is the touch path for what hover shows. Check: review of every `MessageAside`.
  - Don't: `<Message><MessageContent /><MessageAside><ReactButton /></MessageAside></Message>` alone
  - Do: `<ContextMenu><ContextMenuTrigger render={<Message />}>...</ContextMenuTrigger><ContextMenuContent>...</ContextMenuContent></ContextMenu>`
- `rule/message-states-from-the-rules`: When a message's delivery, an upload or a reply changes, move it with `nextDelivery`, `nextUpload` or `nextReply` instead of setting the status by hand, because they ignore a move the state does not allow, such as a late progress report after a failure or a second finish, which by hand would bring a failed upload back to life. Evidence: measured 4 rule tests in registry/cobalt/lib/messages.test.ts. Check: review of every handler that sets `status` or `upload`.
  - Don't: `onProgress={(p) => setUpload({ status: "uploading", progress: p })}`
  - Do: `onProgress={(p) => setUpload((u) => nextUpload(u, { type: "progress", progress: p }))}`
- `rule/message-attachment-size-known`: When a picture's size is known, pass `width` and `height`, because its box is drawn at its final size before it loads, and nothing in the thread moves when it does. Evidence: person D37. Check: review of every `MessageImages` image without a size.
  - Don't: `images={[{ src, alt }]}` for a stored picture
  - Do: `images={[{ src, alt, width: 1600, height: 1200 }]}`
- `rule/message-attachment-failure-retry`: When an upload stops, give its `MessageFile` or picture `upload={{ status: "failed" }}` and `onRetry`, and say "Not sent" on its message, because the person needs to know which file did not arrive and a way to send it again. Evidence: person D39. Check: review of every upload handler.
  - Don't: `catch { removeFile(id) }`
  - Do: `<MessageFile name={name} size={size} upload={upload} onRetry={retry} />`
- `rule/message-reactions-toggle-at-once`: When a `Reaction` is pressed, change its count and fill at once and send in the background, moving it back with a message only if the server refuses, instead of waiting on the request, because a reaction is a light answer people give many times a day. Evidence: person D39, D14. Check: review of every `onPressedChange`.
  - Don't: `onPressedChange={async (on) => { await api.react(on); refresh() }}`
  - Do: `onPressedChange={(on) => { setMine(on); api.react(on).catch(() => setMine(!on)) }}`
- `rule/message-reactions-name-who`: When the people behind a reaction are known, pass them as `names`, with "you" in it when yours, because the count alone does not say whether the person who matters answered. Evidence: principle heuristic: visibility of system status. Check: review of every `Reaction` without `names`.
  - Don't: `<Reaction emoji={e} count={3} pressed />`
  - Do: `<Reaction emoji={e} count={3} pressed names="Maya Chen, James Whitaker and you" />`

### Content
- Follows `rule/writing-status-verb-ing`.
- `rule/message-status-words`: When showing where your message is, use one of "Sending", "Sent", "Read" or "Not sent", in at most 2 words, instead of icons or ticks alone, because a tick's meaning has to be learned and a word does not. Evidence: principle heuristic: match between the system and the real world, a word needs no learning. Check: test `message.test.tsx` renders each status as its word.
  - Don't: `<MessageFooter><CheckIcon /><CheckIcon /></MessageFooter>`
  - Do: `<MessageFooter><MessageStatus status="read" /></MessageFooter>`
- `rule/message-attachment-alt-says-what`: When writing a picture's `alt`, say what it shows in at most 10 words, such as "The fjord from the lodge's terrace", instead of its file name, because the file name says nothing to someone who cannot see it. Evidence: principle wcag: 1.1.1 Non-text content. Check: review.
  - Don't: `alt="IMG_4021.jpg"`
  - Do: `alt="The fjord from the lodge's terrace"`
- `rule/message-reactions-label-count-first`: When wording a chip's name, put the count first with "person" or "people" and the emoji last, such as "3 people reacted with" and the emoji, because a screen reader reads the emoji's name and the count leads. Evidence: principle wcag: 4.1.2 Name, role, value. Check: test `reactions.test.tsx`.
  - Don't: `label={(n, e) => `${e} x${n}`}`
  - Do: `<Reaction emoji={e} count={3} pressed={false} onPressedChange={set} />`

### Anti-slop
- `rule/message-no-pop-in`: When a message arrives, let the thread mark it so it rises 4px and fades, instead of scaling it in or bouncing it, because nothing in the system scales and a bounce on every message grates within a day. Evidence: person D36, D14. Check: test `thread.test.tsx` and a review of message motion for `scale`.
  - Don't: `<motion.div initial={{ scale: 0.8 }} animate={{ scale: 1 }}>`
  - Do: `<Message />` inside a `Thread`, which sets `data-arrived`
- `rule/message-upload-on-the-thing`: When an attachment uploads, pass its `upload` so it is drawn on the file's glyph or over the photo, instead of a progress bar under it, because the bar adds a line that goes when the upload ends and moves the thread, while the glyph is already in the block at 40px. Evidence: person D37; measured the file block at 56px in every state, `.design-system/evidence/message/measure.json`. Check: test `message-attachment.test.tsx`.
  - Don't: `<MessageFile name={name} size={size} /><Progress value={42} />`
  - Do: `<MessageFile name={name} size={size} upload={{ status: "uploading", progress: 42 }} />`
- `rule/message-attachment-file-glyph`: When showing a file anywhere, draw its glyph with `FileTypeIcon` instead of a generic file icon or a coloured badge of its own, because its 10 kinds, colours and marks are one set ported from Tag, read from the `--file-*` tokens, and a second set drifts from it. Evidence: person D41, every colour themable by tokens; principle heuristic: consistency and standards, one set of file glyphs. Check: review of file glyphs outside `file-type-icon.tsx`.
  - Don't: `<FileIcon className="text-chart-3" />` beside a file name
  - Do: `<FileTypeIcon name="Guide.pdf" />`

### Limits
- `rule/message-measure`: When a person's message runs past 28rem, about 62 characters a line at 14px, let the bubble wrap at `max-w-md` instead of widening it to the thread, because a longer line loses the eye on the way back. Evidence: measured 62 characters per line at 14px in a 440px bubble, `.design-system/evidence/message/measure.json`, from docs/system/stress/message.tsx at 1440. Check: probe in docs/system/stress/message.tsx.
  - Don't: `<MessageBubble className="max-w-none">`
  - Do: `<MessageBubble>{text}</MessageBubble>`
- `rule/message-answer-measure`: When an assistant's answer runs long, keep it in its 32rem column, about 78 characters a line at 14px, instead of the thread's full width, because a 42rem line held 104 characters and lost the eye on the way back. Evidence: measured 104 characters a line at 672px and 78 at 512px, `.design-system/evidence/message/measure.json`, from docs/system/stress/message.tsx at 1440. Check: probe in docs/system/stress/message.tsx.
  - Don't: `<MessageContent className="max-w-none">` in an agent's message
  - Do: `<Message agent><MessageContent><MessageAnswer>{text}</MessageAnswer></MessageContent></Message>`
- `rule/message-attachment-four`: When a message holds more than 4 pictures, show 4 and the count of the rest on the fourth, and let the lightbox show them all, because past 4 cells each picture is too small to read in a bubble's width. Evidence: measured 4 cells of 143px at the 18rem picture width, docs/system/examples/message/state-pictures.tsx. Check: test `message-attachment.test.tsx`.
  - Don't: `<MessageImages images={twelve} />` drawn as 12 cells
  - Do: `<MessageImages images={twelve} />`, which draws 4 and opens all 12
- `rule/message-reactions-wrap`: When a message has more than 6 different reactions, let the row wrap under the message instead of scrolling it sideways or hiding some behind "more", because every reaction is someone's answer. Evidence: measured 11 reactions and Add reaction wrap to 2 lines under a 384px message at 1440 and 4 lines under a 192px one at 320, in docs/system/stress/thread.tsx worst. Check: probe in docs/system/stress/thread.tsx at 320 and 1440.
  - Don't: `<Reactions className="overflow-x-auto flex-nowrap">`
  - Do: `<Reactions>{all}</Reactions>`

## Accessibility
Rests on native elements: a `div` per message, `p` for its words, `a` for its addresses and files, `button` for a quote that jumps, Retry and each picture, `img`, `time`, and Base UI `Toggle` for each reaction.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the message | moves to its links and buttons in order: a quote, an address, a picture, a file or its Retry, the reactions, Retry, then the aside's buttons | that part, and the aside shows | by hand |
| Enter | an address | opens it in a new tab | stays on the address | by hand |
| Enter | the quote | goes to the quoted message | where the host sends it | by hand |
| Enter | a picture | opens the lightbox at it | the lightbox; back to the picture on Escape | by hand |
| Enter | a ready file | downloads it | stays on the link | by hand |
| Enter | Retry, on the message, a file's glyph or a photo | sends it again | stays on the button while it is drawn, then the message | by hand |
| Enter or Space | a reaction | adds or takes back yours | stays on the chip | by hand |
| Shift+F10 | inside a message in a `ContextMenu` | opens its actions | the menu's first item | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| message | none, a `div` | `author` as visually hidden text before its words | `data-mine`, `data-agent`, `data-position` for styling only | the author, then the words, as the thread's log adds it | test |
| answer | none | its words | `aria-busy` while it streams | the answer once it is whole | test |
| thinking | status | "Thinking" | none | "Thinking" | test |
| quote | button, or none as a `blockquote` | "Reply to", the author and the quoted words | none | "Reply to Maya Chen, the filing is in, button" | test |
| addresses | link | the address | `target="_blank"` | the address and "link" | test |
| status | none | its word | none | as the thread's log reads changes: "Sent", "Read", "Not sent" | test |
| picture | button, `img` when it failed | `alt`, and "2 more" on the last | `aria-haspopup="dialog"` | "The fjord from the lodge's terrace, button" | test |
| file | link when ready | its name | `download` | the name and "link" | test |
| file glyph, photo ring | progressbar while uploading, hidden otherwise | "Uploading" and the file's name or the picture's `alt` | `aria-valuenow` 0 to 100 when known | the name and the percentage | test |
| Retry | button | "Retry", or "Retry uploading" and the name | none | "Retry uploading Passport.pdf, button" | test |
| reactions | group | `label`, "Reactions" | none | "Reactions, group" | test |
| reaction | button | "3 people reacted with" and the emoji | `aria-pressed` | "3 people reacted with thumbs up, toggle button, pressed" | test |
| time | none, a `time` | the time of day | `dateTime`, and the full date as `title` | the time | test |

## Tokens
| Part | State | Token |
|---|---|---|
| bubble | theirs | `--bubble`, `--bubble-foreground` |
| bubble | yours | `--bubble-mine`, `--bubble-mine-foreground` |
| bubble, pictures, file | all | `--r-bubble`, `--r-bubble-joined`, `--t-settle`, `--curve` |
| quote | all | `--r-bubble-inner`, the text colour at 8 percent |
| answer, caret | all | `--foreground` |
| thinking, actions | all | `--muted-foreground` |
| deleted | all | `--border`, `--muted-foreground`, `--r-bubble` |
| status | failed | `--destructive`, `--primary-ink` |
| pictures | all | `--outline-image`, `--muted` |
| picture | focus-visible | `--ring` inside `--on-photo`, drawn inside the cell |
| over a photo | uploading, failed, more | `--on-photo` on a dark shade |
| file glyph | all | `--file-other`, `--file-document`, `--file-spreadsheet`, `--file-presentation`, `--file-pdf`, `--file-image`, `--file-code`, `--file-archive`, `--file-audio`, `--file-video`, and `--file-ink` for its mark |
| file glyph | uploading, failed | `--file-other` at 45 percent under the kind's colour |
| photo ring | uploading | `--on-photo`, its track at 20 percent, on a dark disc, `--t-settle` |
| Retry over a photo | failed | `--r-control` |
| reaction | theirs | `--muted`, `--muted-hover`, `--foreground` |
| reaction | yours | `--foreground`, `--background` |
| reaction | all | `--r-control-sm`, `--touch`, `--t-press` |
| aside, time | all | `--muted-foreground`, `--t-press` |
| arrival | arrived | `--t-arrive`, `--curve` |

## Related
- Thread: the scrolling conversation that holds messages and works out their runs.
- Trace: the steps an assistant took, above its answer.
- Lightbox: where a message's pictures open.
- Composer: writes the next message, and attaches its files.
- EmojiPicker: what Add reaction opens.
- Timeline: events in order that nobody said.
- Empty: says a place holds nothing yet, or why it could not load, with the next step.
