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

## Description
Holds a conversation that grows while you read it: it opens at the newest message, keeps what you are reading still when more comes, tells you how many came, and says when someone is writing.

`import { Thread, ThreadDay, ThreadTyping } from "@/components/cobalt/ui/thread"`, source `registry/cobalt/ui/thread.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/scroll-chain`, `trap/loading-layout-shift`, `trap/live-region-double`, `trap/reduced-motion-ignored`, `trap/motion-frequent`, `trap/loader-small-dots`, `trap/overflow-scrollbar`.

`trap/scroll-chain` is answered by `overscroll-behavior: contain` on the scroller (Tokens). `trap/loading-layout-shift` by the typing line, which holds its height while no one writes, and by the anchor that keeps the row you read still while pictures load or older messages are added (Rules). `trap/live-region-double` by one log: the thread is `role="log"`, and nothing inside it adds a second live region (ARIA). `trap/reduced-motion-ignored` by the smooth scroll to the newest message turning instant and the typing dots holding still under reduced motion (Motion). `trap/motion-frequent` by arrivals, which animate only for messages that came while the thread was open. `trap/loader-small-dots` by the typing line saying who writes in words beside its dots. `trap/overflow-scrollbar` by the scroller's own `overflow-y: auto`, with fading edges that show only while more is hidden.

### Foundation
Not applicable: hand-rolled.

| Given by the foundation | Added by the team |
|---|---|
| Not applicable: hand-rolled from Tag's conversation and transcript geometry (`/Users/kaanaricioglu/tag/src/owner-ui/Conversation.svelte`, `transcript-geometry.ts`) | Follows the end within 48px and stays there; a reading anchor kept across any change of height; a count of messages that came below while you read, as a button that takes you down; your own message brings you to it; arrivals marked for `animate-arrive`; day rows from `dayLabel`; a typing line that never moves the thread. Dropped from Tag: selection and anchor restore across conversation switches and reloads, the paged reload to find a saved row, and the 1.5-second typing linger, which kept "is typing" under a message that had already come |

## Examples
A conversation about a filing over two days, opened at its newest message.

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

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/thread/default.tsx` | default | A thread opens at the newest message: day rows, runs of one sender, and the delivery of your last message |
| `docs/system/examples/thread/state-new-messages.tsx` | state:reading | Scroll up and press Receive: nothing you read moves, and a count at the bottom takes you to what came |
| `docs/system/examples/thread/state-typing.tsx` | state:typing | Who is writing, as a quiet line that moves nothing when it comes and goes |
| `docs/system/examples/thread/in-product.tsx` | composition:Composer | A guest and their host about a stay: pictures that open in the lightbox, a house guide, reactions, uploads drawn on what uploads, and a failed send kept with Retry |
| `docs/system/examples/thread/in-assistant.tsx` | composition:Message | An assistant in a research tool: the reply thinks, shows its trace while it reads, streams its answer with a caret, and Stop keeps what it said |

Example: A thread opens at the newest message: day rows, runs of one sender, and the delivery of your last message (`docs/system/examples/thread/default.tsx`)

```tsx
import { Message, MessageBubble, MessageContent, MessageFooter, MessageStatus } from "@/components/cobalt/ui/message";
import { Thread, ThreadDay } from "@/components/cobalt/ui/thread";
import { threadRows } from "@/lib/cobalt/messages";

const NOW = Date.parse("2026-10-17T15:00:00Z");
const messages = [
  { id: "1", from: "maya", at: "2026-10-16T16:02:00Z", text: "Did Meridian file the D/A?" },
  { id: "2", from: "you", at: "2026-10-16T16:10:00Z", text: "Yes, this morning. $640M sold of $1.5B." },
  { id: "3", from: "maya", at: "2026-10-17T09:12:00Z", text: "The closing date moved too." },
  { id: "4", from: "maya", at: "2026-10-17T09:12:30Z", text: "Nov 14 now, it was Oct 31." },
  { id: "5", from: "you", at: "2026-10-17T09:20:00Z", text: "Added it to the tracker." },
];

export default function Example() {
  const rows = threadRows(messages, { timeZone: "UTC", now: NOW });
  return (
    <div className="w-full max-w-lg rounded-2xl bg-card">
      <Thread label="Messages with Maya Chen" className="h-80">
        {rows.map((row) =>
          row.kind === "day" ? (
            <ThreadDay key={row.key} day={row.day} now={NOW} timeZone="UTC" />
          ) : (
            <Message key={row.key} mine={row.message.from === "you"} position={row.position}>
              <MessageContent>
                <MessageBubble>{row.message.text}</MessageBubble>
                {row.message.id === "5" && (
                  <MessageFooter>
                    <MessageStatus status="read" />
                  </MessageFooter>
                )}
              </MessageContent>
            </Message>
          ),
        )}
      </Thread>
    </div>
  );
}
```

Example: A guest and their host about a stay: pictures that open in the lightbox, a house guide, reactions, uploads drawn on what uploads, and a failed send kept with Retry (`docs/system/examples/thread/in-product.tsx`)

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

import { AddReactionIcon } from "@/components/cobalt/icon";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/cobalt/ui/avatar";
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from "@/components/cobalt/ui/context-menu";
import {
  Composer,
  ComposerAttach,
  ComposerAttachments,
  ComposerInput,
  ComposerSend,
  type ComposerDraft,
} from "@/components/cobalt/ui/composer";
import { EmojiPickerPopover } from "@/components/cobalt/ui/emoji-picker";
import { IconButton } from "@/components/cobalt/ui/icon-button";
import { Item, ItemContent, ItemDescription, ItemGroup, ItemMedia, ItemTitle } from "@/components/cobalt/ui/item";
import {
  Message,
  MessageAside,
  MessageBubble,
  MessageContent,
  MessageFooter,
  MessageQuote,
  MessageStatus,
  MessageText,
  MessageTime,
} from "@/components/cobalt/ui/message";
import { MessageFile, MessageImages, type MessageImage } from "@/components/cobalt/ui/message-attachment";
import { Reaction, ReactionAdd, Reactions } from "@/components/cobalt/ui/reactions";
import { Thread, ThreadDay, ThreadTyping } from "@/components/cobalt/ui/thread";
import { TooltipProvider } from "@/components/cobalt/ui/tooltip";
import { nextDelivery, nextUpload, threadRows, type Delivery, type Upload } from "@/lib/cobalt/messages";

// The scene's clock is fixed, so its days read the same on every visit: it is 09:41 on Saturday, Oct 17,
// in UTC, and new messages take the time that has passed since the scene opened.
const NOW = Date.parse("2026-10-17T09:41:00Z");
const ZONE = "UTC";

// Emoji are written as escapes: the system's emoji ban scans source text.
const PRAY = "\u{1F64F}";
const HEART = String.fromCodePoint(0x2764, 0xfe0f);
const THUMBS = "\u{1F44D}";
const LAUGH = "\u{1F602}";
// The quick reactions a long press offers on a touch screen, where the row's hover actions are not drawn.
const QUICK = [
  { emoji: HEART, name: "Love" },
  { emoji: THUMBS, name: "Like" },
  { emoji: LAUGH, name: "Laugh" },
  { emoji: PRAY, name: "Thanks" },
];

type Reacted = { emoji: string; count: number; mine: boolean; names: string };
type Post = {
  id: string;
  from: "you" | "ingrid";
  at?: number;
  text?: string;
  quote?: { author: string; text: string };
  images?: MessageImage[];
  file?: { name: string; size: number; href?: string };
  /** The upload of its pictures or file, while it has one, from `nextUpload`. */
  upload?: Upload;
  reactions?: Reacted[];
  /** Where your message is, from `nextDelivery`. */
  delivery?: Delivery;
};

const at = (iso: string) => Date.parse(iso);
const photo = (file: string, alt: string, caption: string): MessageImage => ({
  src: `/photos/${file}`,
  alt,
  caption,
  width: 800,
  height: 800,
});
const history: Post[] = [
  { id: "m1", from: "ingrid", at: at("2026-10-16T18:02:00Z"), text: "Hi, I'm Ingrid. I run Fjordstova, and your room is ready for Sunday." },
  { id: "m2", from: "ingrid", at: at("2026-10-16T18:03:00Z"), text: "Check-in is from 3 PM. If you land earlier you can leave your bags with us." },
  { id: "m3", from: "you", at: at("2026-10-16T18:20:00Z"), text: "Thank you. Our flight lands at 8:40, so we will come by around 11." },
  { id: "m4", from: "you", at: at("2026-10-16T18:21:00Z"), text: "Can we drive up to the door? We have two large suitcases." },
  {
    id: "m5",
    from: "ingrid",
    at: at("2026-10-16T18:31:00Z"),
    quote: { author: "You", text: "Can we drive up to the door? We have two large suitcases." },
    text: "The road stops 200 m below the lodge. Leave the car there and Lars will bring the bags up.",
    reactions: [{ emoji: PRAY, count: 1, mine: true, names: "You" }],
  },
  {
    id: "m6",
    from: "ingrid",
    at: at("2026-10-17T08:58:00Z"),
    images: [
      photo("fjord-walk.jpg", "The fjord from the lodge's terrace", "From the terrace, at 8 this morning"),
      photo("hike.webp", "The forest trail up from the road", "The trail from the car park, five minutes up"),
      photo("barbecue.jpg", "Dinner cooking on the outdoor grill", "Friday dinner is on the grill"),
    ],
    reactions: [{ emoji: HEART, count: 1, mine: true, names: "You" }],
  },
  { id: "m7", from: "ingrid", at: at("2026-10-17T08:58:00Z"), text: "The path is the one with the roots, so bring shoes with a grip. Directions and the Wi-Fi code are in the guide." },
  { id: "m8", from: "ingrid", at: at("2026-10-17T08:59:00Z"), file: { name: "House guide.pdf", size: 2_400_000, href: "#guide" } },
  { id: "m9", from: "you", at: at("2026-10-17T09:30:00Z"), text: THUMBS },
  { id: "m10", from: "you", at: at("2026-10-17T09:31:00Z"), text: "Perfect, see you on Sunday.", delivery: "read" },
];

// 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). It answers after 900ms.
const offline = () => !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
const request = () =>
  new Promise<void>((resolve, reject) => setTimeout(() => (offline() ? reject(new Error("offline")) : resolve()), 900));

// The guest's other conversations, each with the host's picture. The open one reads its last line from the thread.
const INGRID = "/photos/portrait-1.webp";
const others = [
  { id: "james", name: "James Whitaker", photo: "/photos/portrait-5.webp", last: "Your flat in Oslo is ready from Dec 4.", when: "Mon" },
  { id: "hana", name: "Hana Sato", photo: "/photos/portrait-3.webp", last: "We will answer within a day.", when: "Oct 9" },
];
const clockTime = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: ZONE });
/** A message as one line in the inbox: its words, or what was sent. */
const preview = (post: Post) =>
  post.text ?? post.file?.name ?? (post.images ? (post.images.length === 1 ? "A photo" : `${post.images.length} photos`) : "");

export default function MessagesScene() {
  const [posts, setPosts] = useState(history);
  const [typing, setTyping] = useState<string[]>([]);
  const opened = useRef(Date.now());
  const answered = useRef(false);
  const clock = () => NOW + (Date.now() - opened.current);
  const urls = useRef<string[]>([]);
  useEffect(() => () => urls.current.forEach((url) => URL.revokeObjectURL(url)), []);

  const update = (id: string, change: (post: Post) => Post) =>
    setPosts((current) => current.map((post) => (post.id === id ? change(post) : post)));
  const moveDelivery = (id: string, event: Parameters<typeof nextDelivery>[1]) =>
    update(id, (post) => (post.delivery ? { ...post, delivery: nextDelivery(post.delivery, event) } : post));
  const moveUpload = (id: string, event: Parameters<typeof nextUpload>[1]) =>
    update(id, (post) => (post.upload ? { ...post, upload: nextUpload(post.upload, event) } : post));

  // Ingrid reads your first message and answers it, once.
  function answer() {
    if (answered.current) return;
    answered.current = true;
    setTimeout(() => setTyping(["Ingrid"]), 1200);
    setTimeout(() => {
      setTyping([]);
      setPosts((current) => [
        ...current.map((post) => (post.delivery ? { ...post, delivery: nextDelivery(post.delivery, "read") } : post)),
        { id: `r${Date.now()}`, from: "ingrid", at: clock(), text: "Got it. Safe travels." },
      ]);
    }, 3600);
  }

  // Sends words: Sending, then Sent, or Not sent with Retry.
  function deliver(id: string) {
    request().then(
      () => {
        moveDelivery(id, "accept");
        answer();
      },
      () => moveDelivery(id, "fail"),
    );
  }

  // Uploads pictures or a file in steps you can watch on the ring, and stops where it is when the
  // network goes. The message is sent once its upload is done.
  function upload(id: string) {
    let progress = 0;
    const step = () => {
      if (offline()) {
        moveUpload(id, { type: "fail" });
        moveDelivery(id, "fail");
        return;
      }
      progress += 15;
      if (progress < 100) {
        moveUpload(id, { type: "progress", progress });
        setTimeout(step, 250);
        return;
      }
      moveUpload(id, { type: "finish" });
      moveDelivery(id, "accept");
      answer();
    };
    setTimeout(step, 250);
  }

  function retry(post: Post) {
    moveDelivery(post.id, "retry");
    if (post.upload) {
      moveUpload(post.id, { type: "retry" });
      upload(post.id);
    } else deliver(post.id);
  }

  function send({ text, files }: ComposerDraft) {
    const pictures = files.filter((file) => file.type.startsWith("image/"));
    const documents = files.filter((file) => !file.type.startsWith("image/"));
    const added: Post[] = [];
    const base = { from: "you" as const, at: clock(), delivery: "pending" as const };
    if (pictures.length) {
      const images = pictures.map((file) => {
        const src = URL.createObjectURL(file);
        urls.current.push(src);
        return { src, alt: file.name };
      });
      added.push({ ...base, id: crypto.randomUUID(), images, upload: { status: "uploading", progress: 0 } });
    }
    for (const file of documents) {
      const href = URL.createObjectURL(file);
      urls.current.push(href);
      added.push({ ...base, id: crypto.randomUUID(), file: { name: file.name, size: file.size, href }, upload: { status: "uploading", progress: 0 } });
    }
    if (text) added.push({ ...base, id: crypto.randomUUID(), text });
    setPosts((current) => [...current, ...added]);
    for (const post of added) (post.upload ? upload : deliver)(post.id);
  }

  function react(id: string, emoji: string, on: boolean) {
    update(id, (post) => {
      const list = post.reactions ?? [];
      const found = list.find((item) => item.emoji === emoji);
      if (on && found?.mine) return post;
      const next = found
        ? list
            .map((item) =>
              item.emoji === emoji
                ? { ...item, mine: on, count: item.count + (on ? 1 : -1), names: on ? `${item.names} and you` : item.names.replace(/( and)? ?you$|^You$/, "") }
                : item,
            )
            .filter((item) => item.count > 0)
        : [...list, { emoji, count: 1, mine: true, names: "You" }];
      return { ...post, reactions: next };
    });
  }

  const rows = threadRows(
    posts.map((post) => ({ ...post, text: post.images || post.file ? undefined : post.text })),
    {
      timeZone: ZONE,
      now: NOW,
      // Reactions or a "Sending" or "Not sent" line under a message sit between it and the next one.
      ends: (post) => Boolean(post.reactions?.length) || post.delivery === "pending" || post.delivery === "failed",
    },
  );
  const lastMine = posts.findLast((post) => post.from === "you")?.id;
  const latest = posts.at(-1);
  const conversations = [
    {
      id: "ingrid",
      name: "Ingrid Solberg",
      photo: INGRID,
      last: latest ? preview(latest) : "",
      when: latest?.at === undefined ? "" : clockTime.format(latest.at),
    },
    ...others,
  ];

  return (
    <TooltipProvider>
      {/* The inbox shows beside the conversation once the box holds both, 36rem, and leaves it the whole box below. */}
      <div className="@container w-full">
        <div className="flex gap-4">
        <div className="hidden w-64 shrink-0 flex-col gap-3 @xl:flex">
          <h2 className="px-1 text-xl font-semibold tracking-tight">Messages</h2>
          <ItemGroup variant="card">
            {conversations.map((conversation) => (
              <Item
                key={conversation.id}
                render={<a href={`#${conversation.id}`} aria-current={conversation.id === "ingrid" ? "true" : undefined} />}
              >
                <ItemMedia>
                  <Avatar decorative>
                    <AvatarImage src={conversation.photo} />
                    <AvatarFallback />
                  </Avatar>
                </ItemMedia>
                <ItemContent>
                  <div className="flex items-baseline justify-between gap-2">
                    <ItemTitle>{conversation.name}</ItemTitle>
                    <span className="shrink-0 text-xs text-muted-foreground tabular-nums">{conversation.when}</span>
                  </div>
                  <ItemDescription className="line-clamp-1">{conversation.last}</ItemDescription>
                </ItemContent>
              </Item>
            ))}
          </ItemGroup>
        </div>

        <Card size="sm" className="min-w-0 flex-1">
          <CardHeader className="flex items-center gap-3">
            <Avatar decorative size="lg">
              <AvatarImage src={INGRID} />
              <AvatarFallback />
            </Avatar>
            <div className="flex min-w-0 flex-col gap-0.5">
              <CardTitle render={<h2 />}>Ingrid Solberg</CardTitle>
              <CardDescription>Your host at Fjordstova, Oct 18 to 23.</CardDescription>
            </div>
          </CardHeader>

          <Thread label="Messages with Ingrid Solberg" className="h-120">
            {rows.map((row) => {
              if (row.kind === "day") return <ThreadDay key={row.key} day={row.day} now={NOW} timeZone={ZONE} />;
              const post = posts.find((item) => item.id === row.key);
              if (!post) return null;
              const mine = post.from === "you";
              const delivery =
                mine && post.delivery && (post.delivery === "failed" || post.delivery === "pending" || post.id === lastMine)
                  ? post.delivery
                  : null;
              return (
                <ContextMenu key={post.id}>
                  <ContextMenuTrigger
                    className="select-text"
                    render={<Message mine={mine} position={row.position} author={mine ? "You" : "Ingrid Solberg"} />}
                  >
                    <MessageContent>
                      {post.images && (
                        <MessageImages
                          images={post.images.map((image) => (post.upload ? { ...image, upload: post.upload } : image))}
                          onRetry={() => retry(post)}
                        />
                      )}
                      {post.file && (
                        <MessageFile
                          name={post.file.name}
                          size={post.file.size}
                          {...(post.file.href ? { href: post.file.href } : {})}
                          {...(post.upload ? { upload: post.upload } : {})}
                          onRetry={() => retry(post)}
                        />
                      )}
                      {post.text && !post.quote && <MessageBubble>{post.text}</MessageBubble>}
                      {post.text && post.quote && (
                        <MessageBubble>
                          <MessageQuote author={post.quote.author}>{post.quote.text}</MessageQuote>
                          <MessageText>{post.text}</MessageText>
                        </MessageBubble>
                      )}
                      {post.reactions && post.reactions.length > 0 && (
                        <Reactions>
                          {post.reactions.map((item) => (
                            <Reaction
                              key={item.emoji}
                              emoji={item.emoji}
                              count={item.count}
                              pressed={item.mine}
                              names={item.names}
                              onPressedChange={(on) => react(post.id, item.emoji, on)}
                            />
                          ))}
                          <ReactionAdd onPick={(emoji) => react(post.id, emoji, true)} />
                        </Reactions>
                      )}
                      {delivery && (
                        <MessageFooter>
                          {/* An upload that failed has its Retry on the picture or the glyph. */}
                          <MessageStatus status={delivery} {...(post.upload ? {} : { onRetry: () => retry(post) })} />
                        </MessageFooter>
                      )}
                    </MessageContent>
                    <MessageAside>
                      {post.at !== undefined && <MessageTime value={post.at} timeZone={ZONE} />}
                      {!post.reactions?.length && (
                        <EmojiPickerPopover
                          side="top"
                          align={mine ? "end" : "start"}
                          onPick={(emoji) => react(post.id, emoji, true)}
                          trigger={<IconButton size="icon-sm" icon={<AddReactionIcon />} label="Add reaction" />}
                        />
                      )}
                    </MessageAside>
                  </ContextMenuTrigger>
                  <ContextMenuContent label="Message actions">
                    {QUICK.map((quick) => (
                      <ContextMenuItem key={quick.emoji} onClick={() => react(post.id, quick.emoji, true)}>
                        <span aria-hidden="true">{quick.emoji}</span>
                        {quick.name}
                      </ContextMenuItem>
                    ))}
                    {post.text && (
                      <>
                        <ContextMenuSeparator />
                        <ContextMenuItem onClick={() => void navigator.clipboard?.writeText(post.text ?? "")}>
                          Copy text
                        </ContextMenuItem>
                      </>
                    )}
                  </ContextMenuContent>
                </ContextMenu>
              );
            })}
            <ThreadTyping names={typing} />
          </Thread>

          <CardFooter>
            <Composer onSend={send}>
              <ComposerAttach accept="image/*,.pdf,.xlsx,.docx" />
              <ComposerAttachments />
              <ComposerInput aria-label="Message Ingrid Solberg" placeholder="Message Ingrid" />
              <ComposerSend />
            </Composer>
          </CardFooter>
        </Card>
        </div>
      </div>
    </TooltipProvider>
  );
}
```

Example: An assistant in a research tool: the reply thinks, shows its trace while it reads, streams its answer with a caret, and Stop keeps what it said (`docs/system/examples/thread/in-assistant.tsx`)

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

import { RetryIcon, ThumbsDownIcon, ThumbsUpIcon } from "@/components/cobalt/icon";
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { Composer, ComposerInput, ComposerSend } from "@/components/cobalt/ui/composer";
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 { Thread } from "@/components/cobalt/ui/thread";
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";

type Step = { title: string; done: string; status: TraceStatus; duration?: string };
type Turn = { id: string; question: string; reply: Reply; steps: Step[]; summary: string; total: string; rating: "good" | "bad" | null };

// What the stand-in assistant knows: the steps it takes and the answer it gives, in turn.
const SCRIPTS = [
  {
    summary: "Read 2 filings",
    total: "3.1 s",
    steps: [
      { title: "Searching EDGAR for Meridian IV", done: "Searched EDGAR for Meridian IV", duration: "0.9 s" },
      { title: "Reading the Form D/A of Nov 15", done: "Read the Form D/A of Nov 15", duration: "2.2 s" },
    ],
    answer:
      "Meridian Growth Partners IV reported $1.5B sold on its amended Form D/A of Nov 15, against a $1.2B target in August.\n\nThe last six weeks brought in $860M, more than half of the fund. The amendment does not name the new investors.",
  },
  {
    summary: "Searched 3 sources",
    total: "4.6 s",
    steps: [
      { title: "Searching EDGAR for Harbour Street", done: "Searched EDGAR for Harbour Street", duration: "0.8 s" },
      { title: "Reading the Q3 13F-HR", done: "Read the Q3 13F-HR", duration: "2.4 s" },
      { title: "Comparing with Q2", done: "Compared with Q2", duration: "1.4 s" },
    ],
    answer:
      "Harbour Street added eleven positions in Q3, most of them short-dated Treasuries, and sold two regional banks outright.\n\nThe book is 6% smaller by value, at $48.2B, though the count of positions rose from 181 to 192.",
  },
];

const first: Turn = {
  id: "t0",
  question: "What did Harbour Street file this week?",
  reply: {
    status: "done",
    text: "A 13F-HR for Q3, filed on Aug 14, and an amendment to its Q2 13F on Aug 16 that corrects two share counts. Nothing else this week.",
  },
  steps: [
    { title: "", done: "Searched EDGAR for Harbour Street", status: "done", duration: "0.7 s" },
    { title: "", done: "Read the filing index", status: "done", duration: "1.1 s" },
  ],
  summary: "Searched 1 source",
  total: "1.8 s",
  rating: null,
};

// An earlier question, answered from the first script.
const second: Turn = {
  id: "t1",
  question: "And Meridian IV, did it close?",
  reply: { status: "done", text: SCRIPTS[0]!.answer },
  steps: SCRIPTS[0]!.steps.map((step) => ({ ...step, status: "done" })),
  summary: SCRIPTS[0]!.summary,
  total: SCRIPTS[0]!.total,
  rating: "good",
};

export default function Example() {
  const [turns, setTurns] = useState<Turn[]>([first, second]);
  const timers = useRef<number[]>([]);
  const asked = useRef(0);
  useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const change = (id: string, edit: (turn: Turn) => Turn) =>
    setTurns((list) => list.map((turn) => (turn.id === id ? edit(turn) : turn)));
  const move = (id: string, event: ReplyEvent) => change(id, (turn) => ({ ...turn, reply: nextReply(turn.reply, event) }));

  // Plays a script into one turn: each step runs, then the answer comes a few words at a time.
  function play(id: string, script: (typeof SCRIPTS)[number]) {
    let at = 800;
    const later = (fn: () => void, wait: number) => {
      at += wait;
      timers.current.push(window.setTimeout(fn, at));
    };
    script.steps.forEach((step, index) => {
      later(
        () =>
          change(id, (turn) => ({
            ...turn,
            steps: script.steps.slice(0, index + 1).map((s, i) => ({ ...s, status: i < index ? "done" : "running" })),
          })),
        index === 0 ? 0 : 1000,
      );
    });
    later(() => change(id, (turn) => ({ ...turn, steps: turn.steps.map((s) => ({ ...s, status: "done" })) })), 1000);
    for (const word of script.answer.split(/(?<= )/)) later(() => move(id, { type: "words", text: word }), 45);
    later(() => move(id, { type: "finish" }), 45);
  }

  function ask(question: string) {
    const script = SCRIPTS[++asked.current % SCRIPTS.length] ?? SCRIPTS[0]!;
    const id = crypto.randomUUID();
    setTurns((list) => [...list, { id, question, reply: { status: "thinking" }, steps: [], summary: script.summary, total: script.total, rating: null }]);
    play(id, script);
  }

  function stop() {
    timers.current.forEach(clearTimeout);
    timers.current = [];
    setTurns((list) =>
      list.map((turn) => ({
        ...turn,
        reply: nextReply(turn.reply, { type: "stop" }),
        steps: turn.steps.map((step) => (step.status === "running" ? { ...step, status: "failed" as const } : step)),
      })),
    );
  }

  function retry(turn: Turn) {
    const script = SCRIPTS.find((s) => s.summary === turn.summary) ?? SCRIPTS[0]!;
    change(turn.id, (current) => ({ ...current, reply: { status: "thinking" }, steps: [], rating: null }));
    play(turn.id, script);
  }

  const streaming = turns.some((turn) => turn.reply.status === "thinking" || turn.reply.status === "streaming");

  return (
    <TooltipProvider>
      <Card size="sm" className="w-full max-w-3xl">
        <CardHeader>
          <CardTitle render={<h2 />}>Research assistant</CardTitle>
          <CardDescription>Answers from SEC filings, with the steps it took.</CardDescription>
        </CardHeader>
        <Thread label="Conversation with the research assistant" className="h-120">
          {turns.map((turn) => {
            const { reply } = turn;
            const text = reply.status === "thinking" ? "" : reply.text;
            const running = turn.steps.find((step) => step.status === "running");
            const working = reply.status === "thinking" || reply.status === "streaming";
            return [
              <Message key={`${turn.id}-q`} mine>
                <MessageContent>
                  <MessageBubble>{turn.question}</MessageBubble>
                </MessageContent>
              </Message>,
              <Message key={`${turn.id}-a`} agent author="Research assistant">
                <MessageContent>
                  {turn.steps.length === 0 ? (
                    reply.status === "thinking" && <MessageThinking />
                  ) : (
                    <Trace
                      summary={running ? running.title : turn.summary}
                      status={running ? "running" : "done"}
                      {...(running ? {} : { duration: turn.total })}
                    >
                      {turn.steps.map((step, index) => (
                        <TraceStep
                          key={index}
                          status={step.status}
                          title={step.status === "done" ? step.done : step.title}
                          {...(step.duration ? { duration: step.duration } : {})}
                          {...(step.status === "failed" ? { error: "Stopped before it finished." } : {})}
                        />
                      ))}
                    </Trace>
                  )}
                  {text && <MessageAnswer streaming={reply.status === "streaming"}>{text}</MessageAnswer>}
                  {reply.status === "stopped" && <MessageFooter>Stopped</MessageFooter>}
                  {!working && (
                    <MessageActions>
                      <CopyButton value={text} size="icon-sm" label="Copy answer" />
                      <IconButton size="icon-sm" icon={<RetryIcon />} label="Retry" onClick={() => retry(turn)} disabled={streaming} />
                      {(["good", "bad"] as const).map((value) => (
                        <IconButton
                          key={value}
                          size="icon-sm"
                          icon={value === "good" ? <ThumbsUpIcon /> : <ThumbsDownIcon />}
                          label={value === "good" ? "Good answer" : "Bad answer"}
                          aria-pressed={turn.rating === value}
                          onClick={() =>
                            change(turn.id, (current) => ({ ...current, rating: current.rating === value ? null : value }))
                          }
                          className="aria-pressed:text-foreground aria-pressed:[&_svg]:fill-current"
                        />
                      ))}
                    </MessageActions>
                  )}
                </MessageContent>
              </Message>,
            ];
          })}
        </Thread>
        <CardFooter>
          <Composer onSend={({ text }) => ask(text)} streaming={streaming} onStop={stop}>
            <ComposerInput aria-label="Ask the research assistant" placeholder="Ask about a fund or a filing" />
            <ComposerSend />
          </Composer>
        </CardFooter>
      </Card>
    </TooltipProvider>
  );
}
```

## Variants
Not applicable: Thread has one look; it takes the colour of the surface it sits on, and its edges fade in `--card` unless the host sets `--fade-from`.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| following | opened, or scrolled to within 48px of the end | read the newest message as it comes | it stays at the end as messages, pictures and the typing line arrive | by hand |
| reading | scrolled up past 48px | read; nothing moves | the row in view stays where it is through any change of height | by hand |
| new below | a message from someone else came while reading | press the count to go down | "2 new messages" with a down arrow, floating at the bottom | test |
| sent while reading | you send while reading | nothing | the thread goes to the end, where your message is | by hand |
| typing | `ThreadTyping names` is not empty | read on | "Maya is typing" and three fading dots on its held line | test |
| empty | no rows | write the first message | nothing in the scroller; the host puts an `Empty` beside it | by hand |

Example: Scroll up and press Receive: nothing you read moves, and a count at the bottom takes you to what came (`docs/system/examples/thread/state-new-messages.tsx`)

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

import { Button } from "@/components/cobalt/ui/button";
import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import { Thread } from "@/components/cobalt/ui/thread";
import { threadRows } from "@/lib/cobalt/messages";

const lines = [
  "Northgate's N-PORT is in.",
  "Net assets $3.2B for September.",
  "Treasuries are 41 percent of the book now.",
  "Up from 33 in June.",
  "Duration came down to 1.9 years.",
  "They sold most of the agency paper.",
  "Cash is 6 percent.",
  "I will put it in the weekly note.",
];

export default function Example() {
  const [messages, setMessages] = useState(() =>
    lines.map((text, index) => ({ id: `m${index}`, from: index % 3 === 2 ? "you" : "james", text })),
  );
  const receive = () =>
    setMessages((list) => [...list, { id: `m${list.length}`, from: "james", text: `Another note, number ${list.length + 1}.` }]);
  const rows = threadRows(messages);
  return (
    <div className="flex w-full max-w-lg flex-col gap-3">
      <div className="rounded-2xl bg-card">
        <Thread label="Messages with James Whitaker" className="h-72">
          {rows.map((row) =>
            row.kind === "message" ? (
              <Message key={row.key} mine={row.message.from === "you"} position={row.position}>
                <MessageContent>
                  <MessageBubble>{row.message.text}</MessageBubble>
                </MessageContent>
              </Message>
            ) : null,
          )}
        </Thread>
      </div>
      <Button variant="secondary" className="self-start" onClick={receive}>
        Receive a message
      </Button>
    </div>
  );
}
```

Example: Who is writing, as a quiet line that moves nothing when it comes and goes (`docs/system/examples/thread/state-typing.tsx`)

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

import { Message, MessageBubble, MessageContent } from "@/components/cobalt/ui/message";
import { Thread, ThreadTyping } from "@/components/cobalt/ui/thread";
import { Toggle } from "@/components/cobalt/ui/toggle";

export default function Example() {
  // Daniel is writing when the tile opens; the switch under the tile stops and starts him.
  const [typing, setTyping] = useState(true);
  return (
    <div className="flex w-full max-w-lg flex-col">
      <div className="rounded-2xl bg-card">
        <Thread label="Messages with Daniel Okafor" className="h-60">
          <Message mine author="You">
            <MessageContent>
              <MessageBubble>Is the deck ready for the client?</MessageBubble>
            </MessageContent>
          </Message>
          <Message author="Daniel Okafor" position="first">
            <MessageContent>
              <MessageBubble>The client moved the call to 4:30.</MessageBubble>
            </MessageContent>
          </Message>
          <Message author="Daniel Okafor" position="last">
            <MessageContent>
              <MessageBubble>I'm adding their questions to the deck now.</MessageBubble>
            </MessageContent>
          </Message>
          <Message mine author="You">
            <MessageContent>
              <MessageBubble>Can you send it before 4?</MessageBubble>
            </MessageContent>
          </Message>
          <ThreadTyping names={typing ? ["Daniel"] : []} />
        </Thread>
      </div>
      <div className="mt-4 flex flex-wrap items-center gap-2 border-t border-dashed pt-3">
        <Toggle size="sm" pressed={typing} onPressedChange={setTyping}>
          Daniel is typing
        </Toggle>
      </div>
    </div>
  );
}
```

### State precedence
- Following and reading: Not applicable: the reader is within 48px of the end or not.
- New below and following: following wins. Reaching the end clears the count.
- Typing and new below: both show. The typing line is a row at the end; the count floats over the thread.
- Sent while reading and new below: sent wins. The thread goes to the end and the count clears.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| a message arrives | announce | `animate-arrive`, `--t-arrive` on `--curve` | opacity, translate 4px | none; it is there |
| the count shows or hides | announce | `--t-pop` on `--curve` | opacity | none; it shows and hides at once |
| the count is pressed | input | the browser's smooth scroll | scroll position | an instant jump |
| someone is typing | announce | Tailwind `animate-pulse` per dot, offset by `--t-settle` | opacity | the dots hold still |

## Props

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

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `label` | `string` |  | The conversation's name for a screen reader: "Messages with Maya Chen". |
| `newLabel?` | `(count: number) => string` | `(count) => counted(count, { one: "new message", other: "new messages" })` |  |

Also accepts every native `<div>` attribute.

### ThreadDay

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `day` | `string` |  | The day, as YYYY-MM-DD, from `threadRows`. |
| `className?` | `string` |  |  |
| `locale?` | `string` |  |  |
| `now?` | `number` |  | The moment "today" is counted from. |
| `timeZone?` | `string` |  |  |

### ThreadTyping

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `names` | `readonly string[]` |  |  |
| `className?` | `string` |  |  |
| `label?` | `(names: readonly string[]) => string` | `typingWords` |  |

`label` names the log: "Messages with Maya Chen". `newLabel` words the count. Rows go in as direct children, from `threadRows`, with keys that stay the same from sending to sent. `ThreadDay` takes `day`, `now`, `locale` and `timeZone`. `ThreadTyping` takes `names` and `label`.

## Usage

### When to use
- A conversation that grows while it is open: a DM, a support chat, a conversation with an agent.

### When not to use
- An activity feed that is read top down, newest first. Use Timeline instead.
- A short history that does not grow while open. Use Message rows in a Card instead.

### Rules
- `rule/thread-new-waits-below`: When a message arrives while the reader is more than 48px from the end, add it at the end and let the `Thread` count say so, instead of scrolling to it, because a jump moves the line the person was reading. Evidence: person D37; principle heuristic: user control and freedom, nothing moves that you did not move. Check: probe in docs/system/stress/thread.tsx, the row in view keeps its offset when a message arrives.
  - Don't: `useEffect(() => box.scrollTo({ top: box.scrollHeight }), [messages])`
  - Do: `<Thread label="Messages with Maya Chen">{rows}</Thread>`
- `rule/thread-stable-keys`: When a sent message gets its server id, keep the `key` it had while sending, because the thread marks a new row as an arrival, and a new key makes it arrive twice and count as new. Evidence: principle heuristic: consistency and standards, one message is one row from sending to sent. Check: review of every row key in a thread.
  - Don't: `<Message key={message.serverId ?? message.tempId} />`
  - Do: `<Message key={message.clientId} />`
- `rule/thread-reactions-end-run`: When a message has reactions, pass `ends` to `threadRows` so it ends its run, because its reactions sit between it and the next bubble, and a tight corner facing a reaction row reads as a mistake. Evidence: principle heuristic: aesthetic and minimalist design, a joined corner must join something. Check: review of every `threadRows` call in a thread with reactions.
  - Don't: `threadRows(messages)` with reactions under some messages
  - Do: `threadRows(messages, { ends: (m) => m.reactions.length > 0 })`

### Content
- Follows `rule/writing-no-invented-numbers`.
- `rule/thread-label-names-person`: When naming the thread, say whose conversation it is, such as "Messages with Maya Chen", instead of "Chat" or "Conversation", because a screen reader lands in the log by its name. Evidence: principle wcag: 2.4.6 Headings and labels, a name says what it holds. Check: test `thread.test.tsx` renders the label on the log.
  - Don't: `<Thread label="Chat">`
  - Do: `<Thread label="Messages with Maya Chen">`

### Anti-slop
- `rule/thread-typing-no-bounce`: When showing that someone writes, use `ThreadTyping`, whose dots fade in place, instead of dots that bounce or scale in a bubble, because nothing in the system scales or bounces and a bubble that appears and goes moves the thread. Evidence: person D36, D37. Check: test `thread.test.tsx` checks the typing line has no scale.
  - Don't: `<span className="animate-bounce">...</span>`
  - Do: `<ThreadTyping names={["Maya"]} />`

### Limits
- `rule/thread-no-window`: When a thread holds more than 1,000 rendered messages, load older ones on demand above instead of rendering them all, because past that a send costs a frame. Evidence: measured a send with 1,000 messages takes 87ms to its second frame in a development build, docs/system/stress/thread.tsx at 1440. Check: probe in docs/system/stress/thread.tsx.
  - Don't: `rows.map(...)` over a 20,000-message history
  - Do: the newest 200 rows, and older pages added above as the reader reaches the top

## Accessibility
Rests on a native scrolling `div` with `role="log"`.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the thread | focuses the log | the log, with its outline | by hand |
| Arrow Up, Arrow Down, Page Up, Page Down, Home, End | the log | scrolls it | stays on the log | by hand |
| Enter | the count of new messages | scrolls to the end | stays on the count until it hides, then the log | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| scroller | log | `label` | `tabindex="0"`; polite by its role | each message as it is added, and the typing line's words | test |
| count | button | its words, "2 new messages" | `aria-hidden` and `tabindex="-1"` while it counts nothing | its words and "button" | test |
| day row | none, a `time` | its words, "Yesterday" | `dateTime` the day | its words, in reading order | test |
| typing dots | none | none | `aria-hidden` | nothing; the words beside them are read | test |

## Tokens
| Part | State | Token |
|---|---|---|
| scroller | all | `--card` for the edge fades, `--pad-popup` |
| count | shown | `--card`, `--elev-raised`, `--control-sm`, `--r-control`, `--t-pop` |
| day row, typing | all | `--muted-foreground` |
| arrival | arrived | `--t-arrive`, `--curve` |

## Related
- Message: one row of the thread.
- Composer: writes the next message under it.
- Timeline: an ordered history that does not grow while open.
- Inbox: the bell in a top bar that opens the person's notifications.
