Command palette

@yasinsensoy/web

Web · Components

Chat

Chat: a single component for both AI chat (like ChatGPT) and messaging (like WhatsApp).

43 exports

Live example

Preview

AY
Ayşe Yılmazonline
Thursday, November 5
Messages are end-to-end encrypted
I sent the notes from yesterday's meeting, did you get a chance to look?
I did, it looks great 👏
Friday, November 6
And this is the final design. I lightened the colors a bit, the old palette was too dark.
Lovely! Let's show the client tomorrowedited
0:14
😂
The meeting is at 10:00, don't forget

Code

import { Chat, ChatHeader } from "@yasinsensoy/web";

<Chat
  messages={mesajlar}
  users={contacts}
  currentUserId="ben"
  header={<ChatHeader title="Ayşe Yılmaz" subtitle="online" />}
  onSend={send}
  onReact={(m, e) => update(m.id, { reactions: toggleReaction(m.reactions, e, "me") })}
  onEdit={edit}
  onDelete={remove}
  composer={{ attachments: true, voice: true }}
/>

Events

  1. Events appear here when you interact with the preview.

Import

import {
  Chat,
  ChatComposer,
  EmojiPicker,
  ChatHeader,
  TypingIndicator,
  toggleReaction,
  defaultChatMessages,
  parseStreamData,
  readChatStream,
  applyStreamPart,
  useChat,
} from "@yasinsensoy/web";

Chat

componentClient component

Chat: a single component for both AI chat (like ChatGPT) and messaging (like WhatsApp). Messages are given as data; the list, bubbles, actions and composer are drawn automatically.

Messaging (`mode="messaging"`)

  • Bubbles; consecutive messages from the same person are grouped; colored names and avatars in group chats. The day divider sticks to the top while scrolling.
  • Time, "edited", star/pin and delivery ticks (sending, single, double, blue read, failed → tap to retry).
  • Reactions: 6 quick emoji + the full picker; chips show counts and who reacted. Reply: tapping the quote goes to the message and highlights it.
  • WhatsApp format: *bold*, _italic_, ~strike~, URLs as links; emoji-only messages are large; long messages get "Read more".
  • Attachments: an image/video grid (fullscreen Lightbox), voice messages (waveform, seeking, 1.5×/2×), file cards, link previews.
  • Mobile: swipe a bubble right → reply; long press → reaction and action sheet from the bottom (with haptics). On desktop a toolbar appears on hover.

AI (`mode="assistant"`)

  • Responses are drawn without flicker with Markdown while streaming (tables, code blocks); a reasoning section, tool steps, source chips, error + retry, copy / regenerate / 👍👎. With status, a stop button and "thinking" dots. useChat wires it all.

Shared

  • Sticks to the bottom: streaming and new messages stay visible; while scrolled up the position is kept and an "N new messages" button appears. Scrolling doesn't jump while older messages load (onLoadMore). An unread divider.
  • Performance: every row is memo; streaming only redraws the last message. Off-screen rows aren't rendered thanks to content-visibility; smooth even with thousands of messages. Heavy parts (fullscreen, emoji) load when needed.
  • Accessibility: incoming messages are announced to screen readers; ↑/↓ move between messages and the focused message's tools are reached with Tab.
Chat({ messages, mode, currentUserId, users, group: groupProp, status, onSend, onStop, onReact, onEdit, onDelete, onForward, onStar, onPin, onRetry, onRegenerate, onFeedback, onCopy, actions, customActions, canEdit, canDelete, confirmDelete, quickReactions, typing, hasMore, onLoadMore, unreadFrom, suggestions, empty, header, composer, groupWindow, collapseAfter, swipeToReply, timeZone, texts: textsProp, className, ...props }: ChatProps): JSX.Element

Examples

// Messaging
<Chat messages={messages} users={people} currentUserId="me"
  onSend={send} onReact={(m, e) => react(m.id, e)} onDelete={remove}
  composer={{ attachments: true, voice: true }} />

// AI
const chat = useChat({ send: ({ messages, signal }) => fetch("/api/chat", { ... }) });
<Chat mode="assistant" {...chat.props} suggestions={["Write a poem"]} />

ChatComposer

componentClient component

The chat composer: for both messaging (WhatsApp) and AI prompts (ChatGPT). Chat draws it itself; it can also be used on its own (e.g. an "ask" box at the bottom of a page).

  • Growing field: grows as you type and scrolls past the limit (overlay scrollbar).
  • Enter: sends on desktop, Shift+Enter adds a new line; on phones Enter is a new line. IME (Chinese/Japanese) input isn't split.
  • Attachments: paperclip button, paste (screenshots) and drag and drop; images show a small preview, others a type icon. Type, size and count limits are checked.
  • Voice messages: microphone permission is requested; recording shows a timer and live bars. The sent file is in draft.files, the duration and waveform in draft.voice.
  • Reply/edit: a quote bar on top; closes with Esc.
  • AI: while status is streaming the send button becomes "Stop".
ChatComposer({ onSend, value, defaultValue, onValueChange, variant, placeholder, disabled, status, onStop, attachments, voice, emoji, replyTo, replyAuthor, replyColor, onCancelReply, editing, onCancelEdit, submitOnEnter, maxLength, toolbar, footer, onTyping, autoFocus, ref, messages: messagesProp, className, ...props }: ChatComposerProps): JSX.Element

Examples

<ChatComposer variant="assistant" attachments status={status} onStop={stop}
  onSend={({ text, files }) => ask(text, files)} />

EmojiPicker

componentClient component

Lightweight emoji picker: categories, recently used and keyboard navigation (arrow keys, Home/End, Enter). Used in ChatComposer and the reaction bar; can also be used on its own.

  • No extra dependency or emoji font; the system's emoji are used.
  • Categories render as they enter the screen (content-visibility).
EmojiPicker({ onSelect, recent: showRecent, messages: messagesProp, className, ...props }: EmojiPickerProps): JSX.Element

Examples

<Popover trigger={<IconButton icon="smile" label="Emoji" />}>
  {({ close }) => <EmojiPicker onSelect={(e) => { insert(e); close(); }} />}
</Popover>

ChatHeader

componentServer component

Chat header: avatar, name, status or "typing…", actions on the right. Given to Chat's header prop. A server component.

ChatHeader({ title, subtitle, typing, avatar, status, start, actions, className, ...props }: ChatHeaderProps): JSX.Element

Examples

<Chat header={<ChatHeader title="Jane Doe" subtitle="online" status="online"
  actions={<IconButton icon="phone" label="Call" />} />} ... />

TypingIndicator

componentServer component

Three bouncing dots: "typing…" and the AI's "thinking" state. Chat shows it itself; it can also be used on its own in a header or contact list. A server component; the animation is CSS only and stops with the "reduced motion" preference.

TypingIndicator({ label, className, ...props }: TypingIndicatorProps): JSX.Element

Examples

<TypingIndicator label="Jane is typing…" />

Toggles a reaction and returns the new list (does not mutate the array). With single (default, like WhatsApp) the person's previous reaction is removed.

toggleReaction(reactions: readonly ChatReaction[] | undefined, emoji: string, userId: string, options?: { single?: boolean; }): ChatReaction[]

Examples

onReact={(message, emoji) =>
  update(message.id, { reactions: toggleReaction(message.reactions, emoji, myId) })
}

Turkish chat texts.

defaultChatMessages: ChatMessages

Turns an SSE data: line into a part. Recognizes your own part objects (type field), OpenAI (choices[0].delta.content), Anthropic (delta.text, delta.thinking) and { text | content | delta }; when it is not JSON it is the text itself. [DONE] and unknown ones are null.

parseStreamData(data: string): ChatStreamPart | null

Turns a stream into parts: Response (fetch), ReadableStream, AsyncIterable or a single text. In SSE responses data: lines are decoded with parse (default parseStreamData).

readChatStream(source: ChatStreamSource, options?: { parse?: (data: string) => ChatStreamPart | null; signal?: { readonly aborted: boolean; }; }): AsyncGenerator<ChatStreamPart>

Examples

for await (const part of readChatStream(await fetch("/api/chat"))) { ... }

Applies a part to a message and returns the new message.

applyStreamPart(message: M, part: ChatStreamPart): M

useChat

function

Manages the state of an AI chat: keeps messages, reads the response as a stream, stops, regenerates and edits. Provider independent; send calls your own API route.

  • Smooth: parts are drawn once per frame (even when hundreds of parts arrive per second); only the last message updates.
  • Reasoning time is measured automatically ("Thought for 12 s").
  • When stopped, the received text stays; on error the response shows "Retry".
useChat(options: UseChatOptions): UseChatResult

Examples

const chat = useChat({
  send: ({ messages, signal }) =>
    fetch("/api/chat", { method: "POST", body: JSON.stringify({ messages }), signal }),
});
return <Chat mode="assistant" {...chat.props} composer={{ attachments: true }} />;

// Your own generator:
useChat({ async *send() { yield { type: "reasoning", text: "Thinking…" }; yield "Hello!"; } });

Kind of chat.

  • "messaging": like WhatsApp: bubbles on both sides, time and ticks inside the bubble, reactions, swipe to reply, voice messages.
  • "assistant": like ChatGPT: a centered column, user messages as bubbles on the right, AI responses as bubble-less Markdown; reasoning, tools, sources, copy/regenerate/rating.
type ChatMode = "messaging" | "assistant"

Suggestion chip: text, or a separate label + prompt.

type ChatSuggestion = string | { label: ReactNode; prompt: string; }

ChatProps

interface

Props of the Chat component.

Extends: Omit<ComponentProps<"div">, "children" | "onCopy">

NameTypeDefaultDescription
messagesreadonly ChatMessage[]Messages, oldest to newest. See ChatMessage.
mode?ChatMode"messaging"Kind of chat. See ChatMode.
currentUserId?stringId of the person using the app; your own messages appear on the right.
users?readonly ChatUser[]People in the chat (name, photo, color). See ChatUser.
group?booleantrue` when `users` has more than two peopleGroup chat: the other side's name (colored) and avatar are visible.
status?ChatStatus"ready"AI status. See ChatStatus.
onSend?(draft: ChatDraft) => unknownWhen a message is sent. Without it no composer is drawn (read only).
onStop?() => voidWhen "Stop" is pressed (AI).
onReact?(message: ChatMessage, emoji: string) => voidWhen a reaction is chosen or its chip is tapped. toggleReaction does the work.
onEdit?(message: ChatMessage, text: string) => unknownWith the new text when your own message is edited.
onDelete?(message: ChatMessage) => unknownWhen deleted (confirmation is asked first; see confirmDelete).
onForward?(message: ChatMessage) => voidWhen "Forward" is chosen.
onStar?(message: ChatMessage) => voidWhen "Star" is chosen.
onPin?(message: ChatMessage) => voidWhen "Pin" is chosen.
onRetry?(message: ChatMessage) => void"Retry" on a message that failed to send or a failed response.
onRegenerate?(message: ChatMessage) => void"Regenerate" on an AI response.
onFeedback?(message: ChatMessage, value: "up" | "down" | null) => voidWhen a response gets 👍/👎 (null: withdrawn).
onCopy?(message: ChatMessage) => voidWhen text is copied to the clipboard (copying happens automatically).
actions?readonly ChatActionName[]Actions to show. When omitted, all those whose handlers are given; copy and reply are always available. See ChatActionName.
customActions?readonly ChatCustomAction[]Custom actions added to the message menu.
canEdit?(message: ChatMessage) => booleanown, non-deleted messagesCan the message be edited?
canDelete?(message: ChatMessage) => booleanown messagesCan the message be deleted?
confirmDelete?booleantrueAsk for confirmation before deleting?
quickReactions?readonly string[]["👍", "❤️", "😂", "😮", "😢", "🙏"]Quick reactions.
typing?readonly string[]Ids of people typing; a "typing…" bubble at the bottom.
hasMore?booleanAre there older messages? onLoadMore is called when scrolling up.
onLoadMore?() => unknownLoads older messages; loading shows at the top until the promise settles. The position doesn't shift.
unreadFrom?stringId of the first unread message: a divider goes before it and it is scrolled to on open.
suggestions?readonly ChatSuggestion[]Suggestion chips above the composer; an empty array hides them.
empty?ReactNodeContent shown when there are no messages.
header?ReactNodeHeader above the list (e.g. ChatHeader).
composer?Partial<Omit<ChatComposerProps, "onSend">> | falseComposer settings (attachments, voice, placeholder, tools, note…). false hides the composer. See ChatComposerProps.
groupWindow?number300000` (5 min)Messages from the same person within this many ms are grouped.
collapseAfter?number700Plain text longer than this many characters collapses with "Read more"; 0 turns it off.
swipeToReply?booleantrueReply by swiping a bubble right on touch screens.
timeZone?stringthe browser'sTime zone of times and day dividers.
texts?Partial<ChatMessages>Texts of the chat (this name is used because the message data is messages). App-wide via ui.chat in the dictionary. See ChatMessages.

File attachment rules.

NameTypeDefaultDescription
accept?string | readonly string[]Accepted types: "image/*", ".pdf", ["image/*", ".zip"].
maxSize?FileSizeMaximum size per file: bytes or "10 MB".
maxFiles?number10Maximum number of files in a message.

Functions on the ref for controlling ChatComposer from outside.

NameTypeDescription
focus() => voidFocuses the input.
addFiles(files: Iterable<File>) => voidAdds files (drag and drop, your own button); those breaking the rules are dropped.
insertText(text: string) => voidInserts text at the caret.
clear() => voidClears the text and attachments.

Composer look.

  • "messaging": like WhatsApp: a rounded field, emoji on the left, attachment on the right, a round send/microphone button next to it.
  • "assistant": like ChatGPT: a wide card; text on top, a tool row at the bottom (attachment, toolbar, send/stop).
type ChatComposerVariant = "messaging" | "assistant"

Props of the ChatComposer component.

Extends: Omit<ComponentProps<"form">, "onSubmit" | "children" | "ref" | "defaultValue">

NameTypeDefaultDescription
onSend(draft: ChatDraft) => unknownCalled with the draft on send. If the promise rejects, the text comes back.
value?stringText in controlled use.
defaultValue?stringInitial text in uncontrolled use.
onValueChange?(value: string) => voidWhen the text changes.
variant?ChatComposerVariant"messaging"Look. See ChatComposerVariant.
placeholder?stringPlaceholder. Defaults to "Type a message" / "Ask anything…" by look.
disabled?booleanDisabled.
status?ChatStatusAI status: while "submitted" or "streaming" the send button becomes "Stop" and no new message is sent. See ChatStatus.
onStop?() => voidWhen "Stop" is pressed.
attachments?boolean | ChatAttachOptionsfalseFile attachments: paperclip button, paste (screenshots) and drag and drop. true or rules (ChatAttachOptions).
voice?booleanfalseVoice messages: while the text is empty a microphone button appears instead of send; during recording a timer and live audio bars, cancel and send.
emoji?booleantrue` for the `"messaging"` lookEmoji button.
replyTo?ChatMessage | nullMessage being replied to; shown as a quote above the field.
replyAuthor?ReactNodeName of the author of the message being replied to.
replyColor?stringColor of the reply quote.
onCancelReply?() => voidWhen the reply is dismissed.
editing?ChatMessage | nullMessage being edited: its text comes into the field and sending edits it.
onCancelEdit?() => voidWhen editing is cancelled.
submitOnEnter?boolean | "desktop""desktop"Does Enter send? "desktop": on mouse/keyboard devices Enter sends and Shift+Enter adds a new line; on touch screens Enter is a new line (send with the send button).
maxLength?numberMaximum characters. A counter appears when close.
toolbar?ReactNodeExtra tools (e.g. a model picker, a "Search the web" button).
footer?ReactNodeSmall note below the field (e.g. "AI can make mistakes.").
onTyping?() => voidCalled at most once every 3 seconds while the user types; to forward the "typing…" signal to the server.
autoFocus?booleanFocus on open.
ref?Ref<ChatComposerHandle>Control functions. See ChatComposerHandle.
messages?Partial<ChatMessages>Texts of this field. See ChatMessages.

Props of the EmojiPicker component.

Extends: Omit<ComponentProps<"div">, "onSelect">

NameTypeDefaultDescription
onSelect(emoji: string) => voidCalled when an emoji is chosen.
recent?booleantrueRecently used section (stored in the browser).
messages?Partial<ChatMessages>Texts of this picker. See ChatMessages.

Props of the ChatHeader component.

Extends: Omit<ComponentProps<"header">, "title">

NameTypeDescription
titleReactNodeName of the person or group.
subtitle?ReactNodeSubtitle: "online", "last seen 14:05", "Jane, John, You".
typing?ReactNode"typing…" instead of the subtitle (e.g. "Jane is typing…"); shown with dots.
avatar?stringPhoto.
status?AvatarStatusStatus dot of the avatar.
start?ReactNodeElement left of the avatar (e.g. a back button on phones).
actions?ReactNodeActions on the right (call, video call, menu).

ChatMessages

interface

Texts of the chat components (Chat, ChatComposer, EmojiPicker). Replace them app-wide in the dictionary's ui.chat namespace, or for one chat with the messages prop. Placeholders such as {count} and {name} are filled at runtime.

NameTypeDefaultDescription
liststring"Mesajlar"Screen reader name of the message list.
youstring"Sen"Author of your own messages (in quotes, reactions).
unreadstring"{count} okunmamış mesaj"Unread messages separator.
jumpToLateststring"En yeni mesajlara git"Scroll down button.
newMessagesstring"{count} yeni mesaj"Count of new messages that arrived while scrolled up.
loadingOlderstring"Eski mesajlar yükleniyor…"While older messages load.
editedstring"düzenlendi"Note next to the time of an edited message.
deletedstring"Bu mesaj silindi"Deleted message.
deletedOwnstring"Bu mesajı sildin"Your own deleted message.
forwardedstring"İletildi"Note above a forwarded message.
readMorestring"Devamını oku"Link that expands a long message.
sendingstring"Gönderiliyor"Delivery status.
sentstring"Gönderildi"Delivery status: single tick.
deliveredstring"Teslim edildi"Delivery status: double tick.
readstring"Okundu"Delivery status: blue double tick.
failedstring"Gönderilemedi. Yeniden denemek için dokun."Message that failed to send.
starredstring"Yıldızlı"Starred message marker.
pinnedstring"Sabitlendi"Pinned message marker.
reactstring"Tepki ver"Reaction button.
replystring"Yanıtla"Reply action.
copystring"Kopyala"Copy action.
copiedstring"Kopyalandı"After copying.
editstring"Düzenle"Edit action.
deletestring"Sil"Delete action.
forwardstring"İlet"Forward action.
starstring"Yıldızla"Star action.
unstarstring"Yıldızı kaldır"Unstar action.
pinstring"Sabitle"Pin action.
unpinstring"Sabitlemeyi kaldır"Unpin action.
retrystring"Yeniden dene"Retry action.
regeneratestring"Yeniden oluştur"Regenerate response action.
goodstring"İyi yanıt"Like button.
badstring"Kötü yanıt"Dislike button.
morestring"Diğer"More actions menu.
moreReactionsstring"Diğer emojiler"+ button in the reaction bar.
messageActionsstring"Mesaj eylemleri"Screen reader name of the action panel.
deleteTitlestring"Mesaj silinsin mi?"Delete confirmation title.
deleteDescriptionstring"Mesaj herkes için silinir."Delete confirmation description.
reactedBystring"{names} tepki verdi"Tooltip of a reaction chip.
typingstring"{name} yazıyor…"While one person types.
typingTwostring"{a} ve {b} yazıyor…"While two people type.
typingManystring"{count} kişi yazıyor…"While three or more people type.
thinkingstring"Düşünüyor…"While thinking.
thoughtstring"Düşünme"Thinking section of unknown duration.
thoughtForstring"{seconds} sn düşündü"Thinking duration.
toolRunningstring"Çalışıyor"Tool running.
toolDonestring"Tamamlandı"Tool finished.
toolErrorstring"Hata"Tool failed.
toolInputstring"Girdi"Tool input title.
toolOutputstring"Çıktı"Tool output title.
sourcesstring"Kaynaklar"Sources list.
errorTitlestring"Yanıt alınamadı"Default text of the error box.
placeholderstring"Mesaj yaz"Placeholder of the input in messaging.
placeholderAssistantstring"Bir şey sor…"Placeholder in AI chat.
sendstring"Gönder"Send button.
stopstring"Durdur"Stop response button.
attachstring"Dosya ekle"Attach file button.
emojistring"Emoji"Emoji button.
recordstring"Sesli mesaj kaydet"Record button.
sendRecordingstring"Sesli mesajı gönder"Finish and send the recording.
cancelRecordingstring"Kaydı sil"Cancel the recording.
recordingstring"Kaydediliyor"While recording.
micDeniedstring"Mikrofona erişilemedi"When there is no microphone permission.
replyingTostring"{name} yanıtlanıyor"Reply bar.
cancelReplystring"Yanıtı iptal et"Close the reply bar.
editingstring"Mesajı düzenliyorsun"Edit bar.
cancelEditstring"Düzenlemeyi iptal et"Close the edit bar.
removeFilestring"{name} kaldır"Remove button in the attachment preview.
dropFilesstring"Dosyaları buraya bırak"Drag and drop area.
tooManyFilesstring"En fazla {max} dosya eklenebilir"When the file limit is exceeded.
fileTooLargestring"{name} çok büyük (en fazla {max})"When the size limit is exceeded.
fileNotAcceptedstring"{name} desteklenmiyor"When the type is not accepted.
voiceMessagestring"Sesli mesaj"Voice message attachment.
photostring"Fotoğraf"Image attachment (in quotes).
videostring"Video"Video attachment (in quotes).
filestring"Dosya"File attachment (in quotes).
playstring"Oynat"Play the voice message.
pausestring"Duraklat"Pause the voice message.
speedstring"Oynatma hızı"Speed button.
downloadstring"İndir"Download the file.
openMediastring"Tam ekran aç"Open the image/video full screen.
moreMediastring"+{count}"Count of attachments that do not fit the grid.
emptyTitlestring"Henüz mesaj yok"Empty messaging.
emptyAssistantstring"Nasıl yardımcı olabilirim?"Empty AI chat.
suggestionsstring"Öneriler"Screen reader name of the suggestion chips.
emojiRecentstring"Son kullanılanlar"Emoji category.
emojiSmileysstring"Yüzler"Emoji category.
emojiPeoplestring"İnsanlar"Emoji category.
emojiNaturestring"Doğa"Emoji category.
emojiFoodstring"Yiyecek"Emoji category.
emojiActivitystring"Etkinlik"Emoji category.
emojiTravelstring"Seyahat"Emoji category.
emojiObjectsstring"Nesneler"Emoji category.
emojiSymbolsstring"Semboller"Emoji category.

A part coming from the stream. A plain text part (string) is appended to the response.

  • { type: "text", text }: Text appended to the response.
  • { type: "reasoning", text }: Text appended to the thinking section.
  • { type: "tool", id, ... }: A tool call; the same id is updated.
  • { type: "source", url, title }: Adds a source.
  • { type: "message", message }: Changes message fields directly (e.g. { attachments }, { body }).
  • { type: "error", error }: The response ends with an error.
type ChatStreamPart = string | { type: "text"; text: string; } | { type: "reasoning"; text: string; } | ({ type: "tool"; } & ChatToolCall) | ({ type: "source"; } & ChatSource) | { type: "message"; message: Partial<Omit<ChatMessage, "id">>; } | { type: "error"; error: string; }

Values accepted as dates: Date, an ISO string or milliseconds.

type ChatDate = Date | string | number

Role of the message author.

  • "user": The person using the app (on the right).
  • "assistant": The AI or the other party (on the left).
  • "system": Small info line in the middle ("Ayşe joined the group").
type ChatRole = "user" | "assistant" | "system"

A tool call of the AI (web: the title can be a React element).

type ChatToolCall = Core.ChatToolCall<ReactNode>

A source the response relies on.

type ChatSource = Core.ChatSource<ReactNode>

Link preview.

type ChatLinkPreview = Core.ChatLinkPreview<ReactNode>

A chat message. See @yasinsensoy/core/chat ChatMessage.

type ChatMessage = Core.ChatMessage<ReactNode>

Delivery status of a message; shows as ticks next to the time of your own messages (like WhatsApp).

  • "sending": Sending (clock icon).
  • "sent": Reached the server (single tick).
  • "delivered": Reached the recipient (double tick).
  • "read": Read (blue double tick).
  • "failed": Failed to send (red warning; tap to retry).
type ChatMessageStatus = "sending" | "sent" | "delivered" | "read" | "failed"

Custom action added to the message menu.

NameTypeDescription
labelstringDisplay name.
icon?IconPropIcon: a name or an element.
tone?"neutral" | "danger"Red (dangerous) action.
onSelect(message: ChatMessage) => voidCalled with the message when chosen.
when?(message: ChatMessage) => booleanShow only on these messages.

ChatUser

interface

A person in the chat.

NameTypeDescription
idstringUnique id; matches the messages' authorId.
namestringDisplay name.
avatar?stringProfile photo.
color?stringName color in group chats (e.g. "#e11d48", "var(--ui-primary)"). When omitted, a stable color is picked from the id.
status?"online" | "away" | "busy" | "offline"Online status; a dot on the avatar's corner.

ChatDraft

interface

Draft sent from the composer.

NameTypeDescription
textstringText (trimmed).
filesFile[]Attached files (images, documents, voice messages).
replyTo?ChatMessageMessage being replied to; if sent while replying.
voice?{ duration: number; waveform: number[]; }Duration (seconds) and waveform if a voice message was recorded.

Attachment kind. When omitted, it is derived from type (MIME) or the file name.

  • "image", "video": Thumbnail in a grid; full screen on click.
  • "audio": Voice message player (waveform, speed).
  • "file": File card (icon, name, size, download).
type ChatAttachmentKind = "image" | "video" | "audio" | "file"

Message attachment: image, video, audio or file.

NameTypeDescription
id?stringUnique id. When omitted, url or the name is used.
name?stringFile name.
url?stringAddress (download, playback, full screen). A local preview can be given while uploading.
type?stringMIME type (e.g. "image/png", "audio/webm").
kind?ChatAttachmentKindKind. See ChatAttachmentKind.
size?numberSize (bytes).
thumbnail?stringThumbnail (shown in the grid instead of url).
width?numberNatural width (px); when given, space is reserved before the image loads, so nothing shifts.
height?numberNatural height (px).
duration?numberDuration of audio and video (seconds).
waveform?readonly number[]Waveform of a voice message: samples between 0 and 1 (30-60 are enough). When omitted, a fixed pattern is drawn.
progress?numberUpload progress (0-1). When given, a ring shows over the attachment.

ChatReaction

interface

A reaction: the emoji and who reacted.

NameTypeDescription
emojistringEmoji (e.g. "👍").
usersreadonly string[]Ids of the people who reacted. The count is its length.

ChatReasoning

interface

A thinking step of the AI.

NameTypeDescription
textstringThinking text (Markdown).
duration?numberThinking duration (seconds); written as "Thought for 12 s".

Names of the actions on a message. ChatProps.actions picks which actions show.

type ChatActionName = "react" | "reply" | "copy" | "edit" | "delete" | "forward" | "star" | "pin" | "retry" | "regenerate" | "feedback"

Chat state (AI). While "submitted" and "streaming", the send button becomes "Stop".

  • "ready": Ready.
  • "submitted": Request sent, waiting for the first part (three dots).
  • "streaming": The response is streaming.
  • "error": The last request failed.
type ChatStatus = "ready" | "submitted" | "streaming" | "error"

Props of the TypingIndicator component.

Extends: ComponentProps<"span">

NameTypeDescription
label?stringText read by screen readers (e.g. "Jane is typing…"). When omitted it is drawn only visually.

Info passed to the UseChatOptions.send function.

NameTypeDescription
messagesChatMessage[]History to respond to: the last message is the user's new message.
signalAbortSignalAborted when "Stop" is pressed; pass it to fetch.
filesFile[]Files the user attached (to the last message).

Responses the send function can return.

type ChatSendResult = Response | ReadableStream<Uint8Array | string> | AsyncIterable<ChatStreamPart> | Iterable<ChatStreamPart> | string

Options of the useChat hook.

NameTypeDefaultDescription
send(context: ChatSendContext) => ChatSendResult | Promise<ChatSendResult>Produces the response. Can return a fetch response (plain text or SSE; OpenAI and Anthropic formats are recognized), a ReadableStream, an async function* generator or text. See ChatStreamPart.
initialMessages?readonly ChatMessage[]Initial messages (e.g. a saved chat).
parse?(data: string) => ChatStreamPart | nullParsing of an SSE data: line. See parseStreamData.
onFinish?(message: ChatMessage, messages: ChatMessage[]) => voidWhen the response finishes (even if stopped).
onError?(error: unknown) => voidWhen the request fails.
onFeedback?(message: ChatMessage, value: "up" | "down" | null) => voidWhen the user gives 👍/👎.
attachment?(file: File) => ChatAttachment | Promise<ChatAttachment>Converts an attached file into an attachment shown in the message (e.g. upload it and return its URL). Defaults to a local preview URL (URL.createObjectURL).
generateId?() => stringcrypto.randomUUIDGenerates a new message id.

UseChatResult

interface

What the useChat hook returns.

NameTypeDescription
messagesChatMessage[]Messages.
setMessages(messages: ChatMessage[] | ((current: ChatMessage[]) => ChatMessage[])) => voidChanges the messages directly (e.g. load a saved chat).
statusChatStatusStatus. See ChatStatus.
errorunknownLast error.
send(input: string | ChatDraft) => Promise<void>Sends a message (text or a draft).
stop() => voidStops the streaming response; the text received so far stays.
regenerate(message?: ChatMessage) => Promise<void>Regenerates the last (or the given) response.
edit(message: ChatMessage, text: string) => Promise<void>Edits a user message and regenerates what follows.
props{ messages: ChatMessage[]; status: ChatStatus; onSend: (draft: ChatDraft) => Promise<void>; onStop: () => void; onRegenerate: (message: ChatMessage) => void; onRetry: (message: ChatMessage) => void; onEdit: (message: ChatMessage, text: string) => Promise<void>; onFeedback: (message: ChatMessage, value: "up" | "down" | null) => void; }Props to spread onto Chat: <Chat mode="assistant" {...chat.props} />.