Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Chat

ChatWidget renders streaming chat, tool calls, approvals, questions, and session history. AmodalChat wraps it with position="inline" and a runtime URL from the nearest AmodalProvider.

Import ChatWidget from @amodalai/react/widget for a chat-only integration, or from the package root when using provider hooks. The widget subpath also exports components and hooks for a custom chat interface.

Quick start

See SDK Overview for installation. For a multi-tenant app, point serverUrl at an application proxy that authenticates each request and authorizes scope and session access. The callback supplies your application token, and the proxy keeps runtime credentials. See Embedding for proxy requirements.

import { ChatWidget } from '@amodalai/react/widget';
import '@amodalai/react/widget/style.css';
 
<ChatWidget serverUrl="https://app.example.com/api/agent" getToken={getAppToken} position="floating" historyEnabled />;

Props

AmodalChat accepts every ChatWidget prop except position (pinned to inline); its serverUrl is optional and defaults to the provider's runtimeUrl.

A mounted widget reads only its props. Settings saved on the agent's Embed page do not reach it.

Connection and identity

PropDefaultMeaning
serverUrlrequiredBase URL of your application proxy, or the runtime for trusted direct access.
usernone{ id: string }; accepted but neither sent to the runtime nor displayed. It does not authenticate a user.
getTokennoneReturns a bearer token for serverUrl (sync or async): an application token for your proxy, or a runtime token for trusted direct access.
scopeIdnoneScope requested for chat sessions, memory, and agent store tools. A verified token scope takes precedence. A hosted browser session without a scope claim may request only its own user ID; another value returns 403.
scopeContextnoneKey-value pairs injected into connection API calls via contextInjection.
metadatanoneObservability-only values such as userId and screen; a map, or a function read on each send. See Request metadata.

scopeId identifies the tenant, workspace, or record; sessionId identifies one conversation. Reusing a scope does not resume a chat. Use resumeSessionId to continue a saved conversation; see Continue a conversation. Your backend must authorize the scope and session on every request.

Behavior

PropDefaultMeaning
positionfloatingSee Positions.
defaultOpenfalseStart open. Required for right and bottom, which have no launcher.
historyEnabledfalseSession history drawer. Each row shows the chat's status.
showHeader / showInput / showFeedbacktrue / true / falseHeader bar; input bar; thumbs up/down on assistant messages.
showModeltrueThe model that answered, as a muted label in each answer's action row, followed by · fallback when a fallback model answered.
autoFocusfalseFocus the input when it mounts.
keyboardShortcutsfalseHandle Shift+Esc, Mod+Shift+C, Mod+Shift+;, and Mod+Shift+L on the page. CHAT_SHORTCUTS lists them.
commandsnoneSlash commands { name, title, expand? } listed on / plus a partial name. A sent /<name> args goes out, and shows, as expand(args); without expand, as typed.
suggestionsnonePrompts shown on the empty conversation; choosing one sends it.
agentnoneRoot-agent surface name from the bundle's agents; that agent's declared resources scope what the session loads.
deployIdactive deployPin a specific deployment.
initialMessagenoneAuto-sent once on mount as the signed-in user. A string, or { text, attachments } to send files with it. A re-render with the same text does not send it again.
initialDraftnonePlaced in the input on mount for the user to review and send. An empty string clears the input; unset keeps the unsent draft.
resumeSessionIdnoneLoad an existing session on mount and continue sending on that session; a reply still running on the server shows live, with Stop. Takes precedence over initialMessage.

Callbacks

PropMeaning
onToolCall(call)A tool call completed; receives the full ToolCallInfo.
onKBProposal(proposal)The agent proposed a knowledge-base update.
onEvent(event)Every widget event (agent-driven and interaction).
onSessionCreated(sessionId)First stream init returned a session id.
onStreamEnd()The SSE stream ended.
onStateChange({ sessionId, messages })Session state changed (for external persistence).
onStreamEvent(event)Every runtime stream event of a live turn, including artifact publication and updates.

Extension points

PropMeaning
themeSee Theming.
widgetsWidgetRegistry of custom renderers for rich inline widgets.
inlineBlockRenderersRenderers for block types the widget doesn't render natively; native types (text, widget, reasoning, tool_calls, confirmation, ask_user, ask_choice, durable_approval, show_preview, file) cannot be overridden.
transformAnswerText(markdown, { streaming, messageId })Rewrites each piece of assistant markdown before the widget renders it, in live and restored messages, for example to rewrite the app's own link syntax. Copy and Read aloud use the result. streaming is true while the message's turn runs. It runs before the widget handles citation markers. See Citations. Root-relative links it produces reach onNavigate. Pass a stable function, because a new one re-renders every message.
resolveCitation(id)Returns { title, open }, with optional detail and locked, for one of the app's citation ids, or null to drop the citation. See Citations. Pass a stable function, because a new one re-renders every message.
streamFnCustom transport ((text, signal, images?, attachments?) => AsyncIterable<SSEEvent>) for chat messages. The widget still calls serverUrl to load history and to answer approval cards. To refuse a message, throw MessageNotSentError from @amodalai/react before yielding the first event. The widget puts the text, images, and attachments back in the message box and shows the error's message to the user.
onDurableApproval(sessionId, value, followUpMessage?)Required with a custom streamFn when handling durable approval cards. Submit the answer to the runtime and resume or follow the run. The standard transport does this itself.
askDisplayinline by default. Use docked when the host displays questions through AskChoiceBanner and durable approvals through DurableApprovalBanner, both from @amodalai/react.
entityExtractorsReplaces the default entity extractor for entity events.
onOpenFile(file)Open a published file in the host's own layout. Without it, the widget shows the file in place of the transcript. Render the file with FileViewer.
artifactProviderAn ArtifactProvider that discovers and previews files stored by the embedding app, including links and structured registrations in restored conversations.
onArtifactsChange(files)Receives the runtime's and the app's artifacts together.
autoOpenArtifactsDefaults to true. Opens newly produced artifacts when a live turn finishes; restored history stays closed. With workspace, an output opens as soon as it first appears during a live turn, and the newest wins.
workspaceInline only. Shows the chat's outputs, uploaded inputs, web research, and progress checklist in a rail beside the conversation, and opens them in a resizable side panel. See Workspace.
workspaceContentWith workspace, { outputs, panel?, onClose? }: the host's entries for the outputs rail, each { id, title, kind, onOpen }, the element shown in the side panel, and the callback that closes it.
presentationAssetsUrlThe same-origin directory of the presentation editor's assets. PowerPoint files then preview in the file viewer. With workspace, decks from presentation tool results also appear in the outputs rail and open in the slide editor.
onNavigate(path)Receives a plain left click on a root-relative link in an answer, such as /people/julian-marsh, in place of a full page load. Route it with the host's router. Modifier clicks, //host links, and artifact links keep their default handling.
renderAnswerFooter(message, { sessionId, sendMessage, answer })Renders host content, such as a follow-up card, under a finished answer, after its text and cards and before the action row. It runs for finished answers only, including restored ones, never while the answer streams. message is the AssistantTextMessage with its contentBlocks, so tool calls and results are readable. answer is the text the answer shows, without the reasoning folded above it, after transformAnswerText, with [[id]] citations as written. Returning null renders nothing.
renderAnswerActions(message, { sessionId, answer })Renders host buttons in a finished answer's action row, after Copy and Read aloud. It runs for finished answers only, including restored ones. answer is the same text renderAnswerFooter receives. Returning null renders nothing.
inputHint(text)Called on every render with the current text in the input box, including typed, dictated, and restored text. The returned content renders under the input in a status region, which stays in the page so screen readers announce each change. Returning null renders nothing visible.

Images in answers

Assistant Markdown shows an image only when it comes from the page's own origin. An image on another origin renders as a link. A browser fetches an image without a click, so a URL written by a model could otherwise send data to another host.

Attachments

The message box takes files picked with the attach button or dropped on it, including dropped folders, whose files keep their folder path as their name and whose hidden files are skipped.

  • When the agent has a sandbox and the widget uses its own transport, each file uploads as soon as it is added, through POST /api/uploads, and its chip shows the progress. The runtime publishes the limits through GET /api/uploads: up to 50 files per message and 50 MB per file, in the formats the runtime accepts, including Outlook messages, emails, ZIP archives, and legacy Word and Excel files. Send stays disabled, and the status line says "Uploading N files…", until every upload finishes. A file that fails to upload shows the reason and holds Send until it is removed. The message sends each uploaded file by its id.
  • Otherwise, files travel inside the message: up to 5 files of at most 20 MB each, as PDF, plain text, Markdown, CSV, PNG, JPEG, GIF, WebP, Word, PowerPoint, Excel, OpenDocument, or RTF. This is the case with a custom streamFn, which receives each file's bytes.
  • The extension decides a file's type, since browsers send no type for some formats. A file of another type shows "<name> is not a supported file type".
  • The Artifacts panel lists the conversation's uploaded files under "Files in this chat", above the files the agent made, in live and restored conversations. Each opens in the file viewer.

Citations

The model cites a source by writing its id in double square brackets after the claim, such as [[doc:q3-memo]] or [[web:5d41402a]]. Tell the model in the agent instructions which ids to cite.

  • Each marker becomes a numbered link. An id keeps one number for the whole answer, in order of first appearance.
  • The cited sources are listed under the answer. Clicking a citation or a list entry calls the source's open.
  • A source's optional detail is a second line under its title in the list, such as Email · Nov 3. The app formats it, including any date.
  • A source with locked: true shows a lock labeled "No access" for screen readers. A click still calls its open, so the app decides what to show.
  • A marker that is still streaming in stays hidden. Markers inside code stay as written.
  • Web search sources resolve with no app code, in live and restored conversations, including sources a sub-agent's answer cites. The list shows the site name, and a click opens the page in a new tab. A web: id that no search or sub-agent returned is removed, and so is a line the model copies from a sub-agent's source definitions.
  • With resolveCitation, a marker whose id it returns null for is removed. Without it, markers other than web: ids stay in the text as written.
  • A marker [[file:<fileId>]] or [[file:<fileId>#p<page>]] cites a file uploaded to the conversation. Its title is the file name, with the page when one is given, and a click opens the file in the viewer, at that page for a PDF. A file: id that names no uploaded file of the conversation is removed. The built-in reading-documents skill cites files this way.
  • transformAnswerText runs first, so it can rewrite another marker syntax into [[id]].
  • Copy writes citations as [1] and appends the numbered source titles. Read aloud and screen reader announcements leave citations out.
  • When a long conversation clears old tool results to save context, citations to those results can be lost when the conversation is restored.
const resolveCitation = useCallback(
  (id: string) => {
    const doc = documents.get(id);
    return doc ? { title: doc.name, open: () => openPanel(doc.id) } : null;
  },
  [documents],
);
 
<ChatWidget serverUrl={serverUrl} getToken={getAppToken} resolveCitation={resolveCitation} />;

A page that runs the conversation with useChat instead of ChatWidget renders the cited answer with CitedAnswer. It shows the latest assistant answer with the same numbered links, source list, and click behavior as the widget, and renders nothing until the answer has text. It takes messages and isStreaming from useChat, and the optional resolveCitation and transformAnswerText described above. Import @amodalai/react/widget/style.css for its styles.

const chat = useChat({ serverUrl, getToken: getAppToken });
 
<CitedAnswer messages={chat.messages} isStreaming={chat.isStreaming} resolveCitation={resolveCitation} />;

Imperative handle

The ref exposes ChatWidgetHandle:

const chat = useRef<ChatWidgetHandle>(null);
chat.current?.sendMessage("Summarize today's alerts"); // optional second argument: { attachments }, with base64 `data` or an uploaded `fileId`
chat.current?.getSessionId();

Other handle methods: stop(), isStreaming(), toggleHistory(), toggleArtifacts(), getArtifacts(), openFile(file), closeFile(), submitAskChoice(askId, values, message), and respondDurableApproval(sessionId, value, followUpMessage?).

flush(signal) saves every editor registered in the workspace and pauses it, and resolves to a release function. Call it before the host unmounts the widget, and call the release after the navigation commits or is cancelled. It rejects when an editor cannot save.

Workspace

With workspace, an inline widget splits its own width between the conversation and a side panel. A narrow widget stacks the two. The divider position is kept in localStorage.

An editor rendered in the side panel through workspaceContent.panel registers with usePendingEdits. The widget calls each registered function before every turn, including with a custom streamFn, and through flush(signal). The function saves the editor's edits and returns a release that resumes editing. A turn releases its editors when its stream settles. With leaving: true, the widget is about to unmount, so an editor that is still loading need not be waited for.

import { usePendingEdits } from '@amodalai/react/widget';
 
function DraftEditor() {
  usePendingEdits(async (signal) => {
    await saveDraft({ signal });
    lockEditing();
    return unlockEditing;
  });
  return <Editor />;
}

Positions

PositionBehavior
inlineRenders in-place within your layout
floatingFloating button that expands into a chat panel
rightFixed panel on the right side; needs defaultOpen
bottomFixed panel at the bottom; needs defaultOpen

While a chat is shown, the widget marks its session read for the session's owner, and again when each reply finishes. A chat counts as shown when the widget is inline or open, has area on screen, and its browser tab is visible. A widget hidden by the host page, for example with display: none, or a reply that finishes in a background tab leaves the chat unread until the widget is on screen again.

Theming

The theme prop covers the common cases:

<ChatWidget
  serverUrl={serverUrl}
  getToken={getAppToken}
  theme={{
    mode: 'auto', // 'light' | 'dark' | 'auto' (follows prefers-color-scheme)
    primaryColor: '#6e56cf',
    borderRadius: '12px',
    headerText: 'Ask the agent',
    placeholder: 'Type a message…',
    verboseTools: true, // full tool-call params, results, timing
  }}
/>

Other ChatTheme fields: backgroundColor, fontFamily, fontSize, userBubbleColor, agentBubbleColor, toolCallColor, emptyStateText.

Which key drives which surface

Each theme key sets one CSS custom property that drives specific surfaces. primaryColor also colors the floating launcher through an inline style, so overriding --pcw-primary in CSS does not recolor the launcher.

theme keyCSS variableSurfaces it controls
primaryColor--pcw-primarySend button, focus rings, accent text/links; launcher inline
backgroundColor--pcw-bgPanel and header background
userBubbleColor--pcw-user-bubbleUser message bubbles
agentBubbleColor--pcw-agent-bubbleAgent bubbles and inline cards
toolCallColor--pcw-tool-call-bgTool-call card background
borderRadius--pcw-radiusPanel, bubbles, buttons
fontFamily / fontSize--pcw-font / --pcw-font-sizeFont family: all text; size: all but answers, message box
headerText--pcw-header-text †Header title label
placeholder--pcw-placeholder †Input placeholder
emptyStateText--pcw-empty-state-text †Empty-conversation message
modedata-theme / prefers-color-schemeLight vs. dark palette (see below)

† These variables carry a text string, not a style value, and the text is rendered by the component rather than read back from the variable. Set the prop to change the copy; overriding the CSS variable alone has no effect.

Surfaces with no matching theme key (header/body text, muted text, borders, panel tint, shadow) are CSS-only: --pcw-text, --pcw-text-muted, --pcw-border, --pcw-panel-tint, --pcw-user-text, --pcw-shadow. Override those directly.

The composer and the inline reading column have CSS-only variables too:

CSS variableDefaultSurface
--pcw-composer-bg--pcw-bgMessage box card
--pcw-composer-shadownoneMessage box card shadow
--pcw-composer-radius16pxMessage box card corners
--pcw-composer-focus-border--pcw-text-mutedMessage box border while it has focus
--pcw-primary-text#ffffffSend button icon
--pcw-answer-font-size15pxAnswer text and the message box font size
--pcw-column-width768pxMaximum width of the transcript and composer in inline

An empty inline widget opens on the agent's name with the composer and any suggestions centred under it. Once the conversation starts, the composer moves to the bottom.

For anything the prop doesn't cover, override the CSS custom properties (no Tailwind dependency):

.pcw-widget {
  --pcw-primary: #6e56cf;
  --pcw-bg: #ffffff;
  --pcw-text: #1a1a1a;
  --pcw-border: #e5e5e5;
  --pcw-radius: 12px;
}

Chat panel

ChatPanelProvider and ChatPanel put a resizable chat panel on the right of a custom runtime app's pages. Below 1024px wide, the panel covers the page over a backdrop.

import { ChatPanel, ChatPanelProvider, PanelChat } from '@amodalai/react/widget';
import '@amodalai/react/widget/style.css';
 
const Conversation = () => <PanelChat showFeedback />;
 
<ChatPanelProvider
  runtimeUrl="/api/agent"
  storageKey="myapp"
  title="Ask"
  conversation={Conversation}
  navigate={navigate}
  locationKey={location.key}
  user={user}
  getToken={getToken}
>
  <AppRoutes />
  <ChatPanel />
</ChatPanelProvider>;
ChatPanelProvider propDefaultMeaning
runtimeUrlrequiredThe runtime that answers and keeps the conversations.
storageKeyrequiredPrefixes the keys that keep the open conversation and the panel's width.
title / logorequired / noneThe panel header's title, which also labels the panel, and an optional logo before it.
conversationrequiredA component that renders PanelChat. It mounts the first time the panel opens and stays mounted while the panel is closed, so it can be React.lazy.
navigaterequiredThe host router's navigate function. It receives root-relative links clicked in answers.
locationKeynoneA value that changes on each navigation. A full-screen panel returns to its docked width when it changes.
hotkeyMod+JToggles the panel. Mod is Cmd on macOS and Ctrl elsewhere. false turns the shortcut off.
user / getTokennoneAs on ChatWidget. user.id also keys the stored conversation.

PanelChat takes the ChatWidget props except those the panel sets: position, showHeader, serverUrl, user, getToken, resumeSessionId, initialMessage, initialDraft, autoFocus, keyboardShortcuts, historyEnabled, onSessionCreated, onNavigate, and workspaceTitle.

  • useChatPanel() returns the panel's state and actions. ask(text, { scope, attachments }) starts a conversation with that message, newChat(scope) starts an empty one, and openChat(sessionId) reopens a saved one. Each opens the panel. show, close, and reset change the panel without sending anything.
  • The browser tab keeps the open conversation per user, so a reload reopens it and rejoins an answer still running on the runtime.
  • usePanelPrefill(text) offers a question in the input of a new, empty conversation while the calling component is mounted. Text the user typed stays.
  • useChatList() returns { chats, error, refresh } for the signed-in person's chats that have messages, newest first. ChatList renders them with rename and delete, and picking one opens it in the panel. It takes an optional limit, an empty message, and an onPick(sessionId) callback.
  • The panel sets --pcw-panel-width and data-pcw-panel="open" or "expanded" on the root element, so the page can make room for it.
  • Full screen fills the width right of --pcw-panel-inset-left, which the host sets to its sidebar's width.
  • Escape leaves full screen, or closes the docked panel. When the panel covers the page, following a link in an answer closes it.
  • The hooks, ChatPanel, PanelChat, and ChatList throw outside a ChatPanelProvider.

Building blocks

For a custom chat surface, the /widget subpath exports the pieces ChatWidget is made of:

  • Components: MessageList, CitedAnswer, InputBar, SessionHistory, StreamingIndicator, ToolCallCard, AskUserCard, KBProposalCard, SkillPill, TagEditor, FormattedText, and WidgetRenderer (with its WidgetRegistry type).
  • Chat panel: ChatPanelProvider, ChatPanel, PanelChat, ChatList, useChatPanel, useChatList, and usePanelPrefill. See Chat panel.
  • Hooks: useChat (the widget's chat state machine), useWidgetEvents, useSessionHistory.
  • Chat API: listSessions, getSessionHistory, createSession.
  • Theme utilities: defaultTheme, applyTheme, mergeTheme.

The provider-based hooks and headless clients live in the package root; see @amodalai/react.