Index of every page on this site: llms.txt
All skills
assistant-ui avatar

/primitives

@b0609e6
by assistant-uiassistant-ui/skills29 stars
7
Run it yourself

Builds and customizes assistant-ui chat UI from composable, unstyled @assistant-ui/react primitives: ThreadPrimitive, ComposerPrimitive (with Unstable_TriggerPopover for mentions and slash commands), MessagePrimitive and MessagePartPrimitive, ActionBarPrimitive, BranchPickerPrimitive, AttachmentPrimitive, ErrorPrimitive, AssistantModalPrimitive, ChainOfThoughtPrimitive, SelectionToolbarPrimitive, SuggestionPrimitive, QueueItemPrimitive, and the ThreadList primitives. Use when assembling or styling a custom Thread, Composer, message list, action bar, branch picker, or suggestion grid; wiring composer input, dictation, quoting, or attachments; or handling editing, branching, virtualization, scrolling, or chain of thought UI. Covers MessagePrimitive.Parts render functions per part type, groupPartByType, AuiIf in selector form, and the unstyled gotchas (AssistantRuntimeProvider, className). For prebuilt UI use setup, for the styled catalog use elements, for multi-thread sidebars use thread-list.

Use this Skill: https://skilld.dev/gh/assistant-ui/skills/primitives

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesmessages.md

≈2.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Message flows and long threads

Messages can be edited and branched without replacing the rest of the primitive tree. This reference covers editing, branch navigation, timing metadata, large thread rendering, scroll behavior, and image parts.

Contents

Editing

import {
  ActionBarPrimitive,
  ComposerPrimitive,
  MessagePrimitive,
  ThreadPrimitive,
  useAui,
} from "@assistant-ui/react";

function ThreadMessages() {
  return (
    <ThreadPrimitive.Messages>
      {({ message }) => {
        if (message.role === "user" && message.composer.isEditing) {
          return <UserEditComposer />;
        }
        return message.role === "user" ? <UserMessage /> : <AssistantMessage />;
      }}
    </ThreadPrimitive.Messages>
  );
}

function UserMessage() {
  return (
    <MessagePrimitive.Root>
      <MessagePrimitive.Parts />
      <ActionBarPrimitive.Root>
        <ActionBarPrimitive.Edit>Edit</ActionBarPrimitive.Edit>
      </ActionBarPrimitive.Root>
    </MessagePrimitive.Root>
  );
}

function UserEditComposer() {
  return (
    <MessagePrimitive.Root>
      <ComposerPrimitive.Root>
        <ComposerPrimitive.Input />
        <ComposerPrimitive.Cancel>Cancel</ComposerPrimitive.Cancel>
        <ComposerPrimitive.Send>Save</ComposerPrimitive.Send>
      </ComposerPrimitive.Root>
    </MessagePrimitive.Root>
  );
}

function EditButton() {
  const aui = useAui();
  return <button onClick={() => aui.composer.beginEdit()}>Edit</button>;
}

ActionBarPrimitive.Edit calls aui.composer.beginEdit() for the current user message. The edit composer must render within that message's MessagePrimitive.Root, where the same composer primitives save the replacement or Cancel restores the original text. Editing during an active assistant stream cancels that run and starts a new branch. Use AuiIf condition={(s) => !s.thread.isRunning} if the product should block that action.

Branching

import {
  ActionBarPrimitive,
  BranchPickerPrimitive,
  MessagePrimitive,
  useAui,
} from "@assistant-ui/react";

function AssistantMessage() {
  return (
    <MessagePrimitive.Root>
      <MessagePrimitive.Parts />
      <BranchPickerPrimitive.Root hideWhenSingleBranch>
        <BranchPickerPrimitive.Previous>Previous</BranchPickerPrimitive.Previous>
        <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />
        <BranchPickerPrimitive.Next>Next</BranchPickerPrimitive.Next>
      </BranchPickerPrimitive.Root>
      <ActionBarPrimitive.Root>
        <ActionBarPrimitive.Reload>Regenerate</ActionBarPrimitive.Reload>
      </ActionBarPrimitive.Root>
    </MessagePrimitive.Root>
  );
}

function BranchButton({ branchId }: { branchId: string }) {
  const aui = useAui();
  return (
    <button onClick={() => aui.message.switchToBranch({ branchId })}>
      Open branch
    </button>
  );
}

Editing a user message and reloading an assistant message create branches. BranchPickerPrimitive automatically disables movement at a boundary and while the thread is running unless the runtime supports switching during a run. aui.message.switchToBranch({ branchId }) needs a MessagePrimitive.Root context and a branch id from the current message's branch data.

Message timing

import { useMessageTiming } from "@assistant-ui/react";

function MessageTiming() {
  const timing = useMessageTiming();
  if (!timing?.totalStreamTime) return null;

  return (
    <span>
      {Math.round(timing.totalStreamTime)}ms
      {timing.tokensPerSecond != null && `, ${timing.tokensPerSecond.toFixed(1)} tok/s`}
    </span>
  );
}

Use useMessageTiming inside an assistant MessagePrimitive.Root. It returns undefined for a non assistant message or when the runtime has no data. streamStartTime, firstTokenTime, totalStreamTime, tokenCount, tokensPerSecond, totalChunks, and toolCallCount support a custom status label. AI SDK runtimes collect elapsed timing automatically, while token throughput requires usage metadata from the route.

Virtualization

import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
  ThreadPrimitive,
  useAuiState,
} from "@assistant-ui/react";

const MESSAGE_COMPONENTS = { UserMessage, AssistantMessage };

function VirtualizedMessages() {
  const scrollRef = useRef<HTMLDivElement>(null);
  const messageCount = useAuiState((s) => s.thread.messages.length);
  const virtualizer = useVirtualizer({
    count: messageCount,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 120,
    overscan: 5,
  });
  const items = virtualizer.getVirtualItems();
  const paddingTop = items[0]?.start ?? 0;
  const paddingBottom = Math.max(
    0,
    virtualizer.getTotalSize() - (items.at(-1)?.end ?? 0),
  );

  return (
    <ThreadPrimitive.ViewportProvider>
      <div ref={scrollRef} className="h-full overflow-y-auto">
        <div style={{ paddingTop, paddingBottom }}>
          {items.map((item) => (
            <div key={item.key} ref={virtualizer.measureElement} data-index={item.index}>
              <ThreadPrimitive.MessageByIndex
                index={item.index}
                components={MESSAGE_COMPONENTS}
              />
            </div>
          ))}
        </div>
      </div>
    </ThreadPrimitive.ViewportProvider>
  );
}

Use @tanstack/react-virtual only when mounting or updating the full thread is the bottleneck. The virtual rows stay in normal document flow between padding spacers so measured message heights remain correct. A virtualized scroller owns its scroll element, so use ViewportProvider instead of Viewport and implement the product's auto follow, measurement guard, and run start jump there. The id based unstable_useThreadMessageIds and Unstable_MessageById pairing is more resilient to insertions, but MessageByIndex is appropriate when a virtual row already has a stable index.

Scrollbars and scroll behavior

import { ScrollArea as ScrollAreaPrimitive } from "radix-ui";
import { ScrollBar } from "@/components/ui/scroll-area";
import { ThreadPrimitive } from "@assistant-ui/react";

function ScrollableThread() {
  return (
    <ScrollAreaPrimitive.Root asChild>
      <ThreadPrimitive.Root className="flex h-full flex-col">
        <ScrollAreaPrimitive.Viewport asChild className="thread-viewport">
          <ThreadPrimitive.Viewport
            turnAnchor="top"
            autoScroll={false}
            scrollToBottomOnRunStart
            scrollToBottomOnThreadSwitch
            scrollToBottomOnInitialize={false}
          >
            <ThreadPrimitive.Messages>{() => <Message />}</ThreadPrimitive.Messages>
            <ThreadPrimitive.ViewportFooter className="sticky bottom-0">
              <ThreadPrimitive.ScrollToBottom>Jump to latest</ThreadPrimitive.ScrollToBottom>
              <Composer />
            </ThreadPrimitive.ViewportFooter>
          </ThreadPrimitive.Viewport>
        </ScrollAreaPrimitive.Viewport>
        <ScrollBar />
      </ThreadPrimitive.Root>
    </ScrollAreaPrimitive.Root>
  );
}

Viewport follows streamed content unless the reader has scrolled up. autoScroll defaults to true for turnAnchor="bottom" and false for turnAnchor="top"; scrollToBottomOnRunStart, scrollToBottomOnInitialize, and scrollToBottomOnThreadSwitch control those explicit events. ScrollToBottom is hidden when the viewport is already pinned. A Radix scroll area needs its viewport wrapped with asChild, and its intermediate content node needs the layout styles described in the custom scrollbar guide.

Image generation

import { Image } from "@/components/assistant-ui/elements/image";
import { MessagePrimitive } from "@assistant-ui/react";

function AssistantImageMessage() {
  return (
    <MessagePrimitive.Root>
      <MessagePrimitive.Parts components={{ Image }} />
    </MessagePrimitive.Root>
  );
}

Store a generated URL or data URI as an image message part. The local Image renderer handles running, content filter, preview, and zoom states; Image.Actions adds copy, download, and optional regeneration controls. Import it from @/components/assistant-ui/elements/image, never from @assistant-ui/ui. The image-generation guide's package import is stale relative to the current element contract.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo5 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides comprehensive documentation and React code examples for building chat interfaces using the assistant-ui library. It covers various UI primitives for threads, composers, and message rendering. No security risks or malicious patterns were identified during the analysis.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

  • Runlayer9mo

    5 files scanned · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at b0609e6. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 weeks ago.

Activeupdated 2 months ago
  • React
  • assistant-ui
  • primitives
  • radix-ui
  • unstyled-components
  • chat-ui
  • composer
  • message-rendering
  • thread

README badge

README badge for assistant-ui/skills/primitives

Builds custom assistant chat UIs from composable, unstyled @assistant-ui/react primitives (ThreadPrimitive, ComposerPrimitive, MessagePrimitive, ActionBarPrimitive, and others) following Radix UI patterns. Use when you need fine-grained control over thread rendering, message parts (text, image, reasoning, tool-call), composer behavior, and action bars, and are willing to supply your own styling via className.

Generated from the current SKILL.md.

Are these components styled by default?
No. The primitives ship unstyled and require you to add className and apply your own Tailwind, CSS, or styling system.
What do I need to wrap primitives in?
Primitives must be wrapped in AssistantRuntimeProvider, and child primitives require their parent primitive to provide context.
How do I render different message types like text, images, and tool calls?
Use MessagePrimitive.Parts with a children render function that switches on part.type (text, image, reasoning, tool-call) and returns appropriate JSX for each.
Should I use .If or AuiIf for conditional rendering?
Prefer AuiIf for new code; the .If components on primitives are deprecated but still functional.
What's the difference between MessagePrimitive.Parts and MessagePrimitive.Content?
MessagePrimitive.Parts is the canonical API; MessagePrimitive.Content is a deprecated alias for the same functionality.

Generated from the current SKILL.md. These answers refresh after source changes.