Conversation state

AIConversation shows a conversation, and AIMessageComposer takes what the user writes. Between them and your agent sits the state of the conversation: its messages, whether the agent is thinking or writing, the message on its way, and why the last request failed. AIConversationController holds that state and acts on it. You tell it how to reach your agent with a transport, and give it to both components as conversation:

import { useEffect, useState } from "react";
import type { Channel } from "stream-chat";
import {
  AIConversation,
  AIConversationController,
  AIMessageComposer,
} from "stream-chat-react/ai-components";
import { createChannelTransport } from "./transport";

export const Assistant = ({ channel }: { channel: Channel }) => {
  const [conversation, setConversation] = useState<AIConversationController>();

  useEffect(() => {
    const controller = new AIConversationController({
      transport: createChannelTransport(channel),
    });
    setConversation(controller);
    return () => controller.dispose();
  }, [channel]);

  if (!conversation) return null;

  return (
    <div className="assistant">
      <AIConversation conversation={conversation} />
      <div>
        <AIMessageComposer conversation={conversation}>
          <AIMessageComposer.AttachmentPreview />
          <AIMessageComposer.TextInput />
          <AIMessageComposer.Actions>
            <AIMessageComposer.FileInput name="attachments" />
            <AIMessageComposer.SubmitButton />
          </AIMessageComposer.Actions>
        </AIMessageComposer>
      </div>
    </div>
  );
};

createChannelTransport is written below. With these two components, the conversation:

  • Shows the user's message as soon as they send it, and the agent thinking until its reply starts.
  • Turns the composer's send button into a stop button while the agent answers, and stops the agent when it's clicked.
  • Loads older messages as the user scrolls up.
  • Offers to rate each finished reply, and to regenerate the latest one.
  • Offers to edit the user's latest message, which is then answered again.
  • Keeps the error of a request that failed, so the user can try it again.

If you know useChat from Vercel's AI SDK, AIConversationController plays the same part. It's the counterpart of AIConversation in the iOS SDK and of AIConversationController in the React Native SDK, with the same state and behavior.

You can also leave the controller out and pass the components your own messages, as described in Pass the messages yourself.

Info:

AIConversationController is available from version 15.0.1 of stream-chat-react, in the stream-chat-react/ai-components entry point. See Install the SDKs.

Make a conversation

Make one controller per conversation, and dispose of it once its screen is gone. It connects to its transport straight away, and dispose() disconnects it.

Make it inside a useEffect, and dispose of it in that effect's cleanup, as above. In development, React's StrictMode runs each effect, then its cleanup, then the effect again. A controller made in the effect is made again with it. A controller made once, such as with useState(() => new AIConversationController(...)), and disposed in an effect's cleanup, is disposed by the first cleanup and never connects again, so the conversation stops updating.

The effect makes a new controller whenever what it depends on changes, such as when the user opens another channel. To start over on something the effect doesn't depend on, render the component again with a key, such as <Assistant key={channel.cid} channel={channel} />.

The controller takes these options:

Option Description Default
transport How it reaches the agent and learns what the conversation holds. See Write a transport. -
actions { edit, rate, regenerate }: which of these the conversation offers. Pass false to leave one out. See Actions. All true
approver Who answers the approvals and sign-ins that tool calls wait for. AIConversation uses it unless it gets an approver of its own. See Reasoning and Tool Calls. -
composer The composer's store, for an app that fills it itself. Make one with createAIMessageComposerStore(). See Composer. A new store
replyTimeout How many milliseconds it waits, once the agent has a request, for the reply to start or the agent to say what it's doing. After that, it shows an AIAgentError. While the agent says it's working, it waits as long as that takes. null or Infinity waits as long as it takes. 5 minutes

With a conversation, AIConversation takes its messages, the message on its way, whether the agent is thinking and the loading of older messages from the controller, in place of messages, pendingMessage, isThinking and loadOlderMessages. It takes its approver and replyActions too, unless you pass them. AIMessageComposer shows the controller's composer store and sends through it. Their other props work as before. Conversation view and Composer cover each.

Follow its state

The controller keeps its state in conversation.state, a StateStore. useAIConversationState follows what a selector picks of it, and renders the component again when that changes. Keep the selector outside the component, so it stays the same between renders:

import {
  type AIConversationControllerState,
  useAIConversationState,
} from "stream-chat-react/ai-components";

const statusSelector = ({ status }: AIConversationControllerState) => ({
  status,
});

const { status } = useAIConversationState(conversation, statusSelector);
Field Description
messages The conversation as it shows, oldest first. While a reply is written again, or an edited message is answered again, the messages it replaces are left out until the new reply starts.
pendingMessage The message the user sent last that isn't in messages yet. It stays until its reply starts, and after its request was stopped or failed.
status Where the latest exchange is: 'ready', 'submitted', 'streaming' or 'error'. isAIConversationAnswering(status) is true for the middle two.
error Why the latest request failed. It stays until the next request, or until a reply starts after all. See Errors.
activity What the agent says it's doing besides what its reply shows, such as checking external sources, as an AIAgentActivity, or undefined.
hasOlderMessages Whether there are messages before the first one to load.
ratings How the user rated replies, by the reply's id: the rating they gave in the browser, or else the reply's own rating.

status is 'submitted' from the moment the user sends a message until the reply shows something, which is when the conversation shows the agent thinking. It's 'streaming' while the agent writes the reply, and 'ready' again once the reply is finished or stopped.

conversation.editingMessage is the user's message they're editing in the composer, if any.

Show what the agent is doing and errors

The conversation shows the agent thinking by itself, but not the rest of what it's doing, and not the errors. The footer of AIConversation shows under the latest turn's messages, so show them there:

import {
  AIAgentActivityStates,
  AIAgentError,
  AIConversation,
  AITypingIndicator,
  type AIConversationController,
  type AIConversationControllerState,
  isAIConversationAnswering,
  useAIConversationState,
} from "stream-chat-react/ai-components";

const footerSelector = ({
  activity,
  error,
  status,
}: AIConversationControllerState) => ({ activity, error, status });

const Footer = ({
  conversation,
}: {
  conversation: AIConversationController;
}) => {
  const { activity, error, status } = useAIConversationState(
    conversation,
    footerSelector,
  );

  if (error) {
    return (
      <div role="alert">
        {error instanceof AIAgentError && !error.agentMessage
          ? "The assistant is busy. Try again in a moment."
          : error.message}
        <button onClick={() => conversation.retry()} type="button">
          Try again
        </button>
      </div>
    );
  }

  if (
    isAIConversationAnswering(status) &&
    activity?.text &&
    activity.state !== AIAgentActivityStates.error
  ) {
    return <AITypingIndicator text={activity.text} />;
  }

  return null;
};

<AIConversation
  conversation={conversation}
  footer={<Footer conversation={conversation} />}
/>;

Errors

When a request fails, status is 'error', and error says why. It's one of two kinds:

  • The request failed, such as when the message couldn't be sent. It's the error your transport's send rejected with. retry() sends the same request again, with the same message id. A rejection with an AbortError ends the request without an error.
  • The agent couldn't answer. It's an AIAgentError, when the agent reports the error state (AI_STATE_ERROR) or its reply doesn't start within replyTimeout. Its agentMessage is what the agent said, if anything. Without one, its message is the English AI_AGENT_ERROR_MESSAGE, "The agent couldn't answer. Try again.", so check for an AIAgentError without an agentMessage to show copy of your own, or a translation, as above. retry() asks the agent for the reply again, without sending the user's message twice.

clearError() forgets the error and the request that failed.

When the user stops the agent, what it wrote so far stays, and status goes back to 'ready', even while the channel still marks the reply as generating. If the reply hadn't started, the user's message stays, and a reply that still arrives doesn't make the conversation answering again. The reply itself keeps its isGenerating, and shows as being written, without its actions, until your backend stores its final update with generating: false, as Stop the reply describes. A reply stopped before it showed anything is hidden. The conversation ignores what the agent says it's doing until the agent clears it.

Act on it

The components call the controller's methods, and you can call them too, for example from a button of your own:

Method What it does
send({ text, attachments, chatOption, custom }) Sends a message, or the edit of the message being edited. Only text is required.
stop() Stops the reply the agent is writing.
regenerate(reply) Asks for a new reply in place of reply and the messages after it.
edit(message) Puts one of the user's messages in the composer to edit. The next message they send replaces it.
cancelEditing() Stops editing, and empties the composer.
retry(), clearError() See Errors.
rate(reply, rating) Rates a reply, 'positive' or 'negative', or takes the rating back with null. Ratings reach the transport in the order the user gives them, and one it can't take goes back to the rating it has.
loadOlderMessages() Loads the messages before the first one, while there are any.
dispose() Stops following the transport.

While the user edits one of their messages, send sends the edit of that message. To send a message of its own from your code, such as a suggestion or a generated UI's action, stop editing first with cancelEditing(), which also empties the composer.

For example, a suggestion can be sent with the chat option picked in the composer, which conversation.composer holds:

<AISuggestions
  suggestions={suggestions}
  onSelect={(text) => {
    if (conversation.editingMessage) conversation.cancelEditing();
    const { chatOption } = conversation.composer.getLatestValue();
    conversation.send({ chatOption: chatOption ?? undefined, text });
  }}
/>

Actions

The conversation offers what the controller's actions allow:

  • Under each finished reply, the reply actions: copy and share, rate (rate), and, while the agent isn't answering, regenerate on the latest reply (regenerate).
  • On the user's latest message, while the agent isn't answering, an edit button (edit). The message goes back into the composer, which shows "Editing" with a button that cancels it, and the next message the user sends is an 'edit' request.

For components of your own, conversation.replyActions(reply, isLatestReply) gives what the conversation offers for a finished reply, as the props of AIReplyActions, and conversation.editAction(message) gives the edit for the user's latest message, while the agent isn't answering and actions.edit is on, or undefined for any other message.

Write a transport

The transport is the part that knows your agent. It follows what the conversation holds and tells the controller through a feed, and it sends what the user asks. It's an AIConversationTransport:

type AIConversationTransport = {
  connect: (feed: AIConversationFeed) => void | (() => void);
  send: (request: AIConversationRequest) => Promise<void>;
  stop: () => Promise<void>;
  loadOlderMessages?: () => Promise<void>;
  rate?: (reply: AIMessage, rating: AIMessageRating | null) => Promise<void>;
};
Member Description Default
connect Starts telling the feed what the conversation holds. The controller calls it once, when it's made, and calls the function it returns once it's disposed. -
send Sends what the user asks. Resolve once the agent has the request: the reply arrives through the feed. A rejection shows as the error. -
stop Stops the reply the agent is writing. What it wrote so far stays. -
loadOlderMessages Loads the messages before the first one, which arrive through the feed. -
rate Tells your backend how the user rated a reply, or null when they took their rating back. A reply's rating field shows the one your backend has, until the user rates it again. Kept in the browser

The feed, an AIConversationFeed, has three updates:

  • updateMessages(messages) - the conversation's messages, oldest first, each time they change.
  • updateHasOlderMessages(hasOlderMessages) - whether there are messages before the first one.
  • updateActivity(activity) - what the agent says it's doing, as an AIAgentActivity, or undefined once it stops saying. Its state uses the states of Stream Chat's AI indicator, which AIAgentActivityStates lists: thinking, checkingExternalSources, generating and error. Its text is what the agent says about it, such as "Searching the web".

feed.isConnected turns false once the controller is disposed. Stop following what the conversation holds once it does.

While the agent says it's working, the controller waits for its reply as long as that takes, and the conversation shows it thinking until the reply starts. An error state ends the request with an AIAgentError that carries its text.

Requests

send receives an AIConversationRequest:

Field Description
kind What the user asks for: 'message', 'regenerate' or 'edit'. It's an open set, so treat a kind you don't know as a new message.
messageId An id for the user's message. Create the message with it, so the conversation finds its copy by it.
text What the user wrote. When a reply is written again, the text of the message it answers.
attachments The Files the user picked, in the browser, to upload with their message.
chatOption The chat option the user picked in the composer, such as thinking harder.
custom What the composer's store holds as custom, or what your app sent with the request, such as a generated UI's action as custom.uiAction.
message The message it's about: the reply to write again, or the user's message they edited.

A retry sends the same request again, with the same messageId. If the first attempt reached your backend, or you keep a copy of the failed message, use the id so the message isn't added twice.

While a 'regenerate' or an 'edit' is on its way, the controller leaves out the messages it replaces. Once the new reply starts, it shows the messages as the feed has them again, so update the conversation on your backend before the new reply arrives:

  • For a regenerate, remove the request's message and the messages after it, or write the new reply in place of message, under its id. Without a message, it asks for a reply to the latest message, which has none, such as after the agent couldn't answer it.
  • For an edit, change the user's message to say the request's text, under its id, and remove the messages after it.

A transport over a Stream Chat channel

With Stream Chat, the conversation is a channel. This transport follows the channel's messages through its message paginator and its AI indicator events, sends what the user asks as a message in the channel, and stops the agent with channel.stopAIResponse():

transport.ts
import type { Channel } from "stream-chat";
import {
  type AIConversationTransport,
  fromStreamMessage,
} from "stream-chat-react/ai-components";

// Your app's: uploads the files and returns their attachments.
import { upload } from "./upload";

export const createChannelTransport = (
  channel: Channel,
): AIConversationTransport => ({
  connect: (feed) => {
    const unsubscribe = channel.messagePaginator.state.subscribe(
      ({ hasMoreTail, items }) => {
        feed.updateMessages(
          (items ?? []).map((message) => fromStreamMessage(message)),
        );
        feed.updateHasOlderMessages(hasMoreTail);
      },
    );
    const subscriptions = [
      channel.on("ai_indicator.update", (event) =>
        feed.updateActivity({ state: event.ai_state, text: event.ai_message }),
      ),
      channel.on("ai_indicator.clear", () => feed.updateActivity(undefined)),
    ];
    return () => {
      unsubscribe();
      subscriptions.forEach((subscription) => subscription.unsubscribe());
    };
  },
  send: async (request) => {
    // A regenerate asks the question again, and an edit sends the new text as a new message.
    await channel.sendMessage({
      message: {
        id: request.messageId,
        text: request.text,
        attachments: await upload(request.attachments),
      },
    });
  },
  stop: () => channel.stopAIResponse(),
  loadOlderMessages: async () => {
    await channel.messagePaginator.toTail();
  },
});

Load the channel with channel.watch() before you show it. A few things to keep in mind:

  • channel.sendMessage() resolves once the server has the message, and rejects when it couldn't be sent, which shows as the conversation's error.
  • A channel has no way to write a reply again or to edit a message, so this transport asks the question again for a regenerate, and sends an edit as a new message. The messages they replace come back once the new reply starts. If your backend can't remove or replace them, leave those actions out: new AIConversationController({ transport, actions: { edit: false, regenerate: false } }).
  • Ratings stay in the browser unless the transport has a rate. To show the ratings your backend keeps, set them as each message's rating, which the conversation shows until the user rates the reply in the browser.
  • The request's chatOption and custom aren't sent here. Send them the way your backend reads them, such as in the message's custom fields.

For an agent with an API of its own, follow its messages the same way, and send the requests to it, where a 'regenerate' and an 'edit' can replace the messages they're about.

Generated UI

To show the UI your agent writes in place of a reply's text, pass an AIUIHost to AIConversation as ui. What the user does in a reply's UI is an AIUIAction: send it through the controller, with the action as custom.uiAction, so it's on its way like any other message:

import { useMemo } from "react";
import { createA2UIRenderer } from "stream-chat-react/a2ui";
import {
  AIConversation,
  type AIConversationController,
  AIUIHost,
  aiUIActionJSON,
} from "stream-chat-react/ai-components";

// Your components, as Generative UI describes.
import { placeCard } from "./components";

export const Conversation = ({
  conversation,
}: {
  conversation: AIConversationController;
}) => {
  const ui = useMemo(
    () =>
      new AIUIHost({
        components: [placeCard],
        renderers: [createA2UIRenderer()],
        send: (action) => {
          // Otherwise the action would be sent as the edit of that message.
          if (conversation.editingMessage) conversation.cancelEditing();
          conversation.send({
            text: action.label,
            custom: { uiAction: aiUIActionJSON(action) },
          });
        },
      }),
    [conversation],
  );

  return <AIConversation conversation={conversation} ui={ui} />;
};

The host counts each action as sent once it's handed to the controller: a request that fails shows as the conversation's error, with a way to retry, and not through the host's onError. The controller sends nothing for an action whose label is empty, so give every action a label.

The transport then finds the action in the request's custom, and sends it the way your backend reads it. With a Stream Chat channel, that's the message's ai_ui_action custom field. Build the message in a function of its own, in transport.ts:

import {
  AI_UI_ACTION_CUSTOM_DATA_KEY,
  type AIConversationRequest,
  type AIUIActionJSON,
} from "stream-chat-react/ai-components";

/** The message a request sends, with its UI action as `ai_ui_action`. */
const messageFor = async (request: AIConversationRequest) => {
  const uiAction = request.custom?.uiAction as AIUIActionJSON | undefined;
  return {
    id: request.messageId,
    text: request.text,
    attachments: await upload(request.attachments),
    custom: uiAction ? { [AI_UI_ACTION_CUSTOM_DATA_KEY]: uiAction } : undefined,
  };
};

Then have the transport's send call channel.sendMessage({ message: await messageFor(request) }).

Everything else stays as it is: the actions show under each finished reply, also one that answers only with UI, and the user's latest message offers to edit it. The thinking indicator gives way to a reply's UI as soon as it shows. The controller's status can't tell a reply from its UI alone, so it stays 'submitted' until the reply has text, steps or attachments, or is finished. Keep that in mind in a footer that reads the status.

Messages

The components take each message as an AIMessage:

Field Description Default
id The message's stable identity. -
role Who wrote it: "user", "assistant", or a role of your own, which shows as the agent's. Each of the user's messages starts a turn. -
text What it says. A reply's text is Markdown. -
isGenerating Whether the agent is still writing it. false
parts The steps the agent took for it, in order. []
attachments What it carries besides its text, such as images and files, as AIMessageAttachmentData. []
reasoningText (stepId) => string: the whole of a reasoning step's thinking, when your app has it. Otherwise the step's excerpt shows. -
uiDocument The UI the agent wrote for a reply, which shows in place of its text. See Generative UI. -

A message the user sent that isn't in the channel yet, such as while its photos upload, is an AIPendingMessage, with an id, a text and attachments. The controller keeps it as its pendingMessage. Without a controller, Show a message while it's sent covers it.

Messages from Stream Chat

fromStreamMessage turns a Stream Chat message into an AIMessage:

AIMessage From the Stream Chat message
id, text Its id and text.
role "assistant" when custom.ai_generated is true, "user" otherwise.
isGenerating custom.generating.
parts Its ai_reasoning and ai_tool_call attachments.
attachments Its image and file attachments. Attachments of other types are left out.
uiDocument custom.ai_ui, on a reply only.

Pass isAssistant to tell the agent's messages apart some other way, such as by the user who sent them, and reasoningText when your app has the whole of the reasoning:

fromStreamMessage(message, {
  isAssistant: (message) => message.user?.id === "juno",
  reasoningText: (messageId, stepId) => reasoning.get(messageId, stepId),
});

What your backend sends covers how the backend sets these fields.

Steps of a reply

An agent writes each step it takes while replying, a round of reasoning or a tool call, as a custom attachment on its reply. parseMessageParts(message.attachments) reads them, skipping attachments that aren't steps, and fromStreamMessage does it for you. Each step is an AIMessagePartData:

Field Description
id The step's stable identity.
kind The attachment type: ai_reasoning, ai_tool_call, or another ai_ type.
reasoning A round of reasoning, read: its status, and its summary, preview and durationMs.
toolCall A tool call, read: its name, status and executor, its arguments, and the approval or sign-in it waits for.
payload The attachment's fields, for a kind of your own or fields the SDK doesn't read.
version The step's format version (v). A step in a newer version keeps its payload but has no reasoning or toolCall.

The kinds and statuses are open sets, so new ones don't break your code. Reasoning and Tool Calls shows the steps, and its Step format lists what the backend writes.

Pass the messages yourself

Without a controller, the components keep no conversation themselves: they show the data you give them, and hand you what the user does. You work out the messages, the message on its way, whether the agent is thinking, the ratings and the retries in your app. With Stream Chat, the channel holds that data: its messages, with the agent's replies and their steps, and its AI state, which says what the agent is doing:

import { AIStates } from "stream-chat";
import type { Channel, MessagePaginatorState } from "stream-chat";
import { useAIState, useStateStore } from "stream-chat-react";
import {
  AIConversation,
  AITypingIndicator,
  fromStreamMessage,
} from "stream-chat-react/ai-components";

const itemsSelector = (state: MessagePaginatorState) => ({
  items: state.items,
});

export const AssistantConversation = ({ channel }: { channel: Channel }) => {
  const { items } = useStateStore(
    channel.messagePaginator.state,
    itemsSelector,
  );
  const { aiState } = useAIState(channel);

  return (
    <AIConversation
      messages={(items ?? []).map((message) => fromStreamMessage(message))}
      footer={
        aiState === AIStates.ExternalSources ? (
          <AITypingIndicator text="Checking external sources" />
        ) : undefined
      }
    />
  );
};

The channel's message paginator holds its loaded messages oldest first, which is the order the conversation expects, and updates as the backend writes the reply. Load the channel with channel.watch() before you show it. Conversation view covers the rest of what AIConversation takes without a controller, such as pendingMessage, isThinking and loadOlderMessages.

Follow what the agent is doing

useAIState from stream-chat-react returns what the agent is doing in a channel, as aiState:

import { AIStates } from "stream-chat";
import { useAIState, useChannel } from "stream-chat-react";

export const useIsAnswering = () => {
  const channel = useChannel();
  const { aiState } = useAIState(channel);

  return (
    aiState === AIStates.Thinking ||
    aiState === AIStates.ExternalSources ||
    aiState === AIStates.Generating
  );
};

aiState is one of the AIStates from stream-chat, or a state of your own that your backend sends. Say what the agent is doing lists them, and the events that set them.

A few things to know about it:

  • Pass it the channel. It doesn't read the channel from context, so pass it, for example from useChannel(). Without one, it returns AI_STATE_IDLE.
  • It reads the channel's own state. The client keeps the state on the channel, in channel.state, from its ai_indicator.* events. So when you show another channel, the hook shows that channel's current state rather than starting from AI_STATE_IDLE. Channel keeps its children mounted when the channel changes, so state of your own components carries over to the next channel: reset it yourself if it belongs to one channel.
  • The connection resets it. When the connection drops, the client sets the state back to AI_STATE_IDLE, since the events that end a reply aren't replayed.

useAIState in the hooks reference has the details. To show the state, see Show what the agent is doing. To stop the reply, call channel.stopAIResponse(), as Stop the reply in the composer shows.

What your backend sends

With Stream Chat, your backend writes the agent's reply into the channel, and the components show what it writes, through your transport or the messages you pass. A typical backend posts an empty placeholder message as the agent, updates it as the model streams, and stores the final text. Stream Agents, the Stream Chat AI SDK and the LangChain SDK do all of this for you. With a backend of your own, follow the conventions below, which the components and Stream's backend SDKs share. The AI message streaming guide covers the whole backend flow.

Mark the agent's replies

Set two custom fields on the agent's reply:

  • ai_generated: true, when the backend creates the placeholder. Your app reads it to tell the agent's replies apart, and your backend checks it to skip the agent's own replies instead of answering them.
  • generating, true on every update while the reply streams, and false on the final one. It's the only field that tells a client a reply is in flight.
import { StreamClient } from "@stream-io/node-sdk";

const client = new StreamClient(apiKey, apiSecret);

const { message } = await client.chat
  .channel(channelType, channelId)
  .sendMessage({
    message: { text: "", user_id: botId, custom: { ai_generated: true } },
  });

The client keeps custom fields under message.custom, so read them as message.custom.ai_generated and message.custom.generating. Declare them for TypeScript as optional fields, so messages without them still type-check. Custom data types explains the declaration file:

stream-custom-data.d.ts
import "stream-chat";

declare module "stream-chat" {
  interface CustomMessageData {
    ai_generated?: boolean;
    generating?: boolean;
  }
}

The SDK uses them in these places:

  • fromStreamMessage reads ai_generated as the message's role, and generating as isGenerating.
  • The message list. Pass isMessageAIGenerated={(message) => !!message.custom?.ai_generated} to Chat. MessageUI then renders those messages with StreamedMessageText, which types them out, and hides their "Edited" label, which every update of the text would show. The channel list shows their preview as plain text instead of rendering its Markdown. SDK integration shows the setup.

The message list doesn't read generating: a reply types out only the text it grows by after it shows, so a stored reply doesn't type itself out again. Read generating in UI of your own, for example to show a cursor while the reply streams.

Say what the agent is doing

Before the first word of the reply arrives, the model can spend a while thinking or calling tools, and the message is still empty. The backend says what it's doing with ai_indicator.* custom events on the channel, which set the channel's AI state:

Event type Sent by aiState becomes Means
ai_indicator.update Backend The event's ai_state The agent's state changed. Carries the ai_state, the cid, the reply's message_id, and an optional ai_message.
ai_indicator.clear Backend AI_STATE_IDLE The reply is done. Sent after the final text is stored.
ai_indicator.stop App AI_STATE_STOP The user stopped the reply. See Stop the reply.

The ai_state of an update is one of these:

ai_state AIStates The agent is...
AI_STATE_THINKING AIStates.Thinking Thinking.
AI_STATE_EXTERNAL_SOURCES AIStates.ExternalSources Calling a tool, such as a search.
AI_STATE_GENERATING AIStates.Generating Writing the reply, which streams into the message.
AI_STATE_ERROR AIStates.Error Unable to answer. The backend writes the error into the message.

A typical reply sends AI_STATE_THINKING right after the placeholder, AI_STATE_EXTERNAL_SOURCES while a tool call runs, AI_STATE_GENERATING with the first token, and ai_indicator.clear once the final text is stored. Use these names, so the components' states match your backend's. If your backend sends states of its own, read them from aiState the same way, and show them with components of your own.

The Stream backend SDKs don't send ai_indicator.clear after an error, so aiState stays AI_STATE_ERROR until the next reply starts, or the connection drops. Anything you show for it stays up until then.

The indicator events reach only the clients connected when they're sent, and aren't stored, so a user who opens the channel halfway through a reply sees no state until the next event arrives. Use them for the indicator only, and rely on the message's text and generating, which arrive with every update, for the reply itself.

Stop the reply

When the user stops the reply, the app calls channel.stopAIResponse(), which sends ai_indicator.stop. The default composer's stop button does it, and Stop the reply shows a button of your own.

The event carries only the channel's cid, not a message id, so on the backend treat it as "stop whatever reply is in flight in this channel". Abort the model's stream, then finish the way a normal reply finishes: store the text written so far with a regular partial update and generating: false, then send ai_indicator.clear. Without that final update, the message stays as it was last stored.

Stream with ephemeral updates

A regular partial update writes the message to the database on every call. A long reply flushed every few tokens turns into hundreds of writes, and with several conversations at once, you can hit the rate limits for message updates. While the reply streams, update it with client.chat.ephemeralMessageUpdate() instead (ephemeral_message_update in Python). It takes the same payload as client.chat.updateMessagePartial() and sends the same message.updated event, so the reply types itself out the same way, but it stores nothing.

The last update must not be ephemeral. When the model finishes, store the complete text with a regular partial update, and generating: false. Otherwise anyone who opens the channel later loads the last stored version of the message: the empty placeholder, still generating. The same goes for whatever else ends the reply, such as an error or the user stopping it.

// While the model streams: send the latest text without storing it.
await client.chat.ephemeralMessageUpdate({
  id: messageId,
  set: { text, generating: true },
  user_id: botId,
});

// Once the model is done: store the final text.
await client.chat.updateMessagePartial({
  id: messageId,
  set: { text, generating: false },
  user_id: botId,
});

Ephemeral updates are server-side only: call them from your backend, not from the browser. Every server-side SDK has them: the AI message streaming guide shows each one. Even ephemeral updates reach every device watching the channel, so don't send one per token: flush every 20 or so chunks, or at most every 50 to 100 ms, which keeps the typing smooth.