Skip to content

ComponentsBlocks

SourceSource

AI chat

A conversation with an assistant: starter prompts, markdown replies, a typing state and the composer, composed from the registry.

A whole assistant conversation, ready to wire to a model: who you are talking to, the exchange so far, and the composer. Before the first message the list gives way to a greeting and a few prompts to start from, and while a reply is on its way the assistant is shown writing.

The block is the arrangement, not a client. It calls no model and knows no transport: it draws the messages you give it and tells you what was sent. Calling the model, appending the reply (or growing it as it streams) and setting pending stay in your application, so it works with any SDK or none.

Send a message in the preview: the reply is canned and arrives after a pause.

"use client"

import * as React from "react"

import {
  AiChat,
  type AiChatMessage,
} from "@/registry/bases/newt/blocks/ai-chat/ai-chat"

/*
 * No model is called here. The reply is canned and arrives after a pause, so
 * the demo shows the three states the block has — the prompts, the wait and
 * the exchange — without a key or a network.
 */
const REPLY = `Here is a starting point:
- **Name the server** after what people will do there
- Start with three channels: \`#welcome\`, \`#general\`, \`#help\`
- Add a role only when someone needs a permission the others do not

Want me to draft the welcome message too?`

const SUGGESTIONS = [
  "Plan a community server",
  "Write a welcome message",
  "Explain roles and permissions",
]

/* A fixed clock, so the server render and the first client render agree. */
const SENT_AT = "2026-09-07T14:23:00.000Z"
const DISPLAY_TIME = "Today at 14:23"

export default function AiChatDemo() {
  const [messages, setMessages] = React.useState<readonly AiChatMessage[]>([])
  const [pending, setPending] = React.useState(false)
  const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)

  React.useEffect(() => () => clearTimeout(timer.current), [])

  const send = (body: string) => {
    setMessages((current) => [
      ...current,
      {
        id: `user-${current.length}`,
        role: "user",
        body,
        sentAt: SENT_AT,
        displayTime: DISPLAY_TIME,
      },
    ])
    setPending(true)
    clearTimeout(timer.current)
    timer.current = setTimeout(() => {
      setMessages((current) => [
        ...current,
        {
          id: `assistant-${current.length}`,
          role: "assistant",
          body: REPLY,
          sentAt: SENT_AT,
          displayTime: DISPLAY_TIME,
        },
      ])
      setPending(false)
    }, 1200)
  }

  return (
    <AiChat
      className="w-full max-w-lg"
      assistantName="Newt"
      caption="Answers from your own model"
      messages={messages}
      pending={pending}
      suggestions={SUGGESTIONS}
      onSend={send}
    />
  )
}
<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue"
import {
  AiChat,
  type AiChatMessage,
} from "~~/registry/bases/newt/blocks/ai-chat"

/*
 * No model is called here. The reply is canned and arrives after a pause, so
 * the demo shows the three states the block has — the prompts, the wait and
 * the exchange — without a key or a network.
 */
const REPLY = `Here is a starting point:
- **Name the server** after what people will do there
- Start with three channels: \`#welcome\`, \`#general\`, \`#help\`
- Add a role only when someone needs a permission the others do not

Want me to draft the welcome message too?`

const SUGGESTIONS = [
  "Plan a community server",
  "Write a welcome message",
  "Explain roles and permissions",
]

/* A fixed clock, so the server render and the first client render agree. */
const SENT_AT = "2026-09-07T14:23:00.000Z"
const DISPLAY_TIME = "Today at 14:23"

const messages = ref<AiChatMessage[]>([])
const pending = ref(false)
let timer: ReturnType<typeof setTimeout> | undefined

onBeforeUnmount(() => clearTimeout(timer))

function send(body: string) {
  messages.value.push({
    id: `user-${messages.value.length}`,
    role: "user",
    body,
    sentAt: SENT_AT,
    displayTime: DISPLAY_TIME,
  })
  pending.value = true
  clearTimeout(timer)
  timer = setTimeout(() => {
    messages.value.push({
      id: `assistant-${messages.value.length}`,
      role: "assistant",
      body: REPLY,
      sentAt: SENT_AT,
      displayTime: DISPLAY_TIME,
    })
    pending.value = false
  }, 1200)
}
</script>

<template>
  <AiChat
    class="w-full max-w-lg"
    assistant-name="Newt"
    caption="Answers from your own model"
    :messages="messages"
    :pending="pending"
    :suggestions="SUGGESTIONS"
    @send="send"
  />
</template>

Installation

npx newtui@latest add ai-chatnpx shadcn@latest add @newtui/ai-chatnpx shadcn-vue@latest add @newtui/ai-chatpnpm dlx newtui@latest add ai-chatpnpm dlx shadcn@latest add @newtui/ai-chatpnpm dlx shadcn-vue@latest add @newtui/ai-chatyarn dlx newtui@latest add ai-chatyarn dlx shadcn@latest add @newtui/ai-chatyarn dlx shadcn-vue@latest add @newtui/ai-chatbunx newtui@latest add ai-chatbunx shadcn@latest add @newtui/ai-chatbunx shadcn-vue@latest add @newtui/ai-chatdeno run -A npm:newtui@latest add ai-chatdeno run -A npm:shadcn@latest add @newtui/ai-chatdeno run -A npm:shadcn-vue@latest add @newtui/ai-chatvlx newtui@latest add ai-chatvlx shadcn@latest add @newtui/ai-chatvlx shadcn-vue@latest add @newtui/ai-chatvp dlx newtui@latest add ai-chatvp dlx shadcn@latest add @newtui/ai-chatvp dlx shadcn-vue@latest add @newtui/ai-chatnubx newtui@latest add ai-chatnubx shadcn@latest add @newtui/ai-chatnubx shadcn-vue@latest add @newtui/ai-chatnlx newtui@latest add ai-chatnlx shadcn@latest add @newtui/ai-chatnlx shadcn-vue@latest add @newtui/ai-chatupx newtui@latest add ai-chatupx shadcn@latest add @newtui/ai-chatupx shadcn-vue@latest add @newtui/ai-chat

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Copy the source into your project

"use client"

import * as React from "react"

import { cn } from "@/lib/utils"
import { Avatar } from "@/registry/bases/newt/ui/avatar"
import { Button } from "@/registry/bases/newt/ui/button"
import { Chat, ChatBody, ChatFooter } from "@/registry/bases/newt/ui/chat"
import { Markdown } from "@/registry/bases/newt/ui/markdown"
import { MessageComposer } from "@/registry/bases/newt/ui/message-composer"
import {
  MessageGroup,
  MessageGroupAuthor,
  MessageGroupAvatar,
  MessageGroupBody,
  MessageGroupBotTag,
  MessageGroupContent,
  MessageGroupHeader,
  MessageGroupTime,
} from "@/registry/bases/newt/ui/message-group"
import { MessageList } from "@/registry/bases/newt/ui/message-list"
import { TypingIndicator } from "@/registry/bases/newt/ui/typing-indicator"

/*
 * A conversation with an assistant: who you are talking to, the exchange so
 * far, and the composer. Before the first message the list gives way to a
 * greeting and a few prompts to start from; while a reply is on its way the
 * assistant is shown typing.
 *
 * The block knows nothing about a model or a transport. It draws `messages`
 * and reports what was sent; calling the model, streaming the reply into the
 * array and setting `pending` are the application's.
 */
export interface AiChatMessage {
  id: string
  role: "user" | "assistant"
  /** An assistant's body is rendered as chat markdown; a user's as written. */
  body: string
  sentAt: string
  /** Rendered timestamp; the ISO value goes in `sentAt`. */
  displayTime: string
}

export interface AiChatProps extends React.ComponentProps<"div"> {
  assistantName: string
  /** Said quietly beside the name: the model, or what the assistant is for. */
  caption?: string
  userName?: string
  messages: readonly AiChatMessage[]
  /** A reply is being written: the assistant is shown typing. */
  pending?: boolean
  /** The line above the prompts, before the first message. */
  greeting?: string
  /** Prompts offered before the first message; choosing one sends it. */
  suggestions?: readonly string[]
  onSend?: (message: string) => void
  /**
   * Called when the composer's add button is pressed. The composer always
   * draws that button, so without this it does nothing: open your own picker.
   */
  onAttach?: () => void
}

function initial(name: string): string {
  return name.trim().charAt(0).toUpperCase()
}

export function AiChat({
  assistantName,
  caption,
  userName = "You",
  messages,
  pending = false,
  greeting = "How can I help?",
  suggestions = [],
  onSend,
  onAttach,
  className,
  ...props
}: AiChatProps) {
  const [value, setValue] = React.useState("")
  const empty = messages.length === 0 && !pending

  /*
   * New text is followed while the reader is at the bottom and left alone once
   * they have scrolled up to read something older. Sending always follows.
   */
  const body = React.useRef<HTMLDivElement>(null)
  const following = React.useRef(true)
  React.useEffect(() => {
    const element = body.current
    if (following.current && element) element.scrollTop = element.scrollHeight
  }, [messages, pending])

  return (
    <div
      className={cn(
        "overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated",
        className
      )}
      {...props}
    >
      <header className="flex items-center gap-3 border-b border-newt-border px-4 py-3">
        <Avatar>{initial(assistantName)}</Avatar>
        <div className="flex min-w-0 flex-col">
          <span className="flex items-center gap-1.5 font-display text-[15px] font-semibold text-newt-text-primary">
            {assistantName}
            <MessageGroupBotTag aria-label="AI assistant">
              AI
            </MessageGroupBotTag>
          </span>
          {caption && (
            <span className="truncate text-xs text-newt-text-muted">
              {caption}
            </span>
          )}
        </div>
      </header>

      <Chat aria-label={`Conversation with ${assistantName}`} className="h-96">
        <ChatBody
          ref={body}
          focusable
          viewportLabel={`Messages with ${assistantName}`}
          onScroll={(event) => {
            const { scrollHeight, scrollTop, clientHeight } =
              event.currentTarget
            following.current = scrollHeight - scrollTop - clientHeight < 48
          }}
        >
          {empty ? (
            <div className="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-8 text-center">
              <p className="font-display text-xl font-semibold text-newt-text-primary">
                {greeting}
              </p>
              {suggestions.length > 0 && (
                <div className="flex max-w-md flex-wrap justify-center gap-2">
                  {suggestions.map((suggestion) => (
                    <Button
                      key={suggestion}
                      variant="secondary"
                      size="sm"
                      className="border border-newt-border"
                      onClick={() => onSend?.(suggestion)}
                    >
                      {suggestion}
                    </Button>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <MessageList label={`Messages with ${assistantName}`}>
              {messages.map((message) => {
                const fromAssistant = message.role === "assistant"
                const author = fromAssistant ? assistantName : userName
                return (
                  <MessageGroup key={message.id}>
                    <MessageGroupAvatar>
                      <Avatar>{initial(author)}</Avatar>
                    </MessageGroupAvatar>
                    <MessageGroupBody>
                      <MessageGroupHeader>
                        <MessageGroupAuthor>{author}</MessageGroupAuthor>
                        {fromAssistant && (
                          <MessageGroupBotTag aria-label="AI assistant">
                            AI
                          </MessageGroupBotTag>
                        )}
                        <MessageGroupTime dateTime={message.sentAt}>
                          {message.displayTime}
                        </MessageGroupTime>
                      </MessageGroupHeader>
                      <MessageGroupContent>
                        {fromAssistant ? (
                          <Markdown content={message.body} />
                        ) : (
                          <span className="whitespace-pre-wrap">
                            {message.body}
                          </span>
                        )}
                      </MessageGroupContent>
                    </MessageGroupBody>
                  </MessageGroup>
                )
              })}
            </MessageList>
          )}
        </ChatBody>
        <ChatFooter>
          {/*
           * The status region is always there, so that its text appearing is
           * what a screen reader announces; mounted together with its text, a
           * live region is often missed.
           */}
          <div role="status" className="flex h-6 items-center px-1">
            {pending && (
              <TypingIndicator role="none" aria-label={undefined}>
                {assistantName} is writing…
              </TypingIndicator>
            )}
          </div>
          <MessageComposer
            channelName={assistantName}
            aria-label={`Message ${assistantName}`}
            onAdd={onAttach}
            placeholder={`Ask ${assistantName} anything`}
            value={value}
            onValueChange={setValue}
            onSubmit={(message) => {
              following.current = true
              onSend?.(message)
              setValue("")
            }}
          />
        </ChatFooter>
      </Chat>
    </div>
  )
}
<script setup lang="ts">
import { computed, nextTick, ref, watch, type HTMLAttributes } from "vue"
import { Avatar } from "~~/registry/bases/newt/ui/avatar"
import { Button } from "~~/registry/bases/newt/ui/button"
import { Chat, ChatBody, ChatFooter } from "~~/registry/bases/newt/ui/chat"
import { Markdown } from "~~/registry/bases/newt/ui/markdown"
import { MessageComposer } from "~~/registry/bases/newt/ui/message-composer"
import {
  MessageGroup,
  MessageGroupAuthor,
  MessageGroupAvatar,
  MessageGroupBody,
  MessageGroupBotTag,
  MessageGroupContent,
  MessageGroupHeader,
  MessageGroupTime,
} from "~~/registry/bases/newt/ui/message-group"
import { MessageList } from "~~/registry/bases/newt/ui/message-list"
import { TypingIndicator } from "~~/registry/bases/newt/ui/typing-indicator"

import { cn } from "@/lib/utils"

import type { AiChatMessage } from "./types"

/*
 * A conversation with an assistant: who you are talking to, the exchange so
 * far, and the composer. Before the first message the list gives way to a
 * greeting and a few prompts to start from; while a reply is on its way the
 * assistant is shown typing.
 *
 * The block knows nothing about a model or a transport. It draws `messages`
 * and reports what was sent; calling the model, streaming the reply into the
 * array and setting `pending` are the application's.
 */
const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    assistantName: string
    /** Said quietly beside the name: the model, or what the assistant is for. */
    caption?: string
    userName?: string
    messages: readonly AiChatMessage[]
    /** A reply is being written: the assistant is shown typing. */
    pending?: boolean
    /** The line above the prompts, before the first message. */
    greeting?: string
    /** Prompts offered before the first message; choosing one sends it. */
    suggestions?: readonly string[]
  }>(),
  {
    userName: "You",
    pending: false,
    greeting: "How can I help?",
    suggestions: () => [],
  }
)

/** `attach`: the composer's add button was pressed. It always draws that button, so listen for it to open your own picker. */
const emit = defineEmits<{ send: [message: string]; attach: [] }>()

const value = ref("")
const empty = computed(() => props.messages.length === 0 && !props.pending)

function initial(name: string): string {
  return name.trim().charAt(0).toUpperCase()
}

function authorOf(message: AiChatMessage): string {
  return message.role === "assistant" ? props.assistantName : props.userName
}

/*
 * New text is followed while the reader is at the bottom and left alone once
 * they have scrolled up to read something older. Sending always follows.
 */
const body = ref<InstanceType<typeof ChatBody> | null>(null)
let following = true

function onScroll(event: Event) {
  const element = event.currentTarget
  if (element instanceof HTMLElement) {
    following =
      element.scrollHeight - element.scrollTop - element.clientHeight < 48
  }
}

watch(
  () => [props.messages, props.pending],
  async () => {
    if (!following) return
    await nextTick()
    const element = body.value?.$el
    if (element instanceof HTMLElement) element.scrollTop = element.scrollHeight
  },
  { deep: true }
)

function submit(message: string) {
  following = true
  emit("send", message)
  value.value = ""
}
</script>

<template>
  <div
    :class="
      cn(
        'overflow-hidden rounded-[var(--newt-radius-lg)] border border-newt-border bg-newt-bg-elevated',
        props.class
      )
    "
  >
    <header
      class="flex items-center gap-3 border-b border-newt-border px-4 py-3"
    >
      <Avatar>{{ initial(props.assistantName) }}</Avatar>
      <div class="flex min-w-0 flex-col">
        <span
          class="flex items-center gap-1.5 font-display text-[15px] font-semibold text-newt-text-primary"
        >
          {{ props.assistantName }}
          <MessageGroupBotTag aria-label="AI assistant">AI</MessageGroupBotTag>
        </span>
        <span
          v-if="props.caption"
          class="truncate text-xs text-newt-text-muted"
        >
          {{ props.caption }}
        </span>
      </div>
    </header>

    <Chat :aria-label="`Conversation with ${props.assistantName}`" class="h-96">
      <ChatBody
        ref="body"
        focusable
        :viewport-label="`Messages with ${props.assistantName}`"
        @scroll="onScroll"
      >
        <div
          v-if="empty"
          class="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-8 text-center"
        >
          <p class="font-display text-xl font-semibold text-newt-text-primary">
            {{ props.greeting }}
          </p>
          <div
            v-if="props.suggestions.length > 0"
            class="flex max-w-md flex-wrap justify-center gap-2"
          >
            <Button
              v-for="suggestion in props.suggestions"
              :key="suggestion"
              variant="secondary"
              size="sm"
              class="border border-newt-border"
              @click="emit('send', suggestion)"
            >
              {{ suggestion }}
            </Button>
          </div>
        </div>
        <MessageList v-else :label="`Messages with ${props.assistantName}`">
          <MessageGroup v-for="message in props.messages" :key="message.id">
            <MessageGroupAvatar>
              <Avatar>{{ initial(authorOf(message)) }}</Avatar>
            </MessageGroupAvatar>
            <MessageGroupBody>
              <MessageGroupHeader>
                <MessageGroupAuthor>{{ authorOf(message) }}</MessageGroupAuthor>
                <MessageGroupBotTag
                  v-if="message.role === 'assistant'"
                  aria-label="AI assistant"
                >
                  AI
                </MessageGroupBotTag>
                <MessageGroupTime :datetime="message.sentAt">
                  {{ message.displayTime }}
                </MessageGroupTime>
              </MessageGroupHeader>
              <MessageGroupContent>
                <Markdown
                  v-if="message.role === 'assistant'"
                  :content="message.body"
                />
                <span v-else class="whitespace-pre-wrap">{{
                  message.body
                }}</span>
              </MessageGroupContent>
            </MessageGroupBody>
          </MessageGroup>
        </MessageList>
      </ChatBody>
      <ChatFooter>
        <!--
          The status region is always there, so that its text appearing is what
          a screen reader announces; mounted together with its text, a live
          region is often missed.
        -->
        <div role="status" class="flex h-6 items-center px-1">
          <TypingIndicator
            v-if="props.pending"
            role="none"
            :aria-label="undefined"
          >
            {{ props.assistantName }} is writing…
          </TypingIndicator>
        </div>
        <MessageComposer
          v-model="value"
          :channel-name="props.assistantName"
          :aria-label="`Message ${props.assistantName}`"
          :placeholder="`Ask ${props.assistantName} anything`"
          @submit="submit"
          @add="emit('attach')"
        />
      </ChatFooter>
    </Chat>
  </div>
</template>
/*
 * `messages` is deliberately a plain array. The block knows nothing about a
 * model or a transport; map onto this shape at the edge of it.
 */
export interface AiChatMessage {
  id: string
  role: "user" | "assistant"
  /** An assistant's body is rendered as chat markdown; a user's as written. */
  body: string
  /** ISO timestamp, for the `<time>` element. */
  sentAt: string
  /** What the reader sees. */
  displayTime: string
}
export { default as AiChat } from "./AiChat.vue"
export type { AiChatMessage } from "./types"

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds AI chat to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds AI chat to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { AiChat } from "@/components/ai-chat"

export function Example() {
  return <AiChat />
}
<script setup lang="ts">
import { AiChat } from "@/components/ai-chat"
</script>

<template>
  <AiChat />
</template>

Keep the conversation in state, append the user’s message when the block reports it, and set pending while your model answers. To stream, append the assistant’s message once and replace its body as the text arrives; the block renders whatever the array holds.

API reference

AiChat

PropType
assistantName?string

The assistant's name. It labels the header, the assistant's messages, the composer and the conversation for screen readers.

Typestring
messages?readonly AiChatMessage[]

The conversation, oldest first. An empty array shows the greeting and the prompts.

Typereadonly AiChatMessage[]
caption?string

A quiet line under the name: the model in use, or what the assistant is for.

Typestring
userName?string

The name shown on the user's messages.

Typestring
Default"You"
pending?boolean

A reply is being written. Shows the assistant writing above the composer.

Typeboolean
Defaultfalse
greeting?string

The line above the prompts, before the first message.

Typestring
Default"How can I help?"
suggestions?readonly string[]

Prompts offered before the first message. Choosing one sends it as written.

Typereadonly string[]
Default[]
onSend / @send?(message: string) => void

Called with the text when the user submits the composer or chooses a prompt.

Type(message: string) => void
onAttach / @attach?() => void

Called when the add button in the composer is pressed. The composer always draws that button, so without a handler it does nothing: open your own file picker here.

Type() => void

AiChatMessage

PropType
id?string

A stable key for the message.

Typestring
role?"user" | "assistant"

Who wrote it. An assistant's message carries the AI tag and its body is rendered as chat markdown; a user's body is shown as written.

Type"user" | "assistant"
body?string

The text of the message.

Typestring
sentAt?string

ISO timestamp, for the `<time>` element.

Typestring
displayTime?string

The timestamp as the reader sees it.

Typestring

The root takes the native attributes of the <div> it renders; React uses className, Vue uses class.

Accessibility

The conversation is a labelled, focusable scrolling region, so a keyboard user can reach it and scroll back through it. The writing state is a role="status" region that is always in the page, so the “is writing” text appearing is announced without moving focus. The composer is named “Message” plus the assistant’s name. The list follows new text while the reader is at the bottom and stays put once they have scrolled up; sending a message scrolls to the bottom again. In React pass a new messages array as a reply streams in; in Vue a deep change to it is enough. The AI tag has an accessible name of its own (“AI assistant”) rather than relying on the two letters. Say plainly somewhere in your product that the replies are generated: the tag marks who is speaking, it does not explain what that means.

Tokens

AI chat reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer.