OpenMax
Free Trial

Errors and expired sessions

Handle failed requests, failed sends, expired tokens and render errors.

Errors and expired sessions

Error notifications

When an action fails, the chat reports it through the host's attention capability. The default shows nothing, so connect it to your toast component:

import { createChatHost } from "@openmaxai/chat-openmax/react";

const host = createChatHost({
  baseUrl: "https://openmax.com",
  wsUrl: "wss://openmax.com/ws",
  auth: { mode: "token", getToken },
  ports: {
    attention: {
      notify: (level, message) => toast[level](message), // your toast library
      setUnreadSignal: (count) => setTitleBadge(count),
    },
  },
});

This is the one-line OpenMax form; for the connection options see Connect to OpenMax. With your own backend, use createChatHost({ adapter, ports }) from @openmaxai/chat-sdk/react; ports is passed the same way. With a custom host, pass the same object in ports to createLocalPorts.

Failed sends

A failed message stays in the thread, marked "Send failed":

  • Retry resends with the same id and content. If the upload failed, it re-uploads the same files first.
  • Delete removes it locally.

If your server's content filter refuses a message, the messaging capability should return { blocked: { refusalText } } instead of throwing. The message stays with a notice and a delete button, and no retry.

Card buttons show errors inside the card; see Interactive cards.

SDK error types

Error When Import from
ChatSdkConfigError Thrown synchronously by createChatHost on invalid options (for OpenMax, for example: missing baseUrl, no wsUrl and no realtime: "off", unsupported auth.mode) @openmaxai/chat-sdk
ChatSdkError An adapter call failed; carries a kind, retryable, and the backend's status and code @openmaxai/chat-sdk
ChatSdkRequestError An OpenMax REST request failed; a subclass of ChatSdkError with the kind derived from the HTTP status @openmaxai/chat-openmax

The kinds, the fields and the isChatSdkError check are in @openmaxai/chat-sdk · Errors; how OpenMax derives the kind from the status, the code when getToken() fails ("token_unavailable") and the two cases that are not ChatSdkRequestError yet are in @openmaxai/chat-openmax · Errors. message is a sentence for the user: components show a non-empty message as is; when it is empty they use their own copy (group-management writes such as creating a group pick it by kind, the rest use the operation's fallback). @openmaxai/chat-openmax gives that sentence only for a backend code it knows; the backend's text is only in cause.

useChatSdkConversationList() returns the last error and a refetch, for an error state on the conversation list. That error, and the error when host.openConversation fails, is always a ChatSdkError: when the adapter threw something else, the SDK converts it with toChatSdkError (a network TypeError becomes network, AbortError becomes cancelled, TimeoutError becomes timeout, everything else unknown), with the original in cause. Only these two; the errors of reading messages inside MessageThreadNext are still the originals. The conversion is in @openmaxai/chat-sdk · Errors · toChatSdkError.

Unified errors

To branch your own UI on the kind, check with isChatSdkError, not instanceof; to do the same with an error caught elsewhere, convert it with toChatSdkError first:

import { isChatSdkError } from "@openmaxai/chat-sdk";

function describe(error: unknown) {
  if (isChatSdkError(error) && error.kind === "network") return "Network connection failed";
  return "Something went wrong";
}

Expired sessions

The SDK does not refresh tokens itself:

  1. The first request that needs a token calls getToken() and caches the result.
  2. On a 401 it calls getToken({ refresh: true }) (renew for real at this point) and re-sends once with the new token. Requests refused together (or one after another) share one renewal. When getToken returns { token, expiresAt }, the token is renewed before it expires, and only a 401 with code AUTH_TOKEN_EXPIRED renews; any other 401 goes straight to step 3 without renewal (see Connect OpenMax · Tokens and expiry).
  3. If the retry also gets 401, the request rejects with ChatSdkRequestError (status: 401).
  4. The WebSocket trades the same token for a one-time ticket; a 401 there also renews first and exchanges again. If that is still refused after renewal, or getToken() fails with a credential failure, it stops reconnecting; when the server closes the connection because the credentials are no longer valid (for example a revoked personal API Key), it does not reconnect either, and that also counts as an expired session. Create a new host after the user signs in again. A 403 on the ticket request (the credentials are valid but may not get a ticket, for example a personal API Key without the needed permission) also stops reconnecting, but is not renewed and does not count as an expired session.
  5. When the renewal endpoint is offline or times out, the credentials may still be fine: have getToken() throw a ChatSdkError with kind network, and the request fails with network. That is not an expired session; realtime backs off and reconnects as usual, and the next 401 renews again. Only a plain Error or an empty string is unauthorized.

So renew the session, or redirect to sign-in, inside getToken():

import { ChatSdkError } from "@openmaxai/chat-sdk";
import { createChatHost } from "@openmaxai/chat-openmax/react";

const host = createChatHost({
  baseUrl: "https://openmax.com",
  wsUrl: "wss://openmax.com/ws",
  auth: {
    mode: "token",
    getToken: async ({ refresh } = {}) => {
      // refresh is true when the token in hand was just refused with a 401: renew for real
      let token;
      try {
        token = refresh ? await session.renew() : await session.getFreshToken();
      } catch (e) {
        // renewal endpoint unreachable: the credentials may be fine, report network (not an expired session; the next 401 renews again)
        if (isNetworkFailure(e)) throw new ChatSdkError("network", "renew failed", { cause: e });
        throw e;
      }
      if (!token) {
        redirectToLogin();
        throw new Error("signed out");
      }
      return token;
    },
  },
});

When renewal fails (no token, or the re-sent request still gets 401), or the ticket is still refused after renewal (a renewal that failed because of the network does not count, see step 5), the SDK calls attention.notify("error", …) once with "your session has expired"; several requests failing together give one notice. The one-line config above does not take onUnauthorized (known gap); to redirect to sign-in at that point, use createChatHost({ adapter: createOpenMaxAdapter(config), onUnauthorized }), which is also called once; see Error model · onUnauthorized.

Failed identity requests (your profile, conversation members) are not retried for 5 seconds. Until your profile loads, your own messages are drawn as someone else's.

Render errors

Planned

Each area of the chat has its own error boundary: when one area throws during render, only that area switches to a fallback, the others carry on, and the page does not go blank. You don't wrap anything yourself.

Area (ChatRenderErrorArea) Wraps Fallback Resets on its own
conversation-list ConversationList "This part can't be shown right now" and "Retry" —
header ChatHeader Same When the conversation changes
message-thread The message list, not the composer Same When the conversation changes
message One message "This message can't be shown" in the bubble's place, no retry; the other messages of the conversation render as usual When that message's content_version changes
composer The composer "This part can't be shown right now" and "Retry"; the draft is already in drafts and comes back after the retry When the conversation changes
info-panel ChatInfoPanel Same as conversation-list When the conversation changes
agent-runs AgentRunList, AgentRunPanel Same as conversation-list When the agent changes
  • Retry remounts that area once; data already in the store is not requested again.
  • Only render errors are caught. Failures of clicks, sends and other actions do not go through the boundary; they use Error notifications and each action's own rollback as before.
  • Missing-capability throws are caught too (next section) with the same fallback; development builds also log which capability is missing.
  • Focus: if focus was inside the area when it failed, it moves to the "Retry" button; otherwise focus stays where it is.
  • You can still wrap your own boundary around them; the built-in one catches first.

Reporting and customizing

src/app.tsx

<ChatProvider
  host={host}
  onRenderError={(error, { area, conversationId }) => {
    reportError(error, { tags: { chatArea: area, conversationId } });
  }}
  renderErrorFallback={({ area, retry }) =>
    area === "conversation-list" ? <MyListFallback onRetry={retry} /> : null
  }
>
  {children}
</ChatProvider>
ChatProvider prop Type Description
onRenderError (error: unknown, info: { area: ChatRenderErrorArea; conversationId?: string }) => void Called once whenever an area catches an error; use it to report. Do not throw in it
renderErrorFallback (props: { area: ChatRenderErrorArea; error: unknown; retry: () => void }) => ReactNode Replaces the default fallback. Return null to keep the default. The message area has no retry; calling it does nothing

Fallback strings are in the chat namespace: renderError.area ("This part can't be shown right now"), renderError.retry ("Retry"), renderError.message ("This message can't be shown").

Cases that always throw

These are usage errors and throw during render; the boundaries above catch them (the message names what is missing):

  • ConversationList without the conversations capability.
  • CreateGroupModal / ChatInfoPanel without groupManagement.
  • A chat component outside ChatProvider. A boundary cannot catch this one: the boundaries live inside ChatProvider, so it reaches your app.

Fix the cause first; see Capabilities.