# Message scroller

Follow new messages and revisit earlier turns.

## Preview

message-scroller-preview-1.jsx

```jsx
import { useState, useRef } from "react";
import { Composer } from "@/components/ui/composer";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import { Message, MessageBody, MessageMeta } from "@/components/ui/message";
import {
  MessageScrollerProvider,
  MessageScroller,
  MessageScrollerViewport,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerButton,
  MessageScrollerNavigation,
} from "@/components/ui/message-scroller";

export default function Example() {
  return (
    <>
      <MinimalMessageScroller />
    </>
  );
}

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

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

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

function MinimalMessageScroller({ history = false } = {}) {
  const [entries, setEntries] = useState(initialEntries);
  const id = useRef(0);
  return (
    <Chat
      label="Release discussion"
      style={{
        inlineSize: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatContent>
        <MessageScrollerProvider>
          <MessageScroller
            style={{
              blockSize: "20rem",
            }}
          >
            <MessageScrollerViewport label="Release discussion">
              <MessageScrollerContent>
                {entries.map((entry) => (
                  <MessageScrollerItem key={entry.id} messageId={entry.id}>
                    <Message actor={entry.actor} metadataAtRest>
                      <MessageBody>
                        {entry.text}
                        {entry.time && (
                          <MessageMeta placement="inline">
                            <time dateTime={entry.time.dateTime}>
                              {entry.time.label}
                            </time>
                          </MessageMeta>
                        )}
                      </MessageBody>
                    </Message>
                  </MessageScrollerItem>
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerNavigation
              items={entries.flatMap((entry, index) =>
                entry.actor === "user"
                  ? [
                      {
                        messageId: entry.id,
                        prompt: entry.text,
                        reply:
                          entries[index + 1]?.actor === "assistant"
                            ? entries[index + 1].text
                            : undefined,
                        metadata: entry.time && (
                          <time dateTime={entry.time.dateTime}>
                            {entry.time.label}
                          </time>
                        ),
                      },
                    ]
                  : [],
              )}
            />
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </ChatContent>
      <ChatFooter>
        <Composer
          label="Reply"
          onSubmit={({ text }) => {
            const next = `reply-${id.current++}`;
            const sentAt = /* @__PURE__ */ new Date();
            setEntries((current) => [
              ...current,
              {
                id: next,
                actor: "user",
                text,
                time: {
                  dateTime: sentAt.toISOString(),
                  label: sentAt.toLocaleString([], {
                    month: "short",
                    day: "numeric",
                    hour: "numeric",
                    minute: "2-digit",
                  }),
                },
              },
            ]);
          }}
        />
      </ChatFooter>
    </Chat>
  );
}

```

## Design guidance

Use Message scroller to follow a growing conversation. When someone scrolls up, keep their place and let them jump to the latest message. Use Scroll area for content that needs ordinary scrolling.

Add MessageScrollerNavigation for a turn index. The caller supplies each prompt, reply excerpt, and optional metadata; the component shares the existing viewport and jump behavior. Keep top/bottom buttons for edge navigation. Carousel indicators navigate slides and do not own transcript state.

### Accessibility

Name the keyboard-reachable viewport. It uses aria-live="off"; put summary announcements in a separate status region instead of announcing each streaming token. When a focused jump button becomes unavailable, focus returns to the viewport.

On desktop, turn navigation has one link tab stop. Up/Down and Home/End explore every turn; Enter jumps to and focuses the message. Hover and keyboard focus expand the mark and its nearest neighbors. The rail does not track the currently visible turn. On mobile, the whole bar group opens a bottom drawer with a grip and large turn rows. Toggle search to filter prompts and reply excerpts; Close search clears the filter. Select a row to close the drawer and focus its message. Preview Card provides supplementary excerpts on desktop hover/focus. Keep all previewed information in the destination transcript, including timestamps. Do not put unique information or controls in preview metadata.

## Installation

The registry includes Button for jump controls and Preview Card for turn previews. Add Message, Marker, Avatar, or Chat Composer if your layout uses them.

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

The Message-based examples below also use Message.

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

```text
src/components/ui/message-scroller.tsx
src/components/ui/message-scroller.css
src/components/ui/button.tsx
src/components/ui/button.css
```

## Basic usage

Wrap one scroll frame with MessageScrollerProvider, then render chronological rows inside MessageScrollerContent.

```tsx
import {
  MessageScroller,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Message, MessageBody } from "@/components/ui/message";

const messages = [
  { id: "launch-question", actor: "user", text: "Who owns staging?" },
  { id: "launch-answer", actor: "assistant", text: "Priya owns staging." },
] as const;

export function MessageScrollerExample() {
  return (
    <MessageScrollerProvider>
      <MessageScroller style={{ blockSize: "20rem" }}>
        <MessageScrollerViewport label="Support conversation">
          <MessageScrollerContent>
            {messages.map((message) => (
              <MessageScrollerItem key={message.id} messageId={message.id}>
                <Message actor={message.actor}>
                  <MessageBody>{message.text}</MessageBody>
                </Message>
              </MessageScrollerItem>
            ))}
          </MessageScrollerContent>
        </MessageScrollerViewport>
      </MessageScroller>
    </MessageScrollerProvider>
  );
}
```

## Structures

The provider owns scroll state. MessageScroller fills a height-constrained parent, so give that parent a usable block size. Its viewport owns scrolling and keyboard access; content owns chronological rows. Items can wrap messages, markers, or other content. The optional button uses the shared Button owner.

Give each row a stable messageId within its viewport. An HTML id remains caller-owned. Use scrollAnchor for a new turn that should settle at the reading edge.

- MessageScrollerProvider
  - MessageScroller
    - MessageScrollerViewport
      - MessageScrollerContent
        - MessageScrollerItem
    - MessageScrollerButton
    - MessageScrollerNavigation (optional turn index)

## Examples

Examples move from initial position to reading and jump controls, then turn anchors, history, and empty or alternate rows.

### Open at the first message

Use defaultScrollPosition="start" for a review transcript that should begin with its earliest row. Following remains off so later output does not move the reader.

message-scroller-open-at-the-first-message-2.jsx

```jsx
import { useState as useState4 } from "react";
import { Chat, ChatContent } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <Chat label="Launch planning chat" className="ui-message-scroller-demo">
      <Transcript
        turns={openingTurns}
        autoScroll={false}
        position="start"
        getSources={summarySources}
      />
    </Chat>
  );
}

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

```

message-scroller-open-at-the-first-message-2.css

```css
/* apps/web/src/demos/library/model-select.css */

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Reader position and new output

Scroll up to read. New output does not pull the reader away. Use the native jump button or the caller's explicit commands to return to the start or latest response.

message-scroller-reader-position-and-new-output-3.jsx

```jsx
import {
  useEffect as useEffect3,
  useRef as useRef3,
  useState as useState4,
} from "react";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <ChatExample
      seed={openingTurns}
      draft="Write the next launch update."
      anchorNewTurn={false}
      getSources={summarySources}
    />
  );
}

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

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

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

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

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

function ChatExample({
  seed = initial,
  draft = "",
  className = "",
  position = "end",
  anchorNewTurn = true,
  getSources,
}) {
  const [turns, setTurns] = useState4(seed);
  const [stream, setStream] = useState4(null);
  const serial = useRef3(0);
  useEffect3(() => {
    if (!stream) return;
    const timer = window.setTimeout(() => {
      const count = Math.min(stream.count + 4, stream.words.length);
      const finished = count === stream.words.length;
      setTurns((current) =>
        current.map((turn) =>
          turn.id === stream.id
            ? {
                ...turn,
                text: stream.words.slice(0, count).join(" "),
                status: finished ? undefined : "streaming",
              }
            : turn,
        ),
      );
      setStream(
        finished
          ? null
          : {
              ...stream,
              count,
            },
      );
    }, 280);
    return () => window.clearTimeout(timer);
  }, [stream]);
  return (
    <Chat
      className={`ui-message-scroller-demo ${""}`}
      label="Launch planning chat"
    >
      <Transcript turns={turns} position={"end"} getSources={getSources} />
      <ChatFooter>
        <ChatComposer
          defaultValue={"Write the next launch update."}
          status={stream ? "streaming" : "ready"}
          onSubmit={({ text, attachments }) => {
            const id = `reply-${++serial.current}`;
            const words =
              "Launch update: Priya is confirming the staging retry fix. Marta is reviewing rollout coverage. Leon is preparing the support handoff. Keep the launch decision pending until the staging run and coverage review pass. I will keep each owner visible in the update so the team can act before Friday.".split(
                " ",
              );
            setTurns((current) => [
              ...current,
              {
                id: `${id}-question`,
                actor: "user",
                author: "Rina",
                text: text || attachments.map((file) => file.name).join(", "),
                anchor: false,
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
              {
                id,
                actor: "assistant",
                author: "Sol 6.1",
                text: words.slice(0, 4).join(" "),
                status: "streaming",
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
            ]);
            setStream({
              id,
              words,
              count: 4,
            });
          }}
          onStop={() => {
            if (stream)
              setTurns((current) =>
                current.map((turn) =>
                  turn.id === stream.id
                    ? {
                        ...turn,
                        status: "stopped",
                      }
                    : turn,
                ),
              );
            setStream(null);
          }}
        />
      </ChatFooter>
    </Chat>
  );
}

```

message-scroller-reader-position-and-new-output-3.css

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

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Open at the last anchor

Choose defaultScrollPosition="last-anchor" to open at the last marked turn. Without an anchor, the viewport opens at the end; an empty transcript stays at the start.

message-scroller-open-at-the-last-anchor-4.jsx

```jsx
import { useState as useState4 } from "react";
import { Chat, ChatContent } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <Chat label="Launch planning chat" className="ui-message-scroller-demo">
      <Transcript
        turns={openingTurns.map((turn) => ({
          ...turn,
          anchor: turn.id === "next-question",
        }))}
        autoScroll={false}
        position="last-anchor"
        getSources={summarySources}
      />
    </Chat>
  );
}

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

```

message-scroller-open-at-the-last-anchor-4.css

```css
/* apps/web/src/demos/library/model-select.css */

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Jump to the first message

Set direction="start" when the control should return to the beginning of the transcript. The default direction="end" control is shown in the Preview and reading examples.

message-scroller-jump-to-the-first-message-5.jsx

```jsx
import { useState as useState4 } from "react";
import { Chat, ChatContent } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <Chat label="Launch planning chat" className="ui-message-scroller-demo">
      <Transcript
        turns={openingTurns}
        autoScroll={false}
        buttonDirection="start"
        getSources={summarySources}
      />
    </Chat>
  );
}

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

```

message-scroller-jump-to-the-first-message-5.css

```css
/* apps/web/src/demos/library/model-select.css */

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### New turn anchor

Mark the first row of a new turn. As that turn grows, the viewport keeps its start visible and leaves room below it.

message-scroller-new-turn-anchor-6.jsx

```jsx
import {
  useEffect as useEffect3,
  useRef as useRef3,
  useState as useState4,
} from "react";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  return (
    <ChatExample
      draft="What changed since the last update?"
      getSources={summarySources}
    />
  );
}

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

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

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

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

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

function ChatExample({
  seed = initial,
  draft = "",
  className = "",
  position = "end",
  anchorNewTurn = true,
  getSources,
}) {
  const [turns, setTurns] = useState4(seed);
  const [stream, setStream] = useState4(null);
  const serial = useRef3(0);
  useEffect3(() => {
    if (!stream) return;
    const timer = window.setTimeout(() => {
      const count = Math.min(stream.count + 4, stream.words.length);
      const finished = count === stream.words.length;
      setTurns((current) =>
        current.map((turn) =>
          turn.id === stream.id
            ? {
                ...turn,
                text: stream.words.slice(0, count).join(" "),
                status: finished ? undefined : "streaming",
              }
            : turn,
        ),
      );
      setStream(
        finished
          ? null
          : {
              ...stream,
              count,
            },
      );
    }, 280);
    return () => window.clearTimeout(timer);
  }, [stream]);
  return (
    <Chat
      className={`ui-message-scroller-demo ${""}`}
      label="Launch planning chat"
    >
      <Transcript turns={turns} position={"end"} getSources={getSources} />
      <ChatFooter>
        <ChatComposer
          defaultValue={"What changed since the last update?"}
          status={stream ? "streaming" : "ready"}
          onSubmit={({ text, attachments }) => {
            const id = `reply-${++serial.current}`;
            const words =
              "Launch update: Priya is confirming the staging retry fix. Marta is reviewing rollout coverage. Leon is preparing the support handoff. Keep the launch decision pending until the staging run and coverage review pass. I will keep each owner visible in the update so the team can act before Friday.".split(
                " ",
              );
            setTurns((current) => [
              ...current,
              {
                id: `${id}-question`,
                actor: "user",
                author: "Rina",
                text: text || attachments.map((file) => file.name).join(", "),
                anchor: true,
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
              {
                id,
                actor: "assistant",
                author: "Sol 6.1",
                text: words.slice(0, 4).join(" "),
                status: "streaming",
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
            ]);
            setStream({
              id,
              words,
              count: 4,
            });
          }}
          onStop={() => {
            if (stream)
              setTurns((current) =>
                current.map((turn) =>
                  turn.id === stream.id
                    ? {
                        ...turn,
                        status: "stopped",
                      }
                    : turn,
                ),
              );
            setStream(null);
          }}
        />
      </ChatFooter>
    </Chat>
  );
}

```

message-scroller-new-turn-anchor-6.css

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

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Load earlier history

Prepend stable rows while the first visible row keeps its position. messageId values must stay stable across the update.

message-scroller-load-earlier-history-7.jsx

```jsx
import { useState as useState4 } from "react";
import { Button as Button2 } from "@/components/ui/button";
import { Chat, ChatContent } from "@/components/ui/chat";
import {
  CitationList as CitationList2,
  CitationProvider as CitationProvider2,
} from "@/components/ui/citation";
import {
  MessageAvatar as MessageAvatar2,
  MessageHeader as MessageHeader2,
} from "@/components/ui/message";
import { MessageSender as MessageSender2 } from "@/components/ui/message-sender";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  const [loaded, setLoaded] = useState4(false);
  return (
    <Chat label="Launch planning chat" className="ui-message-scroller-demo">
      <Transcript
        turns={[...(loaded ? earlier : []), ...openingTurns]}
        autoScroll={false}
        position="start"
        getSources={summarySources}
        getIdentity={otherSpeaker}
        leading={
          <div>
            <Button2
              variant="ghost"
              size="sm"
              disabled={loaded}
              onClick={() => setLoaded(true)}
            >
              {loaded ? "Start of conversation" : "Load earlier messages"}
            </Button2>
          </div>
        }
      />
    </Chat>
  );
}

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function summarySources(turn) {
  if (turn.id !== "summary") return;
  const sources = [
    "Release runbook",
    "Staging status",
    "Support handoff",
    "Coverage review",
    "Launch checklist",
  ].map((title, index) => ({
    id: `launch-source-${index}`,
    type: "document",
    title,
    document: {
      name: `${title.toLowerCase().replaceAll(" ", "-")}.md`,
    },
  }));
  return {
    parts: sources.map((source) => ({
      type: "source",
      id: source.id,
      source,
    })),
    content: (
      <CitationProvider2 sources={sources} mode="provided">
        <CitationList2 mode="provided" />
      </CitationProvider2>
    ),
  };
}

function otherSpeaker(turn) {
  if (turn.actor !== "user" || turn.author === "Rina") return;
  return {
    kind: "human",
    avatar: (
      <MessageAvatar2>
        <MessageSender2
          name={turn.author}
          kind="human"
          seed={turn.authorId ?? turn.author}
          showName={false}
        />
      </MessageAvatar2>
    ),
    header: <MessageHeader2>{turn.author}</MessageHeader2>,
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

var earlier = [
  {
    id: "prior-priya",
    sentAt: "2026-11-21T09:00:00+07:00",
    actor: "user",
    author: "Priya",
    text: "The staging retry failed once overnight. I\u2019m checking the fix before Friday.",
  },
  {
    id: "prior-sol",
    actor: "assistant",
    author: "Sol 6.1",
    text: "I\u2019ve kept staging open in the launch checklist. Priya owns the next verification run.",
  },
];

```

message-scroller-load-earlier-history-7.css

```css
/* apps/web/src/demos/library/model-select.css */

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Empty conversation

Keep the empty prompt and composer in the caller's layout. The scroller remains a valid, named viewport with no message rows.

message-scroller-empty-conversation-8.jsx

```jsx
import {
  useEffect as useEffect3,
  useRef as useRef3,
  useState as useState4,
} from "react";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  const seed = [];
  const [turns, setTurns] = useState4(seed);
  const [stream, setStream] = useState4(null);
  const serial = useRef3(0);
  useEffect3(() => {
    if (!stream) return;
    const timer = window.setTimeout(() => {
      const count = Math.min(stream.count + 4, stream.words.length);
      const finished = count === stream.words.length;
      setTurns((current) =>
        current.map((turn) =>
          turn.id === stream.id
            ? {
                ...turn,
                text: stream.words.slice(0, count).join(" "),
                status: finished ? undefined : "streaming",
              }
            : turn,
        ),
      );
      setStream(
        finished
          ? null
          : {
              ...stream,
              count,
            },
      );
    }, 280);
    return () => window.clearTimeout(timer);
  }, [stream]);
  return (
    <Chat
      className={`ui-message-scroller-demo ${"ui-message-scroller-demo--empty"}`}
      label="Launch planning chat"
    >
      <Transcript turns={turns} position={"end"} getSources={undefined} />
      <ChatFooter>
        <ChatComposer
          defaultValue={""}
          status={stream ? "streaming" : "ready"}
          onSubmit={({ text, attachments }) => {
            const id = `reply-${++serial.current}`;
            const words =
              "Launch update: Priya is confirming the staging retry fix. Marta is reviewing rollout coverage. Leon is preparing the support handoff. Keep the launch decision pending until the staging run and coverage review pass. I will keep each owner visible in the update so the team can act before Friday.".split(
                " ",
              );
            setTurns((current) => [
              ...current,
              {
                id: `${id}-question`,
                actor: "user",
                author: "Rina",
                text: text || attachments.map((file) => file.name).join(", "),
                anchor: true,
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
              {
                id,
                actor: "assistant",
                author: "Sol 6.1",
                text: words.slice(0, 4).join(" "),
                status: "streaming",
                sentAt: /* @__PURE__ */ new Date().toISOString(),
              },
            ]);
            setStream({
              id,
              words,
              count: 4,
            });
          }}
          onStop={() => {
            if (stream)
              setTurns((current) =>
                current.map((turn) =>
                  turn.id === stream.id
                    ? {
                        ...turn,
                        status: "stopped",
                      }
                    : turn,
                ),
              );
            setStream(null);
          }}
        />
      </ChatFooter>
    </Chat>
  );
}

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

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

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

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

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

```

message-scroller-empty-conversation-8.css

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

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Human and agent messages

Message, marker, and participant rows share one chronological scroll surface. A marker can also carry scrollAnchor when an event should become the reading point.

message-scroller-human-and-agent-messages-9.jsx

```jsx
import { useState as useState4 } from "react";
import { Chat, ChatContent } from "@/components/ui/chat";
import { Marker as Marker2 } from "@/components/ui/marker";
import {
  MessageAvatar as MessageAvatar2,
  MessageHeader as MessageHeader2,
} from "@/components/ui/message";
import { MessageSender as MessageSender2 } from "@/components/ui/message-sender";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerNavigation,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { Fragment } from "react";
import {
  Message,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageMeta,
} from "@/components/ui/message";
import {
  MessageActions,
  MessageActionMenu,
} from "@/components/ui/message-actions";
import { MessageParts } from "@/components/ui/message-parts";

export default function Example() {
  const turns = [
    {
      id: "marta",
      sentAt: "2026-11-21T09:13:00+07:00",
      actor: "user",
      author: "Marta",
      authorId: "human-marta",
      text: "I\u2019ll own rollout coverage.",
    },
    {
      id: "sol",
      actor: "assistant",
      author: "Sol 6.1",
      authorId: "agent-sol-61",
      text: "Marta owns rollout coverage. Staging and support still need an owner.",
    },
    {
      id: "rina",
      sentAt: "2026-11-21T09:15:00+07:00",
      actor: "user",
      author: "Rina",
      authorId: "human-rina",
      text: "I\u2019ll ask Priya to take staging.",
    },
  ];
  return (
    <Chat label="Launch planning chat" className="ui-message-scroller-demo">
      <Transcript
        turns={turns}
        autoScroll={false}
        position="start"
        getIdentity={otherSpeaker}
        leading={
          <MessageScrollerItem messageId="joined">
            <Marker2 variant="separator" kind="person-joined">
              Marta joined
            </Marker2>
          </MessageScrollerItem>
        }
      />
    </Chat>
  );
}

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

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

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

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

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

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

var initial = [
  {
    id: "question",
    sentAt: "2026-11-21T09:05:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Summarize the launch risks. Keep the owners visible.",
  },
  {
    id: "summary",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Three risks need an owner before Friday: staging stability, rollout coverage, and support handoff.\n\nStaging \u2014 Priya will confirm the retry fix.\n\nRollout \u2014 Marta will check the staged release.\n\nSupport \u2014 Leon will prepare the launch reply.",
  },
];

var openingTurns = [
  ...initial,
  {
    id: "next-question",
    sentAt: "2026-11-21T09:08:00+07:00",
    actor: "user",
    author: "Rina",
    text: "What needs to happen before we approve the rollout?",
  },
  {
    id: "next-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Priya needs one clean staging run. Marta needs a named reviewer for each rollout region.\n\nLeon can prepare the support handoff now. Keep the launch decision pending until staging and coverage are confirmed.",
  },
  {
    id: "final-question",
    sentAt: "2026-11-21T09:11:00+07:00",
    actor: "user",
    author: "Rina",
    text: "Turn those risks into a weekly update.",
  },
  {
    id: "final-answer",
    actor: "assistant",
    author: "Sol 6.1",
    text: "Launch update\n\nStaging: Priya is checking the retry fix.\n\nRollout: Marta is confirming regional coverage.\n\nSupport: Leon is preparing the handoff.\n\nNext decision: approve the rollout after the staging run and coverage review pass.",
  },
];

function otherSpeaker(turn) {
  if (turn.actor !== "user" || turn.author === "Rina") return;
  return {
    kind: "human",
    avatar: (
      <MessageAvatar2>
        <MessageSender2
          name={turn.author}
          kind="human"
          seed={turn.authorId ?? turn.author}
          showName={false}
        />
      </MessageAvatar2>
    ),
    header: <MessageHeader2>{turn.author}</MessageHeader2>,
  };
}

function normalizedMessage(turn, sourceParts = []) {
  return {
    id: turn.id,
    actor: turn.actor,
    createdAt: turn.sentAt,
    author: {
      id: turn.authorId ?? turn.author,
      name: turn.author,
      kind: turn.actor === "user" ? "human" : "agent",
    },
    parts: [
      ...(turn.actor === "assistant"
        ? [
            {
              type: "activity",
              id: `${turn.id}-activity`,
              event: {
                id: `${turn.id}-review`,
                kind: "review",
                state:
                  turn.status === "streaming"
                    ? "active"
                    : turn.status === "stopped"
                      ? "cancelled"
                      : "complete",
                label: "Sol 6.1",
                description: "Launch planning response",
              },
            },
          ]
        : []),
      {
        type: "text",
        text: turn.text,
      },
      ...sourceParts,
    ],
    ...(turn.status
      ? {
          status: turn.status,
        }
      : {}),
  };
}

function Transcript({
  turns,
  autoScroll = true,
  position = "end",
  buttonDirection = "end",
  leading,
  getSources,
  getIdentity,
}) {
  const [votes, setVotes] = useState4({});
  const [feedback, setFeedback] = useState4("");
  const share = async (text) => {
    if (!navigator.share) {
      setFeedback("Sharing is not available in this browser.");
      return;
    }
    try {
      await navigator.share({
        title: "Launch planning",
        text,
      });
    } catch {
      setFeedback("Sharing was cancelled.");
    }
  };
  const download = (text) => {
    const url = URL.createObjectURL(
      new Blob([text], {
        type: "text/plain",
      }),
    );
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "launch-planning.txt";
    anchor.click();
    URL.revokeObjectURL(url);
  };
  return (
    <ChatContent>
      <MessageScrollerProvider
        autoScroll={autoScroll}
        defaultScrollPosition={position}
      >
        <MessageScroller>
          <MessageScrollerViewport label="Launch planning conversation">
            <MessageScrollerContent>
              {leading}
              {!turns.length && (
                <div className="ui-message-scroller-empty">
                  What should we work on?
                </div>
              )}
              {turns.map((turn) => {
                const sources = getSources?.(turn);
                const item = normalizedMessage(turn, sources?.parts);
                return (
                  <MessageScrollerItem
                    key={turn.id}
                    messageId={turn.id}
                    scrollAnchor={turn.anchor}
                  >
                    <ActionConversationMessageFrame
                      item={item}
                      self={
                        turn.actor === "user"
                          ? turn.author === "Rina"
                          : undefined
                      }
                      metadataAtRest
                      renderTimestamp={
                        turn.actor === "user" ? messageTimestamp : undefined
                      }
                      identity={getIdentity?.(turn)}
                      sources={sources?.content}
                      actions={
                        turn.actor === "assistant"
                          ? {
                              vote: votes[turn.id],
                              onVote: (vote) =>
                                setVotes((current) => ({
                                  ...current,
                                  [turn.id]: vote,
                                })),
                              onShare: () => void share(turn.text),
                              onDownload: () => download(turn.text),
                            }
                          : undefined
                      }
                    />
                  </MessageScrollerItem>
                );
              })}
            </MessageScrollerContent>
            <span className="ui-sr-only" role="status">
              {feedback}
            </span>
          </MessageScrollerViewport>
          <MessageScrollerNavigation
            items={turns.flatMap((turn, index) =>
              turn.actor === "user"
                ? [
                    {
                      messageId: turn.id,
                      prompt: turn.text,
                      metadata:
                        turn.sentAt &&
                        messageTimestamp(new Date(turn.sentAt), true),
                      reply:
                        turns[index + 1]?.actor === "assistant"
                          ? turns[index + 1].text
                          : undefined,
                    },
                  ]
                : [],
            )}
          />
          <MessageScrollerButton direction={buttonDirection} />
        </MessageScroller>
      </MessageScrollerProvider>
    </ChatContent>
  );
}

```

message-scroller-human-and-agent-messages-9.css

```css
/* apps/web/src/demos/library/model-select.css */

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

/* apps/web/src/demos/library/message-scroller-demo.css */
.ui-message-scroller-demo {
  display: flex;
  flex-direction: column;
  inline-size: 100%;
  min-inline-size: 0;
  block-size: 24rem;
}
.ui-message-scroller-demo--preview {
  block-size: 26rem;
}
.ui-message-scroller-demo--thumbnail {
  block-size: 12rem;
}
.ui-message-scroller-demo--empty {
  block-size: 18rem;
}
.ui-message-scroller-demo .ui-message-scroller {
  flex: 1 1 auto;
  min-block-size: 0;
  block-size: auto;
}
.ui-message-scroller-empty {
  display: grid;
  flex: 1;
  place-items: center;
  color: var(--muted-foreground);
  text-align: center;
  min-block-size: 10rem;
}

```

### Long turn index

The rail shows up to seven recent turns at rest. Hover or keyboard focus reveals the full index without moving the transcript. Long histories scroll inside the expanded rail. Select a mark to revisit its turn.

message-scroller-long-turn-index-10.jsx

```jsx
import { useState, useRef } from "react";
import { Composer } from "@/components/ui/composer";
import { Chat, ChatContent, ChatFooter } from "@/components/ui/chat";
import { Message, MessageBody, MessageMeta } from "@/components/ui/message";
import {
  MessageScrollerProvider,
  MessageScroller,
  MessageScrollerViewport,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerButton,
  MessageScrollerNavigation,
} from "@/components/ui/message-scroller";

export default function Example() {
  return (
    <>
      <MinimalMessageScroller history />
    </>
  );
}

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

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

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

function MinimalMessageScroller({ history = false } = {}) {
  const [entries, setEntries] = useState(historyEntries);
  const id = useRef(0);
  return (
    <Chat
      label="Release discussion"
      style={{
        inlineSize: "100%",
        maxInlineSize: 480,
      }}
    >
      <ChatContent>
        <MessageScrollerProvider>
          <MessageScroller
            style={{
              blockSize: "20rem",
            }}
          >
            <MessageScrollerViewport label="Release discussion">
              <MessageScrollerContent>
                {entries.map((entry) => (
                  <MessageScrollerItem key={entry.id} messageId={entry.id}>
                    <Message actor={entry.actor} metadataAtRest>
                      <MessageBody>
                        {entry.text}
                        {entry.time && (
                          <MessageMeta placement="inline">
                            <time dateTime={entry.time.dateTime}>
                              {entry.time.label}
                            </time>
                          </MessageMeta>
                        )}
                      </MessageBody>
                    </Message>
                  </MessageScrollerItem>
                ))}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerNavigation
              items={entries.flatMap((entry, index) =>
                entry.actor === "user"
                  ? [
                      {
                        messageId: entry.id,
                        prompt: entry.text,
                        reply:
                          entries[index + 1]?.actor === "assistant"
                            ? entries[index + 1].text
                            : undefined,
                        metadata: entry.time && (
                          <time dateTime={entry.time.dateTime}>
                            {entry.time.label}
                          </time>
                        ),
                      },
                    ]
                  : [],
              )}
            />
            <MessageScrollerButton />
          </MessageScroller>
        </MessageScrollerProvider>
      </ChatContent>
      <ChatFooter>
        <Composer
          label="Reply"
          onSubmit={({ text }) => {
            const next = `reply-${id.current++}`;
            const sentAt = /* @__PURE__ */ new Date();
            setEntries((current) => [
              ...current,
              {
                id: next,
                actor: "user",
                text,
                time: {
                  dateTime: sentAt.toISOString(),
                  label: sentAt.toLocaleString([], {
                    month: "short",
                    day: "numeric",
                    hour: "numeric",
                    minute: "2-digit",
                  }),
                },
              },
            ]);
          }}
        />
      </ChatFooter>
    </Chat>
  );
}

```

## API reference

### Provider and frame

Provider and frame properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| autoScroll | boolean | false | Follows transcript growth only while the reader is at the end and has no active reading intent. |
| defaultScrollPosition | start \| end \| last-anchor | end | Sets the opening position. last-anchor uses the last MessageScrollerItem marked scrollAnchor and falls back to end. |
| scrollPreviousItemPeek | number | 64 | Pixels of previous-turn context retained above a newly anchored prompt. Set 0 for exact top alignment. |
| resetKey | string | — | Reinitializes the viewport when the conversation identity changes. |
| MessageScroller | div props + ref | — | Fills its height-constrained parent and clips overflow; accepts native div attributes and ref. |
| MessageScrollerViewport.label | string | Conversation messages | Names the keyboard-reachable scrolling region. |
| useMessageScroller(options) | MessageScrollerHandle | — | Low-level Ghost controller retained for Conversation. Options are follow: when-at-end \| never, initialPosition: start \| end \| last-anchor, optional resetKey and previousItemPeek (default 0); it exposes viewportRef, contentRef, edge state, and start/latest/item commands. |

### Content and item

Content and item properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| MessageScrollerContent | div props + ref | — | Contains rows in chronological DOM order and owns anchor padding. |
| messageId (required) | string | — | Stable identifier used by jump commands, new-turn anchoring, and history preservation. |
| scrollAnchor | boolean | false | Marks this row as a new-turn anchor. It does not depend on the row's message role. |
| MessageScrollerItem | div props + ref | — | Wraps a message, marker, tool result, or other chronological row. |

### Controls

useMessageScrollerControls must be called under MessageScrollerProvider. jumpToMessage does nothing when the id is not mounted. Direct start and message jumps pause automatic following; jumpToLatest returns to the live edge and resumes following only when autoScroll is true.

Jump buttons sit on the right and use an arrow, size="icon-sm", and the shared variant="glass" by default. Pass children to show a custom label. The turn explorer floats over the transcript without reserving message width.

Control properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| jumpToLatest() | () => void | — | Moves to the end and restores opted-in following. |
| jumpToStart() | () => void | — | Moves to the first row and pauses following. |
| jumpToMessage(messageId) | (messageId: string) => void | — | Moves to the identified mounted row and pauses following. |
| isAway / isAtStart | boolean | — | Reports whether the viewport has scrollable content away from the end or is at its start edge. |
| MessageScrollerButton.direction | start \| end | end | Shows the native Button jump control at the matching edge when movement is available. It is disabled and removed from tab order at that edge. |
| MessageScrollerButton.dataSlot | string | message-scroller-button | Sets the button's data-slot marker when a composed facade must preserve its existing slot selector. |

### Turn navigation

Place MessageScrollerNavigation beside the viewport, inside the same provider and MessageScroller. Pass the user row's messageId, a plain-text prompt, an optional plain-text reply, and optional metadata. The rail shares the conversation's normal inline padding: standalone scrollers use 16px by default and 12px on narrow screens, while Chat keeps its existing content padding. Marks are capped to fit inside that padding, leaving a small clear space from the message edge without adding a separate right-side gutter. Applications can set --ui-message-scroller-padding-inline on MessageScroller when their normal conversation padding differs. At rest, the rail shows up to seven recent turns. Hover or focus reveals every turn, with internal scrolling when the index exceeds the available height.

```jsx
<MessageScrollerNavigation
  items={[
    {
      messageId: "launch-question",
      prompt: "Who owns staging?",
      reply: "Priya owns staging.",
      metadata: <time dateTime="2026-11-10T09:11:00+07:00">9:11 AM</time>,
    },
  ]}
/>
```

The preview shows one prompt line and up to three reply lines. It updates as caller data changes. Omit a missing reply or timestamp instead of inventing completion or a date. Supply an attachment's descriptive name as the prompt when there is no user text. The caller chooses which reply to summarize when a turn has several agents or branches.

Only mounted MessageScrollerItem rows are navigable. Unmounted history is unavailable; virtualized applications should load the target through their own controls before offering this index. Empty lists render nothing. Empty and duplicate IDs are ignored, keeping the first entry. Use unique message IDs inside each viewport. Item DOM IDs are generated uniquely unless an explicit id is supplied.

Turn navigation properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| items (required) | readonly MessageScrollerNavigationItem[] | — | Caller-owned turns in transcript order. Updates excerpts without changing transcript data. |
| messageId (required) | string | — | Identifies the mounted user row. Activation uses the existing jump command and focuses that row. |
| prompt (required) | string | — | Full accessible link label and single-line preview. Whitespace-only text falls back to the turn number. |
| reply | string | — | Optional reply excerpt, visually clamped to three lines. |
| metadata | ReactNode | — | Optional supplementary text such as a timestamp; keep it available at the linked destination too. |
| aria-label | string | Conversation turns | Accessible name for the navigation landmark. |
| ...props / ref | nav props / HTMLElement ref | — | Native attributes and ref are forwarded. Prevent the default key event to override internal traversal. |

MessageScroller, MessageScrollerViewport, MessageScrollerContent, and MessageScrollerItem forward native div attributes and HTMLDivElement refs. The viewport defaults to role="region", tabIndex={0}, and label "Conversation messages"; override role or tabIndex when your surrounding semantics require it. Items accept native div props/ref and default tabIndex to -1. MessageScrollerButton forwards Button props and an HTMLButtonElement ref; direction defaults to "end", dataSlot to "message-scroller-button", size to "icon-sm", and variant to "glass".
