Overview
Reference usage
Opinionated conversation surface bundling message list, composer, attachments, and scroll affordances for AI or support transcripts.
Usage
Chat needs a definite-height ancestor Chat's root element fills its parent (
height: 100%). Place it inside an ancestor with a resolved height—a fixed height, a flex or grid cell, or height: 100dvh—or the message viewport collapses and Chat renders as a small card instead of filling its space. See Layout and sizing.
Adapter-driven streaming
ChatAdapter.sendMessage deliberately stays a Promise<void> command. The adapter owns the conversation snapshot, while Chat owns the transient visual stream buffer. Pair the public streaming builders with the imperative instance methods so both surfaces advance together:
The assistant placeholder must exist before beginStreaming; update the same snapshot for each token, finalize it before endStreaming, and cancel it when the backend fails. The package's Adapter-driven streaming example uses a complete finite stream without assuming a particular model provider.
Failed delivery and retry
ChatAdapter.sendMessage receives a MessageInput, not a persisted Message, so it has no message ID. Append the optimistic user message to the authoritative snapshot first and retain the generated ID. Chat awaits adapter commands and reports rejected commands through onAdapterError; adapter implementations should mark delivery status and then rethrow so Chat can handle the error consistently:
The helpers immutably set or clear the transient _deliveryStatus metadata used by Chat's failed-message label and Retry button. Apply the same pair around retryMessage and editMessage resends; the successful attempt clears the marker.
Follow-ups during a run
Approval decisions
A tool approval draws as Cinder's explicit decision surface: the action, the Tool, the Command and a Deny and Approve pair. An adapter that knows more about it adds to that with describeApproval(toolCall, action), which returns a ChatApprovalDetails or undefined (a throw reads as undefined). The approval action carries no word on whether it can be undone, so only the adapter can mark an approval irreversible:
- The surface is Cinder's
ApprovalCardwithlayout="decision": the action as the title, a danger badge whenirreversible, the pause sentence, Tool, yourfacts, whether it can be undone, and the command always open and monospaced. Deny sits left and the named primary right. An irreversible primary arms on its first press ("Press again to refund"), reverts after three seconds or on Escape, and commits on the second press. Escape on an armed press never cancels the approval. - A decision made in this chat stays in the transcript as a receipt: a check badge, "by you" and the time, with a denial's note quoted inline. The receipt outlives the result that asked, so it is still there once the run resumes. A decision made on another surface is not known to Chat; the wire action carries no actor or surface.
- While an approval waits, a drawer above the composer says "Approval needed.", short enough to sit beside Review on one line on a 320px phone. It is a neutral
Calloutwhose action stays beside the words while both fit (actionLayout="fit"); in a column under 20rem (a 320px phone) the button reads Review (reviewApprovalShort) and keeps the name Review approval, so on a phone the reminder is one row. Its Review approval button scrolls to the approval (through the virtualized rows) and focuses its card without answering it. A draft in the box makes Send read Queue with the queue icon. - A transcript pinned to its end shows an item's bottom. When the item at the end waits on the person (a pending approval card, or an open question, including the block a host draws around one in
trailing) and is taller than the room left, the transcript lifts until the item's top, its question, is in view, and the person scrolls on to its buttons. Only the waiting item nearest the end, and only while part of it is in view, lifts the transcript; nothing moves while focus is inside the item; and once the person scrolls, wheels, touches or presses a key in the transcript, or jumps to the latest message, that item stays where they put it.
By default the composer is disabled while streaming is true, and the session controller refuses a second turn while a run is working or a tool approval is pending. A host that owns the run on the server, and can deliver input to it in flight, opts in with sendRunInput. Follow-ups are supported only for server-owned runs (executionOwner: 'server'): with a browser-owned run the controller does not expose the hook, the composer does not offer follow-ups, and submitting during the run behaves as it did before. A host attaching to or retrying a parked run can call controller.sendHiddenMessage() to start an internal turn without weakening the ordinary pending-approval gate; the hidden row remains in authoritative history and is not user-visible. There are two hooks, and they are different types:
ChatAdapter.sendRunInput(conversationId, message, attachments)is the component-facing hook. It takes the same message and attachments assendMessage, preceded by the conversation id. A raw adapter used without the controller gets no row id, and correlating its follow-ups is the host's problem.ChatSessionControllerOptions.sendRunInput(conversationId, message, attachments, { messageId })is the host-facing hook. The controller appends a transcript row for the follow-up and fillsmessageIdwith that row's id, so a host can pass it on as the session input's own id (submitSessionInputaccepts a caller-suppliedid). A retry of the same row passes the same id. Providing it makescontroller.adapterexpose the adapter hook.
The promise resolving is the acknowledgement, and it resolves only when the input's receipt is accepted, queued, or promoted. Every other receipt rejects with an error that names its state, so the row is marked failed with a Retry button. assertRunInputAccepted(receipt) does this for you. Read the receipt, not just the submission outcome: a canceled receipt from an immediate self-cancel (no run is live) and a replayed outcome whose receipt is already canceled both reject. Admission is not delivery, because the server cancels input a run ends without delivering it, and never answers it in a continuation run.
With the hook present:
- The textarea stays enabled during a run, Send and Stop sit side by side, and Enter submits a follow-up.
- The follow-up appears in the transcript at once as a row stamped
metadata._followUp, with a pending "Sending…" state that the acknowledgement clears. - Follow-ups are handed over one at a time, in the order they were sent, so a slow acknowledgement cannot be overtaken.
Chatalso serializes calls to a raw adapter the same way. - A follow-up is accepted while an approval is pending and does not resolve it.
- A follow-up row never owns the run. Retrying after a failed run, finding the owner of a tool call that arrives after a follow-up, an approval continuation's turn and attachments, and the AG-UI transport's choice of turn all stay with the turn that opened the run. Rows without the marker are not follow-ups, including rows installed with
adoptHistory. - When the run's terminal history names the follow-up's row, the transcript keeps one row, moved to the position the terminal gives it, and the client's row wins, so its marker and delivery status survive.
- A rejection marks that row failed with the usual Retry and leaves the run alone. Retrying resends it through the hook with the same
messageIdwhile a run is in progress, and otherwise promotes it to an ordinary turn. - A follow-up still waiting for the hook when the run ends (queued behind a slow acknowledgement) goes out as an ordinary turn on its existing row when the run completes or fails, one after another in the order sent. If the user stopped the run, it is marked failed with a Retry instead. A run parked on a pending approval has not ended.
- Once a run ends, each follow-up the host accepted is classified. The run delivered it when its terminal history (the history a
run.completedframe carries) names the row's id. Otherwise the server cancelled it, and that includes a run that ended with no terminal history at all, such as a stop mid-stream or a failure. If this client pressed stop, the row is marked failed with a Retry. If the run completed or failed, the row is promoted to an ordinary turn after the run ends, reusing its row and attachments. The decision waits for both the acknowledgement and the run's end, in either order, so an acknowledgement that arrives late is still classified. A follow-up the hook rejects is failed as above. controller.invalidate()retires every acknowledgement still owed: a late acknowledgement or rejection writes nothing, and the sender's promise rejects with an invalidation error. A follow-up still queued when it happens is marked failed and reported throughonError. A stop does not retire anything.- The controller's adapter orders its own input (
ChatAdapter.ordersRunInput), soChathands it each follow-up at once and the row shows immediately; for a raw adapter,Chatqueues the calls itself, one at a time, and drops that queue when the conversation changes. - A follow-up queued when the conversation changes is rejected through
onAdapterErrorrather than dropped silently.
A host whose server holds a follow-up until the run takes it, and can take it back until then, also passes retractRunInput(conversationId, { messageId }), resolving 'retracted' when the input will never be delivered and 'delivered' when the run already had it. Then:
- Acceptance is not delivery. An accepted follow-up stays queued (its row keeps the pending status, so the transcript draws it as a queued message) until the run takes it. The host says when with
controller.markFollowUpsDelivered(messageIds), as when its server announces the step that took them, and otherwise the run's terminal history shows it. From then on the row reads as sent and is not resent when the run ends. controller.adapter.removeRunInput(messageId)takes a queued follow-up back, andChatcalls it for Remove. One the host holds goes throughretractRunInput:retractedtakes its row out of the transcript, anddeliveredleaves it as a sent message. One the host was never handed, or whose run ended without taking it, is dropped without asking. A rejection leaves the row queued and is reported throughonAdapterError. A follow-up that is already a sent message cannot be removed.
A controller without sendRunInput, or with a browser-owned run, behaves exactly as before. The "Follow-ups during a run" example shows the flow.
A follow-up typed while a run works, or while an approval waits, is not handed to the run by default. It waits on the page in an Up next drawer above the composer ("2 queued, sends after this run" where the drawer is wide enough, "2 queued" below that; Send now instead carries "Otherwise it sends when this run finishes." as its tooltip and description), each one a bordered, numbered row holding the words of the message it will become, with Edit (which puts its words and files back in the composer) and a remove control named "Remove queued follow-up 1". When the run finishes they go one at a time, each as a new turn through sendMessage, in the order they were typed. Send now instead hands every waiting follow-up to the running run through sendRunInput, which is the only path that uses live run input. Stopping the run, or a waiting follow-up whose send fails, sets the rest aside in a warning drawer whose Restore puts their words and files back in the composer, and Dismiss forgets them. Another conversation starts with an empty queue. While the run works the composer's placeholder reads "Add another follow-up…", and Send reads Queue.
Edit and resend
ChatAdapter.editMessage hands you the edited message's ID and new content; the superseded branch (the old reply, any tool calls after it) should be discarded before the edited content is re-sent. rewindBeforeMessage performs exactly that cut — it drops the named message and everything after it in the transcript, keeps tool-call/tool-result pairs atomic, and renumbers positions — so an edit flow never assembles ids/messages/updatedAt by hand:
rewindBeforePosition is the position-keyed form, and both accept a RewindOptions bag (preserveToolPairs: false cuts strictly at the boundary, leaving a straddled tool call pending).
Transcript mutation and query helpers
@lostgradient/chat re-exports Conversationalist's canonical transcript mutation and query helpers so consumers never hand-walk conversation.ids / conversation.messages or import conversationalist directly:
updateMessage, removeMessage, setMessageHidden, and replaceToolResult are no-ops—they return the original history unchanged—when given an unknown message or tool-call identifier, so callers do not need to guard against a stale ID.
getMessages(conversation, { includeHidden? }) returns the ordered, non-hidden messages Chat renders (pass includeHidden: true to include hidden ones too). getUnresolvedToolApprovals(conversation) finds every tool-result message still parked on outcome: 'action_required' with a pending action—the transcript-level source of truth for "does this conversation have an approval waiting," independent of any UI-only approved/denied state. findToolResultMessage(conversation, toolCallId) locates the tool-result message for a given tool-call ID, which replaceToolResult needs. Both query helpers accept the same { includeHidden? } option as getMessages.
Warning
ChatAdapter.subscribe runs inside Chat's own effect Chat opens subscribe from inside its internal mount $effect, so a synchronous $state write inside subscribe can throw effect_update_depth_exceeded. Defer it with queueMicrotask or tick(). The same applies if subscribe replays a buffered event by calling a handler (onMessage, onTypingChange, etc.) synchronously before returning — defer the CALL to the handler itself, not just any write of your own, since onTypingChange/onReadReceipt write Chat's own internal state before your code runs at all. See the ChatAdapter.subscribe and ChatPushHandlers JSDoc for the full explanation and working examples.
Conversation data contract
Chat declares @lostgradient/cinder and svelte as peer dependencies — host applications install those alongside @lostgradient/chat. conversationalist (and its own zod dependency) is an implementation detail Chat owns: it ships as a regular dependency of @lostgradient/chat and installs automatically, so using Chat never requires a host application to add or version-pick it. Import the conversation types, builders, CURRENT_SCHEMA_VERSION, and isJSONValue from @lostgradient/chat rather than importing conversationalist yourself. An application that uses conversationalist APIs beyond what Chat re-exports may still depend on it directly — that is supported, it just is not something Chat requires.
The exported schema version comes from the conversationalist version Chat depends on. Histories produced by an older compatible schema can render as-is; a newer schema causes Chat to emit a console warning and requires upgrading @lostgradient/chat before relying on that history.
Layout and sizing
Chat's outer layout element is height: 100%. When no ancestor on the chain resolves to a definite height, that 100% resolves against auto and Chat collapses to the intrinsic height of its empty state plus composer. There is no browser error: it just silently shrinks to a small card. Give Chat a sized ancestor with one of the three patterns below.
Fixed-height container. The simplest option—wrap Chat in an element with an explicit height. This is what every example in this component uses.
Full-viewport flex column. For an app shell where Chat should fill the remaining space, give the column a definite height and let the Chat cell flex: 1 with min-height: 0 (so it can shrink below its content and scroll internally rather than overflowing the page).
Grid cell. The same shape works in a grid: give the container a resolved track (grid-template-rows: auto 1fr), place Chat in the 1fr row, and keep min-height: 0 on the Chat cell so it can shrink and scroll internally instead of overflowing the page.
Quoting agent messages
A reader can reply to part of an agent message, or to several parts at once. Quoting needs no props and no adapter support: the quotes travel as Markdown in the message itself, so the model sees them, and a reloaded transcript shows them.
- Selecting text inside one assistant message's content opens a Quote popover (Cinder's
SelectionPopover). A selection that spans messages, or reaches outside assistant content, opens nothing. - Every assistant message also has a Quote message action in its action row. It quotes the current selection when that selection lies inside the message, and otherwise the message's whole rendered text, so quoting works from the keyboard.
- Each quote appears as a chip above the composer showing its first 80 characters, with a Remove button. Chips keep the order they were added in, and quoting the same text twice adds it once.
- A reply carries at most 10 quotes. At 10, both Quote actions are disabled and the chip row says why. A quote longer than 4,000 characters is cut to 3,999 characters plus an ellipsis. Surrounding whitespace is trimmed from every quote.
A quote is the selected text exactly as the browser reports it (Selection.toString()), not a link back to the message it came from, and Chat sends no quote metadata. Sending puts the quotes at the top of the message as Markdown block quotes: every line is prefixed with > , quotes are separated by one blank line, and one more blank line precedes the typed text.
The composed text goes through ChatAdapter.sendMessage (or onSubmit), or through sendRunInput when a run is active, exactly as a plain reply would. ChatSubmitEvent.message.content and the adapter's message.content already hold the composed text. The composer still needs typed text or an attachment to send, so quotes alone cannot be sent. With an attachment and no typed text, the content ends at the last quote.
The quotes leave the chip row the moment the message is handed off, not when the send finishes. The session controller settles sendMessage only when the whole run ends, so a follow-up sent during that run would otherwise repeat them. If the send fails, the quotes come back ahead of any chips added since, in their original order and without repeating any text. When they would not all fit within the limit of 10, the first 10 stay and Chat announces how many were dropped. A send that fails after the conversation has changed restores nothing. onSubmit is not awaited, so only a synchronous throw from it counts as a failure. Changing the conversation clears the chips.
Quoting is on by default. capabilities.quote set to false removes the Quote message action and the selection popover, and clears any chips.
Quoting covers assistant messages only. User messages and tool output offer no Quote action, and a selection inside them opens no popover. The "Quoting agent messages" example shows the flow.
Composer controls, hint and blocked row
composerControls is an optional snippet rendered right after the attach button for the host's own selects (Cinder Select with variant="ghost", presentation="listbox" and a valuePrefix draws Model Claude Sonnet 5.5), and composerActions still sits beside Send for something like a context meter. composerPlaceholder sets the placeholder, and composerHint replaces or hides the line under the box (default Enter to send. Shift and Enter for a new line.). On a touch-only device (no hover and a coarse pointer) the default hint and the formatting shortcuts' words are not drawn, because there are no keys to press; a host's own hint still shows.
composerHeader is an optional snippet for the top row inside the composer's border, above the text, where a new chat draws its ghost agent Select (a leading avatar, the agent's name). The footer is one row that never wraps. When the composer is narrower than COMPOSER_FOLD_WIDTH (40rem: a side panel docked beside the conversation, a phone), or at any width when the controls with their values in full would not fit beside the meter and Send (measured from the controls' own width, and marked on the composer as data-controls-folded), composerControls is called with { folded: true }, and a host draws one ghost Settings control holding the model, effort and permissions in place of the three selects; ChatComposerSettings is that control, so a host writes <ChatComposerSettings {folded}>…the three selects…</ChatComposerSettings> and the selects stand in the row while it is wide and open from Settings once it is not. Controls and Send are 44px tall on a composer under 28rem. composerFormattingToolbar draws a row of Bold, Italic, Code, Link and List buttons above the text, with the words of their shortcuts (⌘B bold, ⌘I italic, ⌘E code and ⌘⇧K link, each its own element) at its right, only while the composer has focus. It opens when the box or the row takes focus and stays while focus is in the composer; a control the host puts in the composer (the agent select above the box, the selects under it) taking focus does not open it, so a click on that control is never moved out from under the pointer by the row appearing. Link is Cmd or Ctrl with Shift and K; plain Cmd or Ctrl with K is left to the host, so its command palette still opens from the composer. A file the person attaches is a tile under a count of the files ("3 files"): a type badge, its name truncated in the middle so the extension always shows, its size, the percentage while it uploads (when the uploadAttachment hook reports it through onProgress, otherwise a moving bar), and a cross that removes it. A file that failed keeps its tile in the danger colour with the reason beside it; an upload that failed also offers Retry before the cross, while a file the composer refused (too large, or a type it does not take) has only the cross. While any file needs attention Send is off, and the line under the composer says so once, "Retry or remove 2 files to send", which Send names through aria-describedby. A type the composer does not take reads "This file type can’t be attached. Attach an image, a PDF or a text file.", naming the kinds acceptedTypes allows. More than three files cap the list: exactly three tiles show, each whole, and a count of the rest under it ("11 more") opens the whole list, which scrolls inside the composer. On a composer 30rem wide or less each file is a row the composer's width, and its name wraps instead of being cut. composerCompact is a one-line composer for a small surface such as a test chat in a side panel: the field and Send share one row (Send becomes Stop while a reply streams, and the field is disabled), with no controls, attachments or formatting, and the hint under it.
composerPlacement="centered" puts the empty state, the composer and composerFooter together in the middle of the surface while the conversation has no message, the way a new chat greets a person, and docks the composer at the bottom as soon as there is one. composerFooter is an optional snippet drawn under the composer's hint or status line, where a new chat draws its example prompts and the other agents to start with; the block is at most 52rem wide.
composerLead is an optional snippet drawn above the composer, outside its border, for a note on where the conversation comes from, such as the chip a new chat started from another page carries; it is drawn whether the composer is live or blocked. composerStarting names the word Send shows while the host is starting what the message belongs to (Starting chat…): Send is off with a spinner, Stop is not offered, and the text stays. With clearComposerOnSubmit={false} Send leaves the typed text and files in the box, and the host empties it with clearInput() once the message has gone through.
composerStatus is the line that replaces the hint: { kind: 'steering' } ("A message now steers the run."), { kind: 'note', text } for a sentence of the host's own such as "Effort High applies from the next step.", { kind: 'reconnecting', attempt } and { kind: 'queued' }. Two kinds are drawers above the composer instead: { kind: 'offline' } says "Your draft is saved here, and Send comes back when you reconnect." (the host's banner says "You're offline"), keeps the draft and turns Send off, and Send's aria-describedby names the drawer; { kind: 'draft-restored', when, ondiscard? } says "Restored your unsent draft from <when>." with Discard draft, which empties the composer and then calls ondiscard. Its { kind: 'blocked', reason, action?, link? } kind replaces the whole composer with one compact row: a warning glyph, the reason in muted text, a secondary button for action and a quiet link for link (each a button with onclick, or an anchor with href). Use it for a missing provider ("Connect a model provider to chat"; set primary: true on the action to draw it as the row's one filled button instead of a secondary one), an unreachable server, an ended chat or a disabled plugin. Two more kinds replace the composer with one neutral bar, with no warning colour: { kind: 'archived', when, newChat?, unarchive? } draws an archive icon and Archived <when>, with newChat as a secondary button on the left and unarchive as the primary button on the right; { kind: 'read-only', tooltip?, request? } draws a lock and the words Read only, whose tooltip says who granted the access (tooltip), and request as the primary button, such as Request access. Each action is a button with onclick or a link with href. The draft in the box is kept while a bar shows. While a question waits, the composer is in answer mode: the placeholder reads "Choose an answer above, or type your own…" and its button reads Answer. Chat does this itself for the questions it draws; a host that draws its own sets composerAnswering (the button reads Answer) and words the placeholder through composerPlaceholder.
variant="transcript" draws the conversation the way Interborough's chat page does. A reply is plain text with no card and no role label; a person's message keeps its tinted bubble. One muted line under each message holds its time, whatever messageActions renders (a model name, a Reply details link, Branch), then Copy and, on a reply, Quote, as words that are always visible. A message that was not sent keeps its bubble and shows a focusable red icon, its time and the red words "Not sent"; the icon opens a popover with notSent.summary and a Retry button, which notSent.retryDisabled makes inert (aria-disabled, so it keeps focus) while notSent.retryNote says when it will retry and describes the button. A follow-up the run has not taken yet (delivery status sending) is a dashed, pale bubble marked "Queued until the run is ready"; "Remove" shows only when the adapter has removeRunInput (the session controller's does when its host passes retractRunInput) or the host passes onRemoveQueued, because only the host knows whether a message it has sent can be taken back; while a removal settles, Remove is not offered again, and the row then leaves the transcript, or reads as sent when the run had already taken it. A run's notes (memory written, a wakeup, a child run, why it stopped) are full-width rows outside the bubble, and a stop note with failed: true is a danger status line with an error glyph and the host's own action beside it (noteAction, for a Retry); a stop note with notice: true is a muted status line with an info glyph and no "Stopped" label, for a chat the host ended. The agent's instructions (a system message) read as muted text folded to one line, "Instructions", a disclosure button with a chevron, and a streaming reply ends in a caret. Edit and rollback are not offered in this presentation.
Composer actions
composerActions is an optional snippet rendered in the composer footer, beside Send, so a host can put its own controls next to the composer; the usual case is a model picker built from Cinder's Select (or Combobox). Chat does not ship a picker: the host owns the value and what it means.
The snippet takes no arguments. It stays interactive while a run streams and while a tool approval is pending, because Chat only disables the composer textarea, never the footer; the host decides whether a control should lock during a run. Without the snippet the composer renders as it always has. The "Composer actions" example shows the whole flow.
Building composer overlays
Slash-command, mention, and autocomplete overlays should use Chat's composer API instead of querying .chat-input-editor directly.
Use bind:this to read or control the composer:
getComposerValue() returns the current plain-text value, clearInput() clears it, and getEditorElement() returns the textarea element (or null before mount and after teardown) for overlay anchoring and focus management. insertAtRange({ start, end }, text) replaces that composer range without a synthetic DOM event, focuses the textarea, and places the caret after the inserted text. It uses native HTMLTextAreaElement.setRangeText() boundaries: out-of-bounds indexes are clamped and a reversed range throws a DOMException. Calls before mount or after teardown are safe no-ops.
oncomposerkeydown runs before Chat's internal Enter-to-send handling for normal composer keydowns. If the callback calls event.preventDefault(), Chat skips its internal key handling for that event. Chat does not call the hook during IME composition, so Enter can still confirm the active candidate instead of sending or being consumed by an overlay.
For ARIA combobox patterns, pass textarea-specific attributes through the composer-prefixed props:
Announcing custom action-required rows
Chat owns always-rendered polite and assertive live regions outside the role="log" timeline. If you render action-required UI through a custom row or messagePart snippet, announce it through Chat instead of mounting another aria-live region inside the log:
Use the default polite channel for non-urgent status updates:
Consumer announcements clear after a short interval so Chat's own history, unread, typing, and tool-approval announcements can continue to flow. Built-in tool-approval rows keep precedence on the assertive channel. If a consumer assertive announcement races with Chat's derived Action required: ... tool-approval announcement, Chat announces the built-in tool approval and drops the consumer assertive text to avoid double output.
Per-row snippet context
row, messageActions, and messageStatus receive the same ChatRowContext. The context contains the message that owns the visible row and optional resolved toolCallPair and artifact values. When a row has cinder:artifact metadata, Chat renders an always-visible Open artifact: <title> row action and opens the built-in artifact panel by default:
onArtifactOpen is an ownership override: when supplied, Chat calls it with the resolved artifact and does not open the internal panel. Omit it to use Chat's built-in ChatArtifactLayout, ArtifactPanel, and ArtifactViewer composition. The resolved artifact keeps the raw descriptor fields and adds id from the source message plus a normalized non-empty title (Artifact when metadata is blank).
messageActions is rendered in the same hover/focus action row as Chat's built-in copy and edit controls. Artifact actions are separate persistent row actions. For native buttons in messageActions, add the shared chat-message-action-button class to opt into the action-row sizing, focus, hover, and touch styles:
The class is intentionally opt-in so consumers can use their own button component or visual treatment without Chat overriding it. Cinder Button instances already provide their own complete styling and do not need this class.
A paired tool-result message does not render a second visible row and does not invoke the snippets separately. Chat folds that result into the corresponding tool-call row's toolCallPair and resolves cinder:artifact metadata from the folded result into artifact. Metadata on the visible message takes precedence. Ordinary rows and unpaired tool-result rows resolve their own artifact metadata, so consumers do not need an external message lookup or a hand-rolled type guard. Artifact identity always comes from the source message id, so duplicate titles and duplicate content remain independent.
Code highlighting
Chat highlights every code block in a transcript: Markdown fences, tool payloads and approval commands. Pass codeHighlighter to choose the highlighter. Build one with Cinder's shikiHighlighter over the grammars and themes your application renders, so its bundle carries only those:
Chat reads codeHighlighter when it mounts. A language outside the configured grammars renders as plain text. Without the prop, Chat highlights any language Shiki knows, which makes a bundler emit every Shiki grammar and theme. A build that configures every Chat can leave that out by setting the explicit-code-highlighter export condition (conditions in Bun.build): Chat then never reaches the full registry, and a Chat without codeHighlighter draws plain code.
Message sources
Pass sourcesByMessageId to show the sources behind assistant messages. It maps an existing message id to Cinder CitationSource entries, in the order to show them:
An assistant message with at least one source shows one Sources control, at the trailing end of its message line: the count and the word ("3 sources", "1 source") in the small muted text of the time, with a small chevron. It looks the same for any count and at any width, and a message without sources has none. An unknown id, an empty array and a user message show nothing, and a Chat given no map renders exactly as before.
Activating the control opens Cinder's Citation list: under the message line on a layout wider than a phone, and as a bottom sheet on a phone. Each row is the source's title (two lines at most), its domain in small muted text, its excerpt in quotation marks when it has one, and an open-in-new glyph at the trailing end; the whole row is the link, and only a safe web address becomes one (a source with no address, or one whose address is refused, keeps its row without the glyph and says so, "Link hidden: the address isn't a safe web link"). Chat never fetches a source. Sources are presentation only: they are never written to the conversation or an export, and duplicates are kept as given. The expanded state, the keyboard and focus behaviour, and focus returning to the control are the disclosure's; opening the list in a message above the viewport, including in a virtualized transcript, keeps the message at the top of the viewport where it was.
When the host withdraws a source while focus is on its row, focus moves to the next row that is a link, or to a message action when none is left; when the host removes every source, focus moves to the message. The withdrawal is said once, through the transcript's announcer.
Docked questions
A question that has choices (a choice, a choice with Something else, a yes or no) is drawn in its transcript row by default. Set questionPlacement="docked" and Chat draws it in place of the composer instead, while the run waits on it:
- A warning that the step Needs you, beside the question when the question fits on one line there and above it when it does not. When several questions were asked together the header also reads
Question 2 of 3with a previous and a next button (named by thepreviousandnextlabels): they only move between the questions and send nothing, an answered question shows its answer selected, and choosing another answer and pressing Answer sends it again, as Change does in the transcript, until the run moves on. The progress is a row of its own above the question, at the leading edge where the question starts: the muted 12px words, then the two buttons directly after them. The question and the tag share a line below it while the question fits, as with one question; they wrap only when the question does not fit. - A fieldset named Question (its legend is visually hidden), with the question as its text (14 px, semibold) and one radio card per choice, every choice shown, each reading at 14 px with its description and the key that chooses it (1, 2, 3 and so on), and on a touch screen a 44 px hit area. The panel is as tall as its content up to about 80% of the viewport; past that only the list of choices scrolls inside it, and the last visible row is cut by the edge. Something else, drawn for a choice that allows an answer of the person's own, opens a text field. The keys work only while focus is inside the dock and never inside a field.
- A choice only selects. The primary Answer on the right sends it, and stays off until something is chosen (or typed). The quiet Reply in chat on the left (its glyph and its words, or only the glyph when the row cannot hold them) gives the composer back and returns the question to its row, where it can still be answered.
- Once answered, the transcript row reads You answered, with Change, as it does for any question. The composer stays mounted while the dock shows, so a draft and its attachments survive.
questionLabels (ChatQuestionDockLabels) replaces any of the words. Every other kind of question stays in its row. A question also stays in its row while the composer is replaced by a blocked, archived or read-only bar, or by an error or deleted availability state, because there is no composer to give back.
Questions the host asks
A host that draws its own question (the one a run parked on, which is not in the conversation) passes hostQuestions (each { id, dockable }) and a hostQuestion snippet that draws one of them, told { docked, replyInChat }. Chat places every question exactly once: the first dockable question the person has not sent back takes the composer's place, behind any question Chat draws itself, and every other question, or all of them while the composer is replaced, is drawn at the end of the transcript. replyInChat() gives the composer back and returns a docked question to the transcript; a question that is no longer asked is forgotten, so one asked again docks again. The host keeps its own guarded answer, its Undo window and which kinds may dock.
Files on a row
ChatMessageAssets draws the files a row carries from addresses the host supplies, each { url, mediaType, name?, size? }: an image through Chat's own attachment grid (with its lightbox, and the failed-image footprint that names what did not load and offers Retry), audio and video with Cinder's players, and anything else, SVG included, as a download that names the file and its size, never its media type. messageAssetKind says which a media type is, and labels (ChatMessageAssetLabels) replaces the words. Chat never reads the bytes, so the host owns where they are served from.
Run outcomes on the turn
A turn that has not simply finished says so on itself, under its text, with the controls that recover it, rather than in the composer. Return a ChatTurnState from messageTurnState for an assistant message:
{ kind: 'streaming' }is a reply that is being written: it ends in a 2 px caret in the accent colour, and no line of time or actions sits under it yet. A turn with no state is drawn this way while text arrives.{ kind: 'reconnecting', attempt, attempts, nextTryIn, wait? }is a turn whose stream dropped. Its partial text reads muted with no caret, and a warning by the composer (the connection is what it affects, so it is not under the partial text) readsConnection lost. Reconnecting, attempt 2 of 5. Next try in 8 s., with Retry (onRetryConnection) and a bar that drains fromwaitseconds to the next try. The host countsnextTryIndown.{ kind: 'stopped' }is a turn the person stopped: a neutral card readsStopped. The answer above is partial.(Stopped before an answer.when the turn said only what it was doing and wrote none; a failed turn's heading readsFailed before an answer.; both areturnLabels), after the step row when there is one, with its time under it, with a secondary Discard (onDiscardTurn) on the left and a primary Continue (onContinueTurn) on the right.{ kind: 'failed', cause, keeps? }is a turn that failed partway: a danger alert readsThis answer is incomplete., then the cause, then what Retry keeps, with Retry (onRetryTurn).{ kind: 'empty' }is a turn that finished without an answer: a neutral row readsThe agent finished without writing an answer.with the turn's time and Retry (onRetryTurn), and no line of time stands under it.{ kind: 'complete' }is a finished answer, the default once nothing streams.
A stopped or failed turn draws its own stop, so a stopped note the run left on it is not drawn as well. advanceTurnState(state, event) moves a state on as the run reports what happened (connection-lost, reconnected, stop, continue, retry, fail, finish) and leaves it alone for an event that does not apply. Discard is not an event: the host removes the turn.
resolveTurnOutcome(conversation, { running, reconnect?, now, holding? }) reads the last turn's state from what the host knows, so the host keeps no copy of the stop-line presentation. It returns the conversation to render, with the stop line the state replaces removed, the id of the assistant message that carries the state, and the state itself: reconnecting while a dropped run's stream waits on its retry, stopped or failed from the stop line the run left, and empty when the last turn ended on tool activity or a blank reply with every call answered. holding says something else (an approval, a question, a failure the host shows) keeps the turn from being finished. turnStateOf(outcome, message) is the messageTurnState for it.
A turn that ends on its steps, because the run only called tools or narrated and then called them, has no reply to carry its outcome. Chat draws that outcome (stopped, failed or empty) after the steps, on an anchor message it makes for the turn: outcome.assistantId is the anchor's id, which turnStateOf answers for, and outcome.rowId is the last row of the turn, whose id carries the run. A dropped stream stays on the turn's own assistant message, and on the anchor only when the turn has none. The anchor has no row, line of time or footnote of its own, and a last call that errored or was refused does not change it.
The recovery callbacks (onRetryConnection, onContinueTurn, onDiscardTurn, onRetryTurn, onRegenerate) may return a promise. Chat runs one command per turn at a time: a second press while it runs does nothing, its control reads busy and the turn's other controls are held, and an answer that arrives after another conversation is shown, or after the turn moved to a state the command no longer fits, changes nothing. A callback that returns or resolves false, or throws, did not go through: the turn says so once, in turnLabels.commandFailed(command), until the next press. A callback that returns nothing went through.
The steps of a run say where they stand too. The step under way turns, its present-tense title ends in an ellipsis, and the group's header adds Step 2 of 3 once there is more than one step and how long it has run, counted from its message's time. Once a step fails, the header counts the steps that worked, 2 of 3 steps, 1 failed, and the failed row opens with Failed in view, what went wrong in danger text, the rest of the error wrapping under it, then Copy error and Retry (onRetryStep). turnLabels replaces any of these words; stepsDone can say what the steps were, such as Checked 2 of 3 sources. Tool-specific labels also include steps, calls, input, output, error, toolStatus, toolProblem, and toolAnnouncement, so the visible count, status, problem phrase, payload headings and live announcement can all be localized together.
Availability
Set availability while the conversation cannot be shown as it is. It replaces the transcript, and for two of its kinds the composer too:
{ kind: 'loading', slowAfterSeconds?, onCancel?, labels? }draws skeleton turns with a status line that readsLoading conversation…and the seconds so far. The editor stays, and Send readsLoading…and waits for the history; the typed text is kept. Once the read has run forslowAfterSeconds(default 10) the line says it is slow, with a spinner, the elapsed time and Cancel, which is drawn only whenonCancelis set. The ticking number is never in a live region: a screen reader hears the status once, and again when the read turns slow.{ kind: 'canceled', onRetry, allConversations?, labels? }is what the host sets after Cancel: a neutral state with a primary Retry and, when given, a secondaryallConversationsbutton. The editor stays open and Send is off, withsendBlocked(Retry to send messages.) beside it; the composer draws no notice of its own, since the state already says what happened.ChatInputtakes the same reason on its own assendDisabledReason.{ kind: 'error', cause, detail?, onRetry, allConversations?, labels? }replaces the transcript and the composer with Cinder'sErrorState: the title, thecausein plain words, an optionaldetailbehind a disclosure, a primary Retry and a secondaryallConversations.{ kind: 'deleted', allConversations, labels? }replaces them with a neutralErrorStatethat saysThis conversation was deleted, withallConversations(for example All conversations) as its primary button.{ kind: 'unconfigured', onConnect, labels? }says a model provider is missing. While the conversation has no message it is anEmptyState,Connect a model providerwith a primary Connect provider, in place of the transcript and the composer. A conversation that has messages keeps them: the transcript stays readable, a waiting approval stays answerable, and only the composer gives way, to one blocked row with the same title and primary action.
labels replaces any of the words (ChatAvailabilityLabels), and allConversations is a ChatAvailabilityAction, a label and an onclick. The transcript and the composer stay mounted but out of sight while a state shows, so a draft and the scroll position survive, and both come back when availability is cleared. For an archived or read-only conversation, whose transcript stays readable, use the neutral composerStatus bars above instead.
Guidance
Use When
- Shipping a full chat surface with composer, scroll-anchor, unread indicator, and attachments bundled as one heavyweight drop-in.
- Building an AI assistant or support thread where conversation state is modeled as a transcript of role-tagged messages.
Avoid When
- Rendering a one-off message list — compose lighter primitives directly instead of pulling the full suite.
- The transcript is read-only and needs no composer — a simple list of message bubbles is a better fit.
Attachment serialization
When capabilities.attachments is enabled, onSubmit receives ready ChatAttachment[] values. Use serializeChatAttachment() or serializeChatAttachments() from @lostgradient/chat to convert those files into transportable base64 payloads without spreading the full byte array onto the JavaScript stack.
Each serialized attachment has this shape:
The output is intentionally the base64 source payload for conversationalist's proposed DocumentContent bridge in stevekinney/agent-bureau#153. A consumer can wrap it as { type: 'document', name, mimeType, source: { kind: 'base64', data: content } } when adding composer attachments to conversation state.
No messages yet
When to use
- Shipping a full chat surface with composer, scroll-anchor, unread indicator, and attachments bundled as one heavyweight drop-in.
- Building an AI assistant or support thread where conversation state is modeled as a transcript of role-tagged messages.
- Embedding Chat in a definite-height flex or grid region where its internal transcript should own scrolling.
- Rendering a one-off message list — compose lighter primitives directly instead of pulling the full suite.
- The transcript is read-only and needs no composer — a simple list of message bubbles is a better fit.
Examples
Adapter-driven streaming
Use ChatAdapter.sendMessage with the public streaming builders while keeping the conversation snapshot synchronized with Chat's imperative stream.
Basic chat
A conversation with editable input and markdown rendering.
Composer actions
Render host-owned controls, here a model Select, in the composer footer beside Send with the composerActions snippet.
Composer in answer mode
A question is waiting: the composer reads Choose an answer above, or type your own…, and its button is Answer in place of Send. Picking a choice sends it at once.
Composer with an attached file
An attached file is a removable chip with its name and size, between the text and the control row.
Composer with attachment errors
Each failed file stays as a chip naming it, with the reason beside it and a Remove link: an unsupported type, a file over the limit, and a failed upload. The composer keeps the typed text and Send stays enabled for the text; a failed file is left out of the message.
Blocked composer, chat ended
A chat the server ended when it restarted: one blocked row with a secondary New chat button, no text box and no controls.
Blocked composer on a narrow card
On a narrow card the actions drop to a second line instead of overlapping the reason.
Blocked composer, no agent can do it
When no agent has the tool a chat needs, the reason appears once, as the composer’s blocked row, with a link to Agents; the agent select above it still reads Choose an agent. What was typed is kept and shows once an agent that can do it exists.
Blocked composer, no provider (Assistant can be chosen)
With no model provider the composer is one compact blocked row: the warning glyph and the reason on the left, Connect a provider, and a quiet Use Assistant link where Assistant can be chosen. There is no text box.
Blocked composer, no provider (fixed agent)
A chat whose agent is fixed does not offer Use Assistant: the row has the reason and Connect a provider only.
Blocked composer, agent plugin disabled
The agent’s plugin is disabled: the row names the agent and the plugin once, and Enable and restart opens a confirm dialog that says what happens to running work. The composer stays read-only until it is confirmed.
Blocked composer, restarting
After Enable and restart the composer says only what is new, with no action.
Blocked message bar on a waiting run
A run waiting on a person, with no provider connected: the shared blocked row (a warning glyph, “Connect a model provider to send messages”, and a Connect a provider link) sits under the question card, followed by a Cancel run button beside it. There is no message text box.
Blocked composer, server unreachable
While Interborough is unreachable the composer is one blocked row with only the reason: Retry lives in the banner, so there is no second retry button.
Compact composer: a test chat
A one-line composer for a small surface such as Try it: the field "Send a test message" and Send share one row, with the line about real tools under it. While an answer streams Send becomes Stop and the field is disabled; with no model provider the shared blocked row stands in its place.
Compact composer: a failed answer
Try it when the provider answers with an error: under the person’s message a titled danger block says “Couldn’t get an answer”, what failed and that nothing was saved, with Try again.
Compact composer: a tool call under way
Try it while an answer streams: the tool call shows as the line “Using Lookup order…” under the person’s message, above the partial reply “Category: damaged item, urgency” and its caret, with no line of time or Copy under the reply yet, and the field is disabled with Stop in the place of Send.
Composer formatting while it has focus
The composer styles Markdown in place (the bold span shows styled) and, only once the box has focus, draws a formatting toolbar with the words of its shortcuts: ⌘B bold, ⌘I italic, ⌘E code and ⌘⇧K link. Plain ⌘K is left to the host’s command palette.
Composer
The one composer row with a provider connected: the placeholder, attach, ghost selects for Model, Effort and Permissions, a context meter reading 38%, a quiet disabled Send, and the hint underneath.
New chat composer
A new chat’s composer is one bordered surface: a ghost agent select with the agent’s avatar at the top, the text, then a control row with attach, a ghost Permissions select and a quiet Send that stays disabled until there is text. The hint sits under the surface.
New chat composer with a model agent
With a model agent and a provider connected the control row shows ghost selects Model Claude Sonnet 5.5, Effort Medium and Permissions On changes asks, plus Send; the agent select reads Tool runner with its TR avatar.
Composer docked on a phone
At 375px the composer is docked to the bottom of the screen: the agent select on its first row, the placeholder, then attach, one ghost Settings control holding Model, Effort and Permissions, and a 44px secondary Send, disabled until there is text.
Composer with a queued follow-up
A follow-up is queued: the composer shows Stop and the line under it says it sends when the run is ready.
Composer while the stream reconnects
The stream dropped: the reply so far stays at full contrast, Stop stays, and the line under the composer counts the attempts. The run keeps going on the server.
Composer after a mid-reply setting change
Effort changed from Medium to High while a reply streams: the transcript shows the finished call (“Lookup order 4398 → $27.25, delivered Friday”, 0.4s) under the message and the streaming reply with a caret, the composer shows High and the line under it says when it applies. Stop is shown.
Composer with its settings folded
With a panel docked beside the conversation the composer is too narrow for Model, Effort and Permissions, so `composerControls` is told it is `folded` and the host draws one ghost Settings control in their place. The row keeps the attach button, the Settings control, the 38% context meter and Send, and never wraps.
Composer while the chat is working
Stop replaces Send while the chat is working, and the line under the box says a message now steers the run.
Density and variant
Compare comfortable vs compact density and bubble vs flat visual variant on the same conversationalist-shaped transcript.
Follow-ups during a run
Opt in to follow-ups with sendRunInput: the composer stays enabled while a run streams, Send and Stop sit side by side, and a follow-up shows as pending until the transport acknowledges it.
Full-height layout
Place Chat in a definite-height flex or grid cell with min-height: 0 so the transcript owns the scroll region.
Question with choices
A pick-one question with the payload’s own descriptions under each choice, and one field to type your own answer. Picking a choice answers at once.
Question with Undo
A choice picked with a five-second Undo window: the choice shows selected and one inline line reads “Answered Staging, Undo (5s)”. The count pauses while focus or the pointer is inside the question.
Question with Undo, a run’s own words
The question a run’s page draws: the same Undo window with the page’s words. The picked choice says “Selected” under its label and the others show their labels alone; the one inline line reads “Answer sent: Production. Undo for 5 s.” with the note of what happens next, and an Undo action.
Question answered
The same question once its Undo window has ended: the run has the answer and the line reads “You answered: Staging”.
Question with a structured answer
When the agent asks for fields, the answer is a form. Picking a value sends nothing; the host’s own Send answer button, beside what the agent does next, commits it.
Quoting agent messages
Select part of an assistant message, or use its Quote message action, to gather excerpts above the composer; sending puts them at the top of the message as Markdown block quotes.
Streaming chat
Streaming status keeps the composer in stop mode.
Transcript: the agent’s instructions
The agent’s instructions open the transcript as left-aligned muted text with no status fill, folded to one line, "Instructions, Show", that opens to the full text.
Transcript: interrupted while a changing tool ran
The run ended while Issue refund, a tool that changes things, was running. Its row shows "Interrupted, may have run" in danger text, and the status line says the call may have run and Retry goes back through the approval. It never says nothing was changed, so a refund cannot be issued twice.
Transcript: interrupted while a reading tool ran
The run ended while Lookup order, a tool that only reads, was running. Its row shows "Interrupted, didn’t finish" in danger text with an error glyph, never a dot, and the status line says the call didn’t finish and nothing was changed, with a secondary Retry that sends the turn again.
Transcript: a message that was not sent
Online, a message that could not be delivered keeps its bubble and shows a focusable red icon, its time and the red words "Not sent". The icon opens a popover that says "Not sent. Interborough couldn't deliver this message. Your message is kept." with an enabled Retry button.
Transcript: not sent while the server is unreachable
With the server unreachable the message stays visible as "Not sent". Its popover says "Not sent. Interborough can't be reached. Your message is kept.", Retry is inert, and "Retries when you're back online." says when it will try again.
Transcript: a queued follow-up
A message sent while the run is working is a dashed, pale bubble marked "Queued, sends when the run is ready", with Remove when the host can take it back. It never looks sent before the run reaches it, and becomes a normal message then.
Transcript: a reply and its message
A reply is plain text with no card or role label; a person's message keeps its tinted bubble. One muted line under each message holds its time, the host's actions (a model name, Reply details, Branch), Copy and, on a reply only, Quote. A message you sent shows Branch and Copy only.
Transcript: a reply that stopped partway
The failure is a status line below the partial reply, not agent speech: danger text with an error glyph, "The reply stopped partway: the model provider dropped the connection.", and a secondary Retry beside it. Retry replaces the partial reply with a fresh one.
Transcript: a reply that is streaming
While a reply streams, its tool call shows as a rail row with a spinner, “Running…” and the elapsed time, and the reply ends in a caret, with no line of time, Copy or Quote under it yet and no typing dots. Stop replaces Send in the composer.
Transcript: a reply streaming after its call finished
The call finished, so its rail row reads its result and its time (“Lookup order 4398 → $27.25, delivered Friday”, 0.4s), and the reply under it goes on streaming with a caret, longer than it was while the call ran. The chat header carries no line about settings: the status line is the only trace of a change.
With reasoning and steps
Assistant messages can surface a collapsible reasoning block (extended thinking) and an ordered step list before the final answer. Both are UI-only overlays derived from message metadata — the underlying transcript is unchanged.
With suggested replies
After the final assistant message, suggested follow-up labels appear as clickable chips. Clicking a chip calls onSuggestionSelect(label). The chips are derived from message metadata — the underlying transcript is unchanged.
With tool approval
Action-required tool results render as approval prompts the user must accept or reject before the tool can continue.
With tool calls
Tool results fold into the visible row with validated artifact metadata for opening a panel.
Props
Name | Type | Default | Description |
|---|---|---|---|
codeHighlighter | Highlighter | undefined | Highlights every code block in the transcript: Markdown fences, tool payloads and approval
commands. Build one with Cinder's shikiHighlighter over the grammars and themes the
application renders, so its bundle carries only those. Read when Chat mounts. Omit it and Chat
highlights any language Shiki knows, which bundles every Shiki grammar and theme unless the
build sets the explicit-code-highlighter condition; then a Chat without this prop draws plain
code. | |
conversation required | ConversationHistory | The conversation transcript to render. Pass a {@link ConversationHistory}
snapshot; consumers holding a stateful conversation object pass its current
snapshot (e.g. conversation.current). | |
atBottom bindable | boolean | true | Whether the message viewport is scrolled to the bottom. Bindable; updated automatically as the user scrolls. Default true. |
unreadCount bindable | number | 0 | Number of messages received while the viewport was scrolled away from the bottom. Bindable; resets to 0 when the user scrolls to the bottom. Default 0. |
newMessageIndicatorVisible bindable | boolean | false | Whether the "new messages" indicator is currently visible above the composer. Bindable; cleared automatically when the viewport reaches the bottom. Default false. |