OpenMax
Free Trial

Message-display plugins

Draw a kind of message with your own component — how to write and install one, the capabilities it needs, the order of the message body, the read-only drawing when it is not installed, and sending events.

Message-display plugins

A message-display plugin claims a kind of message (by message.type) and draws that message's body with its own component. Interactive cards are a message-display plugin: the card plugin cardRenderer claims CARD messages; see Interactive cards.

Write a plugin

Define it with defineMessageRenderer:

poll-renderer.tsx

import {
  type ChatMessageRendererProps,
  defineMessageRenderer,
} from "@openmaxai/chat/message-thread";

function PollView({ message, readOnly, emit }: ChatMessageRendererProps) {
  const poll = JSON.parse(message.content ?? "{}") as { question?: string; options?: string[] };
  return (
    <div className="rounded-xl border p-3">
      <p>{poll.question}</p>
      {(poll.options ?? []).map((option) => (
        <button
          key={option}
          type="button"
          disabled={readOnly}
          onClick={() => emit("voted", { option })}
        >
          {option}
        </button>
      ))}
    </div>
  );
}

export const pollRenderer = defineMessageRenderer({
  id: "acme-poll",
  types: ["ACME_POLL"],
  layout: "bare",
  View: PollView,
});
Field (ChatMessageRenderer) Type Required Description
id string Yes Unique; clashing with another message-display plugin throws when the set is installed
types readonly string[] Yes The message types it claims (message.type). Not empty, and no built-in type (see Claiming rules)
matches (message: ChatMessage) => boolean No Narrows within types, for example to one schema. Without it the plugin takes every message of those types. Called during render, so do not throw
requiredPorts readonly (keyof ChatHost)[] No Host capabilities it needs; missing any one skips the plugin, without throwing
layout "bare" | "bubble" No Default "bubble": the body sits in a bubble. "bare" leaves the bubble out because the body has its own frame (cards do)
excerptQuote boolean No Default false. true lets users select text in the body and quote it; see Quoting selected text
View ComponentType<ChatMessageRendererProps> Yes The body component. It can use hooks, and it can be a React.lazy: the message's fallback_text shows while it loads

What View receives (ChatMessageRendererProps):

Prop Type Description
message ChatMessage The message
host ChatHost The current host. Read only the capabilities you declared in requiredPorts; the others may be missing
readOnly boolean The conversation is read-only: observing, an Agent collaboration, a DM whose peer can no longer receive messages, provisioning, or locked by the remote control — the same check that makes the composer read-only. What to draw when read-only is up to the plugin
senderIsAgent boolean Whether the sender is an Agent, by the participant's kind
participantMap Readonly<Record<string, ChatParticipant>> Optional. Conversation members by member id, for resolving names
interactions ChatMessageInteractions Idempotency keys and the double-click guard for this message; see Idempotency keys and double clicks
emit (name: string, payload?: ChatPluginEventPayload) => void Sends an event to the app; see Sending events
locale, t Interface language and the text lookup, same as the host's i18n

Only optional props will be added later.

Claiming rules

  • In the order of the installed array, the first plugin whose types include the message's type and whose matches is true (or absent) draws it. One type can have several plugins told apart by matches; put the more specific ones first.
  • Plugins claim by message.type, before the message area's own shape checks.
  • The built-in types TEXT, AGENT_TEXT, IMAGE, FILE and SYSTEM cannot be claimed (case-insensitive); installing such a plugin throws. Editing, recalling, @mentions, captions and media detection hang on these types, and system notices are drawn separately even earlier. The full list is CORE_MESSAGE_TYPES.

Installing

With the SDK, install through messageRenderers on ChatProvider:

app.tsx

import { CHAT_SDK_MESSAGE_RENDERERS, ChatProvider } from "@openmaxai/chat-sdk/react";
import { pollRenderer } from "./poll-renderer";

<ChatProvider host={host} messageRenderers={[pollRenderer, ...CHAT_SDK_MESSAGE_RENDERERS]}>
  {/* … */}
</ChatProvider>;
  • Without messageRenderers you get CHAT_SDK_MESSAGE_RENDERERS (the form-card plugin formCardRenderer and the card plugin cardRenderer). With it you get exactly the plugins you pass; to keep the defaults, put them in the same array.
  • The array can be written inline in JSX: while the plugin ids stay the same, the previous one is kept.
  • Events plugins send with emit and plugin failures go to createChatHost({ onEvent }); see Sending events.

With @openmaxai/chat directly, use MessageRenderersProvider. The MessageThread below is a component of @openmaxai/chat and has no style root: the SDK stylesheet applies only inside the .omx-chat component root each SDK component brings along, so put it inside ChatRoot and wrap it in an element with the class omx-chat (plus omx-dark in dark mode, with colorScheme="dark" on ChatRoot), or style it yourself. 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.

app.tsx

import { MESSAGE_RENDERERS, MessageRenderersProvider } from "@openmaxai/chat/message-thread";

<MessageRenderersProvider
  renderers={[pollRenderer, ...MESSAGE_RENDERERS]}
  onPluginEvent={(event) => track(event)}
>
  <MessageThread conversation={conversation} />
</MessageRenderersProvider>;
  • Without this wrapper you get MESSAGE_RENDERERS (formCardRenderer, cardRenderer) and plugin events go nowhere.
  • onPluginEvent receives the events plugins send; onRendererError receives reports of plugin failures.
  • It cannot be nested: ChatProvider already contains one, and wrapping another inside throws on mount. To change the plugin set, change the outer one.

Plugins whose capabilities are missing are skipped

A plugin declares the capabilities it needs in requiredPorts. If the host lacks any of them, the plugin is not installed and nothing throws; the messages it would claim go to the next plugin or the built-in drawing. A host without cards, for example, skips the card plugin and cards are drawn read-only. If the host changes at runtime, the plugins are picked again.

This differs from composer plugins: used with @openmaxai/chat alone, a composer plugin with a missing capability throws; a message-display plugin does not, because lacking a capability (for example cards) is a valid state.

Order of the message body

To draw a message body, the message area asks in this order and the first one that answers draws it:

  1. Message-display plugins (in installed order)
  2. The message area's own drawing: Agent replies, read-only cards, images and files, text
  3. The message's fallback_text

The body and the bubble shell come from the same single check. The host's render capability only says how text, Markdown and images are drawn, not who draws a message; the former render.renderStructuredMessage and render.renderCustomMessage are removed. See Migrating.

When the card plugin is not installed

When no plugin claims a CARD message (the host has no cards, or the card plugin is not installed), the message area draws it read-only: the body, the result line (with who answered) and the "superseded" / "expired" notices show; no business button is drawn; choices and "Create agent" are disabled with a tooltip saying answering is not available here (in a read-only conversation, that the conversation is read-only); a truncated card only says its content is incomplete, with no "expand". Nothing you click sends a request, and no message is sent in place of an answer.

Quoting selected text

Users can select part of a message body and click "Quote" next to the selection to quote that text in the composer. A plugin body offers this only when the plugin declares excerptQuote: true; without it, selecting and native copy work as usual but no "Quote" button appears. The default is off because the message area cannot see a plugin's structure: a body that is clickable as a whole would treat the end of a drag selection as a click. formCardRenderer, cardRenderer and read-only cards have it on.

With excerptQuote: true:

  • The quoted text is the visible text of the body. Buttons, inputs, selects, images, svg and aria-hidden elements are left out. Mark other interface text (status labels, times, counters, hints) with the data-excerpt-skip attribute and it is left out too, together with everything inside it. A control whose label is content, such as an option drawn as a button, can be marked data-excerpt-text so its label is included, as a line of its own.
  • A selection that holds nothing but such left-out parts shows no "Quote" button.
  • The click that ends a drag selection (or a touch long-press selection) inside the body is stopped before it reaches the body, so selecting never presses a button, follows a link or opens a clickable card. A plain click, and a click from the keyboard, is not affected.
  • Jumping back from the quote highlights that text in the body. If the body has changed since (expanded, answered, updated) and the text is no longer where it was, the first occurrence is highlighted, and if it is gone the whole message is.

Sending events

A plugin hands events to the app with emit(name, payload). The app receives an envelope:

{
  type: "plugin";
  pluginKind: "message-renderer";
  pluginId: string;  // the plugin's id
  name: string;      // emit's first argument
  payload: ChatPluginEventPayload;  // emit's second argument, {} when omitted
}
  • type, pluginKind and pluginId are filled in by the package from the installed plugin; the plugin cannot set them. A plugin cannot pose as one of the SDK's own events (their type is not "plugin") or as another plugin.
  • Put only JSON values in payload: no functions, React nodes or Error. The package passes it on as is without cloning, and warns when it is not a JSON value.
  • Delivered synchronously, in the order of the calls. Errors thrown by the receiver are caught (console.error) and do not affect the plugin.
  • Without a receiver (no onEvent in the SDK, or no onPluginEvent on MessageRenderersProvider), emit does nothing.
  • Call it only in event handlers and effects. Calling it during render warns: strict mode and concurrent rendering would send it twice.

Idempotency keys and double clicks

interactions is this message's interaction handle; plugins take it, they do not create it:

Member Description
idempotencyKey(actionId) The idempotency key for this button on this message. Network retries, timeout retries and clicking again after a failure all use the same key
resetIdempotencyKey(actionId) Call it when the host's verdict asks for a new key; only this button's key changes
pending A submission for this message is in flight
run(task) Double-click guard: while a submission is in flight it does not run and returns null; otherwise it takes the slot and frees it when task settles
subscribe(listener) Subscribe to changes of this message's in-flight state

They are kept on the host, so keys and in-flight state survive the virtual list unmounting and remounting the component; switching accounts (a new host) starts fresh. "The same host" is told by the host's instanceScope object: a hand-written host must hand out the same instanceScope for its whole lifetime and not rebuild it along with data such as members or presence, or an in-flight button becomes clickable again and a retry gets a new key.

Failures

When a plugin's View throws while rendering, only that message falls back to its fallback_text and the other messages are unaffected; when matches throws, that message is drawn with its fallback_text too. The failure is reported to the app: renderer.failed through onEvent in the SDK, or onRendererError on MessageRenderersProvider with @openmaxai/chat alone, once per message and plugin.