OpenMax
Free Trial

@openmaxai/chat

What each @openmaxai/chat entry point exports, and every field of the ChatHost object.

@openmaxai/chat

The chat UI and the ChatHost type it reads everything through (see host). Build the host with @openmaxai/chat-sdk or write it yourself. Peer dependency: react 19.

The components of this package have no style root: the SDK stylesheet (@openmaxai/chat-sdk/styles.css) applies only inside the .omx-chat component root each SDK component brings along. Rendered outside an SDK component, they need to go inside ChatRoot and into an element of yours with the class omx-chat (plus omx-dark in dark mode, with colorScheme="dark" on ChatRoot), or styles of your own; for the conversation list, message thread and conversation header with a host from createChatHost, use the components of @openmaxai/chat-sdk instead. A wrapper alone is not enough: outside ChatRoot, dialogs, menus and popovers portal to document.body, outside your wrapper, and get no styles; within ChatRoot they land in its overlay container, which carries the class omx-chat.

Entry point Use it for
@openmaxai/chat Everything common in one import
@openmaxai/chat/host ChatHost, the provider, hooks and capability types
@openmaxai/chat/conversation-list The conversation list
@openmaxai/chat/message-thread The message thread
@openmaxai/chat/composer The composer and its plugins
@openmaxai/chat/header The conversation header
@openmaxai/chat/group-management Create group, group info panel
@openmaxai/chat/surfaces Floating windows, dock, mobile drawer
@openmaxai/chat/preview A self-check view for your host
@openmaxai/chat/markdown The Markdown renderer behind agent replies
@openmaxai/chat/agent-runs Planned Agent run components

@openmaxai/chat

Export Kind From
everything in @openmaxai/chat/host ./host
ConversationList, KNOWN_GAPS_CONVERSATION_LIST component, constant ./conversation-list
MessageRenderersProvider, defineMessageRenderer, types ChatMessageRenderer, ChatMessageRendererProps, ChatPluginEvent ./message-renderers. MessageThread and KNOWN_GAPS_MESSAGE_THREAD are only on ./message-thread: the legacy message thread reads react-query, so the root entry does not need it
defineComposerPlugin, useComposerEngine, resolveDmReadOnlyCopy, KNOWN_GAPS_COMPOSER, type ComposerPlugin ./composer
ChatHeader, KNOWN_GAPS_HEADER, types ChatHeaderProps, ChatHeaderBadge ./header
CreateGroupModal, ChatInfoPanel, AddMemberContainer, KNOWN_GAPS_GROUP_MANAGEMENT, types CreateGroupModalProps, ChatInfoPanelProps, ChatMemberStatus ./group-management
CHAT_VERSION constant (string) This package's version. @openmaxai/chat-sdk must be the same version; see Installation

COMPOSER_PLUGINS, ChatFileDropZone, the resizable list column and ./surfaces are only in their own entry points. Each KNOWN_GAPS_* is a readonly string[] of what that module does not do yet.

@openmaxai/chat/host

ChatHost

Required fields form ChatCoreHost. A missing optional field hides its UI; the three marked "throws" make the component that needs them throw. Members, signatures and error rules of each capability: Host capabilities; fields of the data types: Data model.

Field Type Required What it does
identity ChatIdentityPort Yes Current user id, member and conversation-member lookup (synchronous), searchDirectory for the people picker
messaging ChatMessagingPort Yes sendMessage, loadThread, createConversation. Optional addReaction, removeReaction, recallMessage, editMessage, loadMessage, loadThreadSince, loadReadCursors, listMessageEdits each enable their feature; loadChangesSince together with getMessagesByIds enables catching up on changes
drafts ChatDraftsPort Yes get, save, clear, plus previews and subscribe for the list
inboundDelivery ChatInboundDeliveryPort Yes Parameters of the realtime connection the SDK owns: endpointUrl(), authToken(), clientId(), isMock(); the optional subscribe(onSignal) is the transitional entry point for host-forwarded signals (messages, read, reaction, messageChanged, card, delivery, reconnected). See Host capabilities · inboundDelivery
render ChatRenderPort Yes renderMarkdown, renderImage, renderMessageText, renderRichText, optional renderMention. To draw a kind of message yourself, use a message-display plugin
attention ChatAttentionPort Yes notify(level, message) for toasts, setUnreadSignal(count) for a badge
i18n ChatI18nPort Yes t(key, vars?) and locale()
instanceScope ChatInstanceScopePort Yes Query-key scope, invalidate("conversations" | "messages" | "members"), key–value storage
attachments ChatAttachmentsPort Yes limits, start, cancel, getTask, optional subscribeTasks and resolveUrls. maxAttachments: 0 hides the button
composerPreferences ChatComposerPreferencesPort No sendShortcut(): "enter" (default) or "mod-enter"; optional mentionListStyle(): "flat" (default) or "grouped" (the @-mention list arrangement)
localRecords ChatLocalRecordsPort No Synchronous get(key) / set(key, value), no remove: device-local records the package keeps for the current user (the people they mentioned recently). The package defines the keys (one prefix per feature, including the current user's id); the host must keep organizations apart; values are small and bounded, with no names, message text or credentials. Without it instanceScope.storage is used; give it when that storage is split per surface or conversation, or when two hosts of your app should share the records
mediaViewer ChatMediaViewerPort No open(slides, index). Without it images are not clickable. See Image viewer
conversations ChatConversationsPort No, throws list, setPinned, setHidden, optional setMuted, markReadUntil. ConversationList throws without it
groupManagement ChatGroupManagementPort No, throws createGroup, updateGroupProfile. CreateGroupModal and ChatInfoPanel throw without it
memberStore ChatMemberStoreReader No getMembers, subscribe (the read side of the @openmaxai/chat-store member store). The group info panel and MessageThread read conversation roles from it; without it roles count as unknown. See memberStore
workItems ChatWorkItemsPort No, throws search({ search, projectId?, cursor? }) for # references. With the default plugin set the composer throws without it. See Composer
subConversations ChatSubConversationsPort No findOrCreate. Context sub-conversations; without it no sub-conversation UI (no dot for has_unread_subconversations in the conversation list). See subConversations
mentions ChatMentionsPort No listUnread, markRead, markAllRead. Without it there is no "jump to @mention" button
connectors ChatConnectorPanelPort No snapshot, subscribe, toggle, refresh, dropRevoked, managementHref, openManagement, notify, onComposerSend, optional connectorActionHref, openConnectorAction, onPanelOpened, onConnectorToggled, searchCatalog. Only hosts that install connectorPanelPlugin need it
composerMenu ChatComposerMenuPort No snapshot, subscribe, notify, optional onMenuOpened. Only hosts that install composerPlusMenuPlugin need it
cards ChatCardsPort No isOperationAllowed, optional invokeAction, expandBody, settleChoice, submitInteraction, refreshCard, formDrafts, openCreateAgent. Without it there is no action footer. See Cards
profileCard ChatProfileCardPort No loadProfile, listOwnedAgents, openDirectMessage, openSelfSettings, optional openAgentManagement and peekProfile (a synchronous first frame). Without it avatars are not clickable. See Profile card
agentConfig ChatAgentConfigPort No loadModelState, setModel, setModelVisibility. Without it the header shows a disabled placeholder. See Header
agentGroupPolicy ChatAgentGroupPolicyPort No loadGroupPolicy, canManageGroupPolicy, setGroupReplyMode, setGroupAllowlist, openAgentSettings?. How agents reply in groups, see agentGroupPolicy
conversationResources ChatConversationResourcesPort No list(query, { signal? }): a conversation's images, files and links, newest first, paged by cursor; only rows of currently visible messages. See conversationResources
messageSearch ChatMessageSearchPort No search(query, { signal? }): search one conversation's messages; hits are currently visible messages only, matched against and quoting their current text. See messageSearch
agentRuntime ChatAgentRuntimePort No loadState, runAction. The management area of the info sidebar's agent identity card, see agentRuntime
navigation ChatNavigationPort No navigate, resolveHref. The chat components do not read it
workReferences ChatWorkReferencesPort No href(ref) (synchronous; the browser URL put on <a href>) and open(ref) (called on a plain left click; resolves "ok" | "denied" | "missing" | "failed"). The chat components do not read it; message rendering does (workReferences of ChatMarkdown, the SDK default render), see workReferences. Work references in message text ([#label](proj://…) / issue://…) always render as a chip; when the rendering layer does not get this port the chip is not clickable. To report failed opens, wrap it with bindWorkReferenceNotice from @openmaxai/chat/markdown (the SDK default render already does)
forward ChatForwardPort No forwardMessages, mergeForwardMessages (@experimental). With it and conversations, MessageThread and MessageThreadNext offer "Forward" on a message; see forward
agentRuns Planned ChatAgentRunsPort No cancelRun (optional subagentRunId stops one subagent invocation only), loadActiveRuns, loadRunEvents, optional loadAgentRuns, describeTool. Without it, no agent run progress is shown

ChatHostWithConversationList and ChatHostWithGroupManagement make conversations / groupManagement required. Degradation details: Capabilities.

Provider and hooks

Export Signature What it does
ChatHostProvider ({ host: ChatHost, children }) Not an install entry point; install the host with ChatProvider. Placed inside ChatProvider, it replaces some capabilities for the part of the UI below it, for example to add profileCard
useChatHost () => ChatHost Returns the installed host
useChatCapability <K extends keyof ChatHost>(key: K) => ChatHost[K] Returns one field of the host
useChatConversationsPort () => ChatConversationsPort Returns host.conversations
useChatGroupManagementPort () => ChatGroupManagementPort Returns host.groupManagement
ChatRequestCacheProvider ({ cache: ChatRequestCache, children }) Gives the part of the UI below it one shared request cache (the kind createChatRequestCache builds). One per scope: whoever installs it swaps in a new one or calls clear() when the organization or user changes
useChatRequestCache () => ChatRequestCache Returns the cache of the nearest ChatRequestCacheProvider; without one, falls back to a cache the component builds itself (for tests and standalone mounting only; components do not share it)

Hook errors

Thrown during render, with a Chinese message naming what is missing.

Hook Throws when Fix
useChatHost (and every component) There is no ChatProvider above it Wrap the tree in ChatProvider
useChatConversationsPort (used by ConversationList) host.conversations is missing Provide conversations, or do not render ConversationList
useChatGroupManagementPort (used by CreateGroupModal, ChatInfoPanel) host.groupManagement is missing Provide groupManagement, or do not render those components

Other exports

Export Kind What it does
ChatOperationNotAllowedError class Throw from recallMessage / editMessage when the server refuses (e.g. recall window passed). The UI says "cannot recall" instead of "failed, retry"
isChatOperationNotAllowed (error: unknown) => boolean Checks the chatOperationNotAllowed === true field; works across package copies, unlike instanceof
ChatMembershipUnknownError class Thrown by the host when, loading a conversation by id, it cannot tell whether the current user is a member (and fetching again would give the same answer). A deep link then says "can't confirm you're a member of this conversation" instead of "failed to open, try again"
isChatMembershipUnknown (error: unknown) => boolean Checks the chatMembershipUnknown === true field; as above, not instanceof
sendContentTypeFor (attachments) => "image" | "file" "image" when every attachment is an image
hostText (port, key, ns = "chat") => string | null Asks the host's i18n capability for one string; a raw key (with or without the ns: prefix), an empty string or a non-string counts as unknown and returns null, so you fall back to your own text. The SDK's built-in image viewer and the floating surfaces' button labels use the same rule
sweepFormDraftValue (raw, nowMs) => { action: "keep" } | { action: "remove" } | { action: "set"; value } For the host's form-card draft cleanup: keep a stored value, remove it, or write it back with a close time (voided records are removed 7 days after closing; the format belongs to the package, the host does not parse it)
can (actor, action, conversation, target?) => ChatPermission Whether the current user may do this in the conversation, with rules matching the server; see can
resolvePermission (permission, whenUnknown) => boolean Folds the three-state result of can into show-or-not
pluginsForHost (plugins, host) => plugins The plugins whose capabilities the host has: a plugin stays only if the host has every item in its requiredPorts; order is kept. Shared by composer plugins and message-display plugins
usePluginsForHost hook Same as pluginsForHost; returns the same array while the picked plugin ids stay the same
ChatComposerPreferencesPort, ChatMemberKind, ChatMentionInput, ChatMessageTextContext, ChatUploadStartHooks, ChatSendShortcut type The capability type of composerPreferences, and types used in member signatures Planned
ChatConnectorPanelPort, ChatConnectorPanelSnapshot, ChatConnectorPanelAvailability, ChatComposerConnector, ChatConnectorToggleOutcome, ChatConnectorToggledEvent, ChatConnectorPanelOpenSource, ChatConnectorCatalogSearch type The connectors capability (plug Connector panel) and its data types
ChatComposerMenuPort, ChatComposerMenuSnapshot, ChatComposerMenuOpenTrigger type The composerMenu capability (composer "+" menu) and its data types
ChatMemberPresencePort, ChatMemberPresenceStatus, ChatMemberRef, ChatMemberMarksPort, ChatMemberMarkSubject type The memberPresence capability (status dots on avatars) and memberMarks (the host-drawn avatar corner badge and name tag) with their data types
ChatAgentCapabilityTagsPort, ChatAgentCapabilityTag type The agentCapabilityTags capability (Agents' capability tags, read for the rows on screen) and its data type
ChatAgentActivityPort, ChatAgentRunView type The agentActivity capability (Agent run progress; read-only progress (experimental · transitional)) and its data type; ChatAgentRunView is ChatAgentActivityRun of @openmaxai/chat-store. Replaced when the planned Agent runs capability lands
ChatForwardPort, ForwardRequestBody, ForwardTargetInput, ForwardNoteInput, ForwardMentionInput, ForwardResponseData, ForwardTargetResult, MergeForwardTargetResult, ForwardNoteResult, ForwardTargetError, ForwardedCopy, MergedForwardCard type The forward capability (forwarding messages, @experimental) and its request and result types; fields in the Data model

Types: ChatCoreHost, ChatHost, ChatHostWithConversationList, ChatHostWithGroupManagement, the capability types ChatIdentityPort, ChatMessagingPort, ChatDraftsPort, ChatInboundDeliveryPort, ChatRenderPort, ChatAttentionPort, ChatI18nPort, ChatInstanceScopePort, ChatLocalRecordsPort, ChatAttachmentsPort, ChatMediaViewerPort, ChatConversationsPort, ChatGroupManagementPort, ChatMemberStoreReader, ChatWorkItemsPort, ChatMentionsPort, ChatSubConversationsPort, ChatCardsPort, ChatProfileCardPort, ChatAgentConfigPort, ChatAgentGroupPolicyPort, ChatAgentRuntimePort, ChatConversationResourcesPort, ChatMessageSearchPort, ChatNavigationPort, ChatWorkReferencesPort, and their data types: ChatWorkReference, ChatWorkReferenceOpenResult, ChatParticipant, ChatDirectoryMember, ChatDirectoryPage, ChatConversation, ChatConversationPage, ChatSubConversationContext, ChatSubConversationFindOrCreateInput, ChatSubConversationOwner, ChatSubConversationResult, ChatConversationParticipant, ChatMessage, ChatThreadPage, ChatThreadLoadOptions, ChatThreadSincePage, ChatThreadChange, ChatThreadChangesPage, ChatThreadMessagesByIdsPage, ChatAttachment, ChatUploadTask, ChatComposerDraft, ChatQuoteExcerpt, SendMessageInput, ChatSendOutcome, ChatSendBlocked, CreateConversationInput, ChatMessageEdit, ChatMessageEditInput, ChatMessageChangeResult, ChatReadCursorSnapshot, ChatInboundSignal and its variants (ChatInboundMessagesSignal, ChatInboundReadSignal, ChatInboundReactionSignal, ChatInboundMessageChangedSignal, ChatInboundCardSignal, ChatInboundDeliverySignal, ChatInboundReconnectedSignal, ChatInboundConnectedSignal, ChatInboundCatchUpSignal, ChatInboundTypingSignal), ChatImageViewerSlide, ChatCardActionInput, ChatCardChoiceInput, ChatCardFormAnswer, ChatCardInteractionInput, ChatCardActionResult, ChatCardActionErrorKind, ChatCardFormError, ChatOnboardingCardEvent, ChatMemberProfile, ChatProfileEntity, ChatUnreadMention, ChatUnreadMentionsPage, ChatWorkItem, ChatWorkItemKind, ChatWorkItemPage, ChatConversationResource, ChatConversationResourceBase, ChatConversationAttachmentResource, ChatConversationLinkResource, ChatConversationResourceKind, ChatConversationResourcePage, ChatConversationResourcesQuery, ChatMessageSearchHit, ChatMessageSearchPage, ChatMessageSearchQuery, ChatMessageSearchSnippetPart, ChatAgentModelOption, ChatAgentModelState, ChatAgentGroupPolicy, ChatAgentGroupScope, ChatAgentGroupReplyMode, ChatAgentPolicyApplyOutcome, ChatAgentPolicyRejectReason, ChatAgentRuntimeAction, ChatAgentRuntimeActionState, ChatAgentRuntimeActionUi, ChatAgentRuntimeState, ChatAgentRuntimeStatusRow, ChatCreateGroupInput, ChatGroupProfileUpdate, ChatGroupMembersChangeResult, ChatGroupLeaveOptions, ChatGroupLeaveResult, ChatInstance.

Every field is listed in the Data model.

can

function can(actor: ChatPermissionActor, action: ChatPermissionAction, conversation: ChatPermissionConversation, target?: ChatPermissionTarget): ChatPermission;
function resolvePermission(permission: ChatPermission, whenUnknown: boolean): boolean;

Whether the current user may do something in this conversation. A pure function whose rules match the server. It only decides whether a button is shown or enabled; the server has the final say, and a rejection needs a message.

action Allowed when
editGroupProfile A group (type: "GROUP") and the conversation role is OWNER or ADMIN
inviteMembers A group and the role is at least MEMBER (the server checks the group's who_can_invite, member by default; the front end cannot read that setting)
removeMember A group, the role is at least ADMIN, and the other person (target.role) ranks strictly lower; removing yourself is denied (use leave)
deleteGroup A group and the role is OWNER
recallMessage Your own message (target.senderId is me) is always allowed, the time window is the caller's; someone else's needs OWNER or ADMIN
mentionAll Only the server-computed conversation.can_mention_all; pass the conversation from the get-by-id detail, since list rows always carry false

Ranking: OWNER > ADMIN > MEMBER > PUBLISHER = SUBSCRIBER. The result has three states: { status: "allowed" }, { status: "denied", reason }, { status: "unknown", reason }.

  • An unknown role is not "no permission". When actor.conversationRole is missing or UNSPECIFIED (on the wire that is also what observers and unknown roles become), role-dependent actions return unknown; so does removeMember when the other person's role is unknown. Only actor.isMember === false (known not to be a member) returns denied (notMember).
  • Group actions in a conversation that is not a group are always denied (notGroup).
  • actor.orgRole does not change the result of any of these actions (the server does not read the org role for them).
  • resolvePermission(p, whenUnknown) folds the three states into show-or-not: allowed is true, denied is false, unknown is whenUnknown (the rule to apply when roles are not known, such as "show it and let the server reject").

Types: ChatPermission, ChatPermissionAction, ChatPermissionActor, ChatPermissionConversation, ChatPermissionTarget, ChatPermissionDeniedReason, ChatPermissionUnknownReason. With the Chat SDK, its permissions hook passes the current user's roles in for you.

@openmaxai/chat/conversation-list

Export Kind Notes
ConversationList component Props. Needs host.conversations
ResizableConversationListColumn component Drag-to-resize column. Props: width: number | null, onWidthChange(w: number | null), children, inactive?: boolean (pass true on narrow screens: the wrapper becomes display: contents, sets no width and shows no handle, and the list inside is not remounted)
clampConversationListWidth (w, viewportW?) => number Clamps a width to the allowed range
CONVERSATION_LIST_MIN_W, CONVERSATION_LIST_MAX_W constant 220, 560 (px)
CONVERSATION_LIST_MAX_VIEWPORT_RATIO constant 0.4: max 40% of the viewport (but never below the minimum)
CONVERSATION_LIST_WIDTH_VAR constant "--chat-list-w". ConversationList takes its width from it; ResizableConversationListColumn sets it on its own wrapper whenever width is not null, overriding an ancestor's value. See Theming · Layout
KNOWN_GAPS_CONVERSATION_LIST constant
ResizableConversationListColumnProps type
useResponsiveEnvironment hook The hook the list itself uses for narrow-screen / coarse-pointer checks: const [ref, { narrow, coarsePointer }] = useResponsiveEnvironment(), judged against the window of the node attached via ref. Wrappers around the list (such as the SDK's resizable) use the same rule

@openmaxai/chat/message-thread

Export Kind Notes
MessageThread component Props. Renders the composer itself
MessageThreadProps type
useThreadMessagesSnapshot hook (host, conversationId) => readonly ChatMessage[]. The messages the thread has already loaded for this conversation (ascending seq), read-only, no requests; reads the thread's own cache under the same host and follows it
KNOWN_GAPS_MESSAGE_THREAD, KNOWN_GAPS_COMPOSER constant
MessageRenderersProvider component Installs message-display plugins: renderers, onPluginEvent, onRendererError. Cannot be nested
defineMessageRenderer function Defines a message-display plugin
MESSAGE_RENDERERS constant The plugins installed without a MessageRenderersProvider: [formCardRenderer, cardRenderer]
cardRenderer, formCardRenderer constant The card plugin and the form-card plugin, both need the cards capability; see Interactive cards
CORE_MESSAGE_TYPES constant Types a plugin cannot claim: TEXT, AGENT_TEXT, IMAGE, FILE, SYSTEM
ChatMessageRenderer, ChatMessageRendererProps, ChatMessageInteractions type The plugin's shape, what its View receives, the interaction handle
ChatPluginEvent, ChatPluginEventPayload, ChatJsonValue, ChatRendererFailure type Plugin event envelope and data, the report of a plugin failure
ConnectionStatusBar component Connection status bar: tells the user when the realtime connection drops and offers a retry Planned
defineMessageAction function Defines a message-action plugin Planned
ChatMessageAction, ChatMessageActionContext type Shape and context of a message-action plugin Planned

@openmaxai/chat/message-renderers

Only the message-display plugin API, without the message area. Import from here when you install plugins but do not use MessageThread; importing from @openmaxai/chat/message-thread pulls in the whole message area. These are the same objects @openmaxai/chat/message-thread exports.

Export Notes
MessageRenderersProvider, defineMessageRenderer, MESSAGE_RENDERERS, cardRenderer, formCardRenderer, CORE_MESSAGE_TYPES Same as in @openmaxai/chat/message-thread
ChatMessageRenderer, ChatMessageRendererProps, ChatMessageInteractions, ChatPluginEvent, ChatPluginEventPayload, ChatJsonValue, ChatRendererFailure Types, same as above

@openmaxai/chat/composer

Export Kind Notes
COMPOSER_PLUGINS readonly ComposerPlugin[] Built-in: mention (@, needs identity and i18n) and the # work-item plugin (needs workItems)
defineComposerPlugin function Type helper for custom plugins
useComposerEngine hook The engine built from the current plugin set
ChatFileDropZone component Lets files dropped anywhere inside it (e.g. on the header) reach the thread
plainTextToHtml (text: string) => string Turns plain text into the HTML the composer draft understands: split on \n, one <p> per line; &, < and > are always escaped, so text such as <script> is never parsed as a tag. An empty string returns an empty string. Use it when a host writes text into a draft instead of building HTML by hand
resolveDmReadOnlyCopy (reason) => { title, detail } i18n keys for the DM read-only banner
KNOWN_GAPS_COMPOSER constant
ComposerPlugin, ComposerToolbarPanelProps, ComposerChrome, ChatFileDropSink type ComposerChrome is "card" | "flush"
ComposerCandidate, ComposerPanelProps, ComposerToolbarItem, ComposerNodeSpec type For writing plugins; see Write a composer plugin Planned
ComposerToolbarPlacementOverrides type Type of toolbarPlacement on ChatProvider: Readonly<Record<string, "bar" | "plus-menu">>
composerPlusMenuPlugin ComposerPlugin Composer "+" menu (Skills / Knowledge base). Needs composerMenu; not in COMPOSER_PLUGINS
connectorPanelPlugin ComposerPlugin Plug button, enabled-Connector capsule and Connector panel next to "+". Needs connectors; not in COMPOSER_PLUGINS. The two are independent; install both as [composerPlusMenuPlugin, connectorPanelPlugin, ...COMPOSER_PLUGINS]
collapseConnectors, connectorAuthState, connectorRowLayout, filterConnectors, orderConnectors, unauthorizedEnabledConnectors function Pure rules of the Connector panel (folding, three-state, search, order, enabled-but-unauthorized). There is no per-conversation enable limit.
shouldApplyMenuToggle, shouldSwallowTriggerPress function Click guards of the "+" menu
ComposerPlusMenuControl, ComposerToolbarSlotProps, ComposerLeadingSlotProps type For a plugin that takes over the "+" slot (ComposerToolbarItem.PlusSlot) or draws right after it (ComposerToolbarItem.LeadingSlot)

Plugins are installed through the plugins prop of ChatProvider, which defaults to COMPOSER_PLUGINS. A plugin whose requiredPorts are missing on the host is not installed; the rest of the composer works and nothing throws.

@openmaxai/chat/header

Export Kind Notes
ChatHeader component Props
ChatHeaderProps, ChatHeaderBadge type
conversationHeaderText function (conversation, t, options?) => ConversationHeaderText: computes headerTitle, headerSubtitle and badge from the conversation data, using the same title function as the conversation-list row; pass the list's memberNames as options.memberNames so the two names agree; the SDK's ConversationHeader uses it
ConversationHeaderText type { headerTitle: string; headerSubtitle: string | null; badge: ChatHeaderBadge | null }
ConversationHeaderTextOptions type { memberNames?: Readonly<Record<string, string>>; members?: readonly ChatParticipant[] }: options of conversationHeaderText; members (the conversation's members) is read only for an Agent collaboration conversation without agent_collab_participants, whose title is then its Agent members as "A ⇄ B"
CollabAgent, OnlineStatus type Types of the collabAgents and dmPeerStatus props; see Header · API Planned
KNOWN_GAPS_HEADER constant

@openmaxai/chat/group-management

All three components need host.groupManagement.

Export Kind Notes
CreateGroupModal component Props
ChatInfoPanel component Props
ChatGroupInfoBlocks, ChatGroupInfoBlocksProps, ChatGroupMembersTab, ChatInfoBlockState component The blocks of a group's "Info" tab in the conversation info sidebar: profile (edited in place), members ("People / Agents" pages, add, Agent reply mode), conversation settings, leave / dissolve. The member list's load state comes in membersState and affects only the member block; the page is controlled by membersTab. Writes go through groupManagement / agentGroupPolicy, as in ChatInfoPanel. @experimental
ChatGroupProfileBlock, ChatGroupProfileBlockProps component A group's name and description as read-only text, nothing else (no members, settings, exit or editing); needs neither groupManagement nor the member list. Used for an observed group in the info sidebar. @experimental
AddMemberContainer component Member picker used in the info panel
CreateGroupEntry component The "New group" button next to the conversation list search (pass to createGroupAction); opens CreateGroupModal
isGroupOwner, humanSuccessorCandidates, ownerLeaveWillDeleteGroup function "Owner leaves the group" helpers
KNOWN_GAPS_GROUP_MANAGEMENT constant
CreateGroupModalProps, ChatInfoPanelProps, ChatMemberStatus type

@openmaxai/chat/surfaces

Containers for a conversation outside the main page. You pass the conversation body in through renderBody. Usage, props and every store member: Floating windows, dock and drawer.

Export Kind Notes
FloatingChatLayer component Floating chat windows
FloatingChatLayerProps interface Props of FloatingChatLayer: ChatSurfaceProps plus the minimize animation target collapseAnchor
ChatDockColumn component Conversations docked as a column
ChatMinimizedDock component Avatars of minimized chats
ChatMobileDrawer component Bottom drawer, shown when isCompact is true
ChatAgentInfoBlocks, ChatAgentInfoBlocksProps component The info sidebar's "Info" tab for a DM with an agent: identity card (profile from loadProfile, status from memberPresence, tags from agentCapabilityTags, model control from agentConfig), the management area from agentRuntime, and the conversation settings (mute / pin, each only with its callback). Each section has its own skeleton and its own error with "Retry". @experimental
ChatMemberIdentityCard, ChatMemberIdentityCardProps component A read-only identity card for a member (avatar, name, online status from memberPresence), with no actions; the profile comes from loadProfile, falling back to the given name and avatar. Used for the other side of an observed DM when that side is a person. @experimental
ChatPersonInfoBlocks, ChatPersonInfoBlocksProps component The info sidebar's "Info" tab for a DM with a person: the person's card (profile from loadProfile, status from memberPresence), "Their Agents" (from listOwnedAgents, each a button calling onOpenAgent, plain rows without onOpenAgent; the whole section left out when there are none) and the conversation settings (mute / pin, each only with its callback). Each section has its own skeleton and its own error with "Retry". @experimental
ChatInfoSidebarLayout, ChatInfoSidebarLayoutProps component The conversation info sidebar's layout under a header: message area on the left, a resizable sidebar card on the right (an overlay when the container is narrower than 672 px), a bottom drawer when compact; with placement="cover" it covers the whole container with a back arrow instead (floating windows, dock tabs, the phone drawer). Open state, width and content come from props; a "Messages" tab only when messages is given and a "Files" tab only when files is given; with tab / onTabChange the selected tab is controlled. @experimental
ChatConversationFilesTab, ChatConversationFilesTabProps, ChatConversationFilesJumpTarget component The sidebar's "Files" tab (put it in ChatInfoSidebarLayout's files): the conversation's images, files and links from the host's conversationResources, newest first under "This week" / "Earlier", with search, a segmented All / Files / Links / Images filter and paging by cursor; refetched on the host's realtime signals for the conversation, never on a timer. Images open mediaViewer; "Show in chat" calls onJumpToMessage. @experimental
ChatConversationMessagesTab, ChatConversationMessagesTabProps, ChatConversationMessagesJumpTarget component The sidebar's "Messages" tab (put it in ChatInfoSidebarLayout's messages): searches the conversation through the host's messageSearch and lists the hits with marked snippets, paging by cursor. Picking a hit calls onJumpToMessage; notFound shows "This message is no longer available" and drops the hit. A realtime recall or delete hides the hit at once; edits, recalls, deletes and reconnects search again; nothing is kept after it unmounts. @experimental
ChatPrimaryDropZone component { enabled, stable?, children }. Declares an area (usually the conversation list column) as the main-chat drop zone: dropping a floating window or docked tab on it opens the conversation in the main chat (claimPrimary); dropping a list row back on it cancels. Draws a light-blue dashed outline and a hint while something is dragged over it. While a non-modal page dialog is open (the page is isolated) the zone takes nothing, same as the dock zone. With enabled false it renders only children; with stable it keeps a display: contents wrapper so flipping enabled does not remount children
useListRowDragOut hook Drag conversation list rows out of the list. { enabled, rowKeyOf, ghostOf, onDrop } ⇒ { onPointerDown, onDragStart, overlay }: put onPointerDown and onDragStart on the list container (the latter blocks the browser's native image drag on row avatars) (rows are found with rowKeyOf; pressing a button, link or form field inside a row does not start a drag, while a row that is itself a <button> drags normally and still gets its click when the pointer moves 6px or less, and its Enter / Space; "inside" means the control's parent still resolves to the same row in rowKeyOf, so put the key on the button when the button is the row); overlay is the card that follows the pointer and the dashed outline at the landing spot. A drag starts after the pointer moves more than 6px, mouse and pen only. Released over the main-chat drop zone ⇒ onDrop is not called; over the dock zone ⇒ { kind: "dock" }; anywhere else ⇒ { kind: "float", at } (top-left corner, kept inside the viewport). You write the registry in onDrop
useFloatingChatStore, useChatPreferencesStore hook Zustand stores for open chats and surface preferences
useChatSurfaceTitle, useChatSurfaceTitles hook (chat) => string / (chats) => string[]. A window's title kept up to date: the installed title source's answer for its conversation (see ChatSurfaceTitleSource), else the title stored when it was opened. Re-renders when the source notifies that conversation. The floating window's own title bar, ChatDockColumn, ChatMinimizedDock and ChatMobileDrawer read titles through it. @experimental
ChatSurfaceTitleSource interface { get(conversationId): string | undefined; subscribe(conversationId, listener): () => void }. Where window titles come from; install one with useFloatingChatStore.getState().setTitleSource(source), which returns its uninstaller and throws while another source is installed (one per page). undefined or "" falls back to the stored title. What it answers is never persisted. @openmaxai/chat-sdk installs one while its surfaces are mounted. @experimental
DOCK_COLUMN_WIDTH_VAR constant Name of the CSS custom property ("--chat-dock-column-width") the docked column sets on the root element: its rendered width as a CSS length, viewport cap included. Present only while the column is rendered, and updated on every frame of a resize drag. For fixed elements on the right edge of the viewport that must stay clear of the column, e.g. right: calc(var(--chat-dock-column-width) + 12px); give a fallback for when there is no column. The minimized dock uses it too
DOCK_RESIZE_HANDLE_OUTSET constant How far the docked column's resize handle sticks out past the column's left edge, as a CSS length ("0.625rem"); the column places the handle with it. Add it to DOCK_COLUMN_WIDTH_VAR when an element must also leave the handle grabbable
MINIMIZED_DOCK_INSET_VAR constant Name of the CSS custom property ("--chat-minimized-dock-inset") the minimized dock sets on <html>: the viewport-bottom height it occupies (px, including its 16px offset from the bottom edge), updated as the dock wraps or grows. The property is absent while the dock is not rendered — read it as var(--chat-minimized-dock-inset, 0px) so content near the viewport bottom (e.g. the main chat page's composer) moves clear of the dock
installChatSurfaceStorage function Call once at startup with a storage (e.g. localStorage) to persist and reload open windows and preferences. Without it nothing is persisted
setChatSurfaceStorage function Sets the storage without reloading the stores
switchChatSurfaceScope function (scope: string | null, owner?: string | null) => void. Keeps the open windows in a separate bucket per scope (e.g. per organization): the store key is stored as <key>:<scope>. Switching clears the windows in memory and loads the new scope's bucket (empty if nothing was saved there) without writing to either bucket, all in one synchronous call. null means no scope: windows are cleared and nothing is persisted. Calling it again with the same scope and owner does nothing. Hosts that never call it keep the single unscoped key. Preferences are not scoped. owner is the account a bucket belongs to: once given, every bucket records it (an owner field); on load, a bucket recorded for another account, or with no owner, is not used and is deleted, and when another account's bucket is found (and the storage can list its keys) every other bucket not owned by the current account is deleted too. null means the account is not known yet: windows are cleared, nothing is read or written, and surfacesHydrated stays false until a later call gives the account. Omitting it keeps the current owner. For hosts that never give an owner, the first scope read after the storage is installed takes over a leftover unscoped copy; hosts that give an owner delete it instead
handChatSurfaceScopeToHost function () => void. For a host whose storage is already separated per organization and account (e.g. @openmaxai/chat-sdk with instanceScope.storage): from then on the open windows are stored under the plain store key with no :<scope> suffix and no recorded owner, and switchChatSurfaceScope does nothing; closing and restoring windows on an organization or account change is up to the host. Call it before installing the storage; it cannot be undone on the page. @experimental
MIN_W, MIN_H constant Minimum floating window size (320, 280)
placementOf, detachedConversationIds, visibleConversationIds, mergeRestoredSurfaces function Selectors over useFloatingChatStore state: where a conversation is open ("primary", "detached" or null), conversations open on a detached surface (floating window, minimized to the dock, or docked tab — any presentation), conversations whose body is on screen now. mergeRestoredSurfaces merges restored storage into the current state
ChatSurfaceProps, ChatSurfaceScope, ChatSurfaceHeaderChrome, ChatSurfacePaneChrome, ChatSurfaceMode, FloatingChat, ChatSurfacePreference, RememberedGeometry, SendShortcut, MentionListStyle, ChatSurfaceStorage type
PrimarySurface, FocusedSurface, SurfacePlacement, SurfaceRegistryState type The conversation in the primary surface, the focused surface, the return value of placementOf, the selectors' input
ListRowDrop, ListRowGhost, UseListRowDragOutOptions type useListRowDragOut's drop result, card content (label, avatarUrl, colorKey, isGroupGlyph), and options

ChatSurfaceProps has isCompact: boolean, renderBody(chat, scope) and the optional renderHeader(chat, …), renderPane(chat, …), unreadCountOf(conversationId), unreadMentionOf(conversationId), mutedOf(conversationId) and onClaimPrimary(conversation) (called instead of the registry's claimPrimary when a floating window or docked tab is dropped on the main-chat drop zone; for hosts that keep the main selection themselves). isCompact is your app's page-level choice (drawer, or floating windows and dock); the components inside the body still lay out by their own container.

@openmaxai/chat/surfaces/store

Only the surfaces store and the persistence key, no components. For code that every page loads up front (for example cleanup on logout or account switch): importing @openmaxai/chat/surfaces there pulls the floating windows, dock column and dock into the first load. It exports the same store instance as @openmaxai/chat/surfaces.

Export Kind Notes
useFloatingChatStore hook The same one as in @openmaxai/chat/surfaces
CHAT_SURFACES_STORAGE_KEY constant Storage key for the persisted open windows ("cws-floating-chats")
switchChatSurfaceScope function The same one as in @openmaxai/chat/surfaces
handChatSurfaceScopeToHost function The same one as in @openmaxai/chat/surfaces
clearPersistedChatSurfaces function (storage) => void. Deletes that key and every scoped bucket of it (<key>:<scope>) from the given storage directly, whether or not the store has been loaded. storage needs key, length and removeItem. Use it when the account changes: installChatSurfaceStorage may not have run yet at that point, so clearing the store alone misses the stored copy

@openmaxai/chat/preview

Export Kind Notes
ChatContractSmoke component { conversationId?: string }. Loads members and messages and sends a message through ChatHost only. Use it to check a hand-written host

@openmaxai/chat/markdown

The Markdown renderer that draws agent replies in the default render of @openmaxai/chat-sdk (see createMarkdownRender). Use it directly when you write your own render.renderMarkdown, or to show Markdown elsewhere in your app.

Export Kind Notes
ChatMarkdown component Renders one Markdown string
DEFAULT_CHAT_MARKDOWN_LABELS constant The English strings used when labels is not given
DEFAULT_BROADCAST_MENTION_TYPE_BY_NAME constant Broadcast mention names (@所有人, @Everyone, @All agents and so on) and the mention type each stands for (all / all_agents)
DEFAULT_BROADCAST_MENTION_NAMES constant The names in DEFAULT_BROADCAST_MENTION_TYPE_BY_NAME; highlighted when a message has a broadcast mention
broadcastMentionDisplayName function (name, labels, idByName?, typeByName?): the text to show for a broadcast name found in a message, in the reader's language (labels); a name that is also a direct mention in the message, or that is not a broadcast name, comes back unchanged
resolveChatMarkdownMentions function Turns a message's structured mentions into the mentions prop
trimUrlBoundary function Cuts trailing punctuation, full-width prose and text written right after the host off a bare URL, the way autolinks are cut
trimUrlAuthority function Only the host part of that rule: cuts a URL at the first character after scheme:// (before the path) that a host, port or userinfo cannot contain, such as the ( in https://a.com(note); leaves the path and trailing punctuation alone
ChatMessageLink component One link in a message body: opens in a new tab by default; with navigation, same-origin conversation links open in the current page
matchInAppConversationHref function Tells whether a URL is a same-origin conversation link (see ChatMessageLink); returns { routeHref, browserHref } or null
isPlainLeftClick function Whether a click is a left click without modifier keys
ChatWorkReferenceChip component One work reference chip (reference plus optional links). With links it is an <a> with the real URL: a plain left click calls links.open (a click while the previous one has not returned is ignored), and links.onUnavailable when that does not succeed; modifier / middle clicks are left to the browser. Without links it is a <span> with the same look. ChatMarkdown and the SDK default render draw this chip
splitWorkReferences function Splits plain text into text segments and references, for your own renderMessageText (same pattern as the built-in text rendering)
splitMessageLinks function Splits plain text into text segments and { label, href } links: the [label](href) a person sends when pasting a hyperlink into the composer, http(s) / mailto / tel only. For your own renderMessageText; run it before bare-URL linkifying
isMisleadingLinkLabel function (label, href) => boolean: true when the label as a whole looks like a URL / domain / email but its host differs from href (after NFKC and stripping format and other default-ignorable characters; both sides compared as lowercase punycode with a leading www. ignored; userinfo or bidi controls also count). When true, do not render it as a clickable label; show "label (real URL)" instead
isAddressLikeLabel function (label) => boolean: true when the label as a whole looks like a URL / domain / email (same recognition as isMisleadingLinkLabel). When it is not misleading but this is true, wrap the label in <bdi dir="ltr"> like a URL: an RLO earlier in the text can reverse URL-like text so it reads as a different address
stripBidiControls function (text) => string: removes U+202A–U+202E and U+2066–U+2069 (embedding / override / isolate controls). Pass any shown URL or URL-like text (both parts of "label (real URL)", autolinked bare URLs, URL-like labels) through it and wrap it in its own <bdi> (URLs with dir="ltr"): a PDI / LRI inside the text defeats the <bdi> isolation, and a leftover RLO can then display the URL reversed. Display only (text, title); leave href as is
bindWorkReferenceNotice function (port, { attention, i18n }) => ChatWorkReferenceLinks: adds "on failure, attention.notify("error", t("workReference.unavailable.<result>"))" to the host's workReferences

Types: ChatMarkdownProps, ChatMarkdownHooks, ChatMarkdownNavigation, ChatMessageLinkProps, InAppConversationLink, ChatMarkdownLink, ChatMarkdownImageProps, ChatMarkdownImageSlide, ChatMarkdownArtifact, ChatMarkdownArtifactResolution, ChatMarkdownArtifactQuery, ChatMarkdownLabels, ChatMarkdownMentions, BroadcastMentionLabels ({ all, all_agents }, the broadcast names in the reader's language), ChatMarkdownMentionRow, ResolveChatMarkdownMentionsOptions, ChatWorkReferenceLinks (the shape of the host's work reference port, plus an optional failure callback), MessageLink (one link found by splitMessageLinks).

ChatMarkdown

import { ChatMarkdown, resolveChatMarkdownMentions } from "@openmaxai/chat/markdown";

<ChatMarkdown
  content={source}
  variant="chat"
  mentions={resolveChatMarkdownMentions(message.mentions, { selfId: me })}
  renderLink={({ href, label }) =>
    href.startsWith("/docs/") ? <InAppLink to={href}>{label}</InAppLink> : undefined
  }
/>;

GFM (tables, strikethrough, task lists, bare URLs), fenced code, and ```mermaid diagrams. The diagram renderer is downloaded only when a reply contains one; until then the source shows. HTML in the source is shown as text, and links other than http(s), mailto, irc(s), xmpp and relative ones are emptied unless isAllowedUrl lets them through. javascript:, vbscript: and data: URLs (links and images) are always emptied, whatever isAllowedUrl returns.

Prop Type Description
content string Markdown source. Required
variant "default" | "chat" "chat" inherits the bubble's font size and uses compact spacing. Default "default" (13px document text)
mentions ChatMarkdownMentions Which mentions to highlight; see below
className string Added to the root element (.kb-markdown)
renderLink (link: ChatMarkdownLink) => ReactNode | null | undefined Take over a link (for example in-app routing). Work references (proj:// / issue://) are drawn as chips by the package and never reach it. Return nothing to get the default: a new tab with rel="noopener noreferrer". artifact:// links never reach it. link.attributes holds the link's other attributes (such as title); spread them on your <a>
isAllowedUrl (url: string) => boolean Keep URLs with a custom scheme so renderLink can draw them. Work references (proj:// / issue://) are recognized and drawn as chips by the package and never reach it. javascript:, vbscript: and data: are never kept, even if this returns true
resolveArtifacts (uris: readonly string[]) => Promise<ChatMarkdownArtifactResolution> Resolves the artifact:// images and links in the reply, in one call. A failed call is retried once after 1 second. Nothing is cached: each mounted reply resolves its own. Without it (and without useResolveArtifacts) they show as unavailable
useResolveArtifacts (uris: readonly string[]) => ChatMarkdownArtifactQuery A React hook that resolves them instead, returning { status, data }; takes precedence over resolveArtifacts. Use it to keep results in your own cache (for example React Query) and clear it on org switch or sign-out. It is called on every render, also with no URIs (don't fetch then); pass a module-level function and don't switch between giving and not giving it
renderImage (props: ChatMarkdownImageProps) => ReactNode Draw an image yourself (for example with your framework's image component). Default <img>. Pass onError through so expired images show as expired
openImageViewer (slides: readonly ChatMarkdownImageSlide[], index: number) => void Open your image viewer; you keep its open state. Clicking an artifact:// image passes every image in the reply whose contentType is image/*. An artifact with another contentType does nothing when clicked; one without a contentType opens alone
renderImageViewer (props: { slides; index; onClose }) => ReactNode Draw the viewer and let ChatMarkdown keep its open state. Used when openImageViewer is not given. With neither, images are not clickable
labels Partial<ChatMarkdownLabels> imageUnavailable, imageExpired, fileFallback, fileUnavailableSuffix
navigation ChatMarkdownNavigation { navigate(href), resolveHref(href) }, the same shape as the host's navigation port, so you can pass that. When given, same-origin conversation links drawn by the default link open in the current page; see ChatMessageLink. Links taken over by renderLink don't use it
workReferences ChatWorkReferenceLinks Where work reference chips point and how they open (see ChatWorkReferenceChip above). Without it the chips are not clickable

ChatMarkdownMentions is { names, selfNames?, idByName?, broadcastTypeByName?, broadcastLabels? }. Each @ followed by a name in the text (outside code and links) becomes a <span class="cws-mention"> with data-mention-name, data-mention-id from idByName, and data-mention-type for broadcast names (@所有人, @Everyone, …), so copying it into the composer keeps the mention. Names in selfNames also get cws-mention-self (the pill). With broadcastLabels, a broadcast name shows in the reader's language (a message sent as @所有人 reads @Everyone to an English reader); data-mention-name keeps the name as written in the text.

import { ChatMessageLink } from "@openmaxai/chat/markdown";

<ChatMessageLink href={url} navigation={host.navigation}>{url}</ChatMessageLink>;

The default link of ChatMarkdown; use it for links in your own renderMessageText too. Without navigation it opens in a new tab (target="_blank", rel="noopener noreferrer"). With navigation, a same-origin conversation link (path is the home page from navigation.resolveHref("/"), trailing slash optional; only conversation / group / dm parameters, at least one non-empty; no #) gets no target, and a left click without modifier keys calls navigation.navigate("/?conversation=…") (no basePath); the host decides where the conversation opens. Cmd / Ctrl / Shift / Alt / middle click are left to the browser. javascript:, vbscript: and data: URLs never count. Other props (style, title and so on) go on the <a>.

resolveChatMarkdownMentions

function resolveChatMarkdownMentions(
  mentions: readonly ChatMarkdownMentionRow[] | null | undefined,
  options?: { resolveName?: (memberId: string) => string | undefined; selfId?: string; broadcastNames?: readonly string[] },
): ChatMarkdownMentions;

Reads message.mentions the same way the default render does: a name comes from username, else resolveName; rows without a name are skipped. Rows with is_mention_all are the server's expansion of a broadcast mention, not direct mentions: they add the broadcast names to names and nothing else. selfId marks the rows that mention the current user.

@openmaxai/chat/agent-runs

Planned

Export Kind Notes
AgentRunProgress Component One run's progress row, with tool steps and a stop button
AgentRunSteps Component Tool steps only
AgentStopButton Component Stop button only
AgentRunList Component All unfinished runs of one agent in this conversation
AgentRunPanel Component The Agent panel

Related types: the capability ChatAgentRunsPort, the realtime signal ChatAgentEventSignal (definition), and the store's ChatAgentRun and ChatAgentRunPart.