Adapter
createOpenMaxAdapter and its options OpenMaxChatConfig, OpenMaxAuth, OpenMaxGetTokenOptions: which endpoints each member calls.
Adapter
Exports of the @openmaxai/chat-openmax root entry point for the adapter itself: the function that builds it and its config. Status, wiring it into a host and an index of every export are on the Overview. The adapter interface itself (the contract of each member) is on @openmaxai/chat-sdk · Adapter.
createOpenMaxAdapter
function createOpenMaxAdapter(config: OpenMaxChatConfig): ChatSdkAdapter;
Builds an adapter for the OpenMax backend (name is "openmax") to pass to createChatHost from @openmaxai/chat-sdk/react. Synchronous: it sends no request and does not call getToken; the token is fetched the first time a request really goes out. An invalid config throws ChatSdkConfigError synchronously (see OpenMaxChatConfig). It reads only the connection fields of config (baseUrl, wsUrl, realtime, auth, workspaceId, orgId) and storage (where the device id is kept); the other fields belong to the host and are used only by createChatHost in @openmaxai/chat-openmax/react.
The connection URLs, the token and the device id are held by the adapter itself: they are not part of the adapter interface and do not appear on the host's inboundDelivery.
| Member | OpenMax's implementation |
|---|---|
identity |
The current user (GET /api/v1/me; returns undefined when the token carries no member identity), conversation members (the members endpoint returns at most 1000 rows and does not page), organization directory search. The member list fetched when opening a conversation by id is handed to the SDK through subscribeMembers, so the same conversation is not fetched twice |
messaging |
Sending, history (latest window, older with before_seq, newer with after_seq, around a message with around_seq), catching up with loadThreadSince, creating conversations (creating a DM shares the one /me with the identity reads), fetching one message by id, reactions, recall, editing and edit history, the change log; see Message endpoints. None of the four methods that hand out messages (loadThread, loadThreadSince, getMessagesByIds, loadMessage) carries the backend's raw agent_run: with agentActivity (read-only progress (experimental · transitional), see the options table below) on the adapter decodes it internally into the neutral run field agent_run_summary (full v3 ⇒ full form, reference ⇒ reference form, unparsable with a valid run id ⇒ a reference form with only the run id, anything else left out); with it off nothing is filled |
conversations |
Conversation list, pin, hide, mute, advancing the read position. Getting one conversation by id fetches the conversation, then the member list, and looks for the current user's row: if present, the user is a member (pinned, muted and read position come from that row, unread count is 0); if absent, an observer (read-only); if loading the current user fails, the load fails (retryable); if the member list comes back full without the current user, membership cannot be decided and it throws ChatMembershipUnknownError |
realtime |
Only with wsUrl. It first trades the token for a one-time ticket (POST /auth/ws-ticket), opens the WebSocket with the ticket and the device id, decodes frames into signals (including typing frames ⇒ typing signals and presence frames ⇒ the SDK's own ChatSdkPresenceSignal; with agentActivity on, agent_activity frames are split off first, their payload taken by proto-JSON decoding or, when that fails, the snake→camel fallback, validated inside the adapter, and valid ones handed over as the SDK's own ChatSdkAgentActivitySignal while invalid frames are dropped without breaking the connection; with it off they are dropped like other unknown frames), reconnects with exponential backoff (a ticket exchange that has not answered within 10 seconds is aborted, and a WebSocket that has not opened within 10 seconds is closed; either counts as a failed attempt, so a hung request or handshake also backs off and reconnects; during a token handover only that handover is dropped and the old connection stays in use), sends connected on the first successful open (reconnected instead when an attempt failed before it) and reconnected after each reconnect; acks sync when the device id is persisted (see storage below); when the ticket exchange fails with unauthorized it stops reconnecting and reports once through sink.error; a ticket exchange failing with forbidden (403) also stops reconnecting and reports once, without renewing; when a path wsUrl has no usable page origin it opens no connection, does not reconnect, and reports once through sink.error a ChatSdkError with code ws_url_unresolved (see Paths below); when the server closes the connection with the credential-revoked close code (4007, credential_revoked) it does not reconnect and reports once through sink.error a ChatSdkError with kind unauthorized and code ws_credentials_invalid; for every close (including the host's dispose() closing an open connection) it hands one ChatSdkRealtimeCloseRecord (layer "sdk") to sink.closed once the outcome is known, and the SDK passes it to the host's onEvent as realtime.closed; this package sends no report requests. When the host already owns a connection, give realtime: "off" and replace this member with openMaxSharedRealtime |
uploads |
Per-conversation uploads (requireConversation is true, at most 5 files, 500 MB each), with resolveUrls for display URLs (preview mode) and resolveDownloadUrl, which resolves a download URL (download mode) when a file's download button is clicked |
cards |
One submit endpoint for yes/no cards, business-card buttons and form cards (POST /api/v1/messages/{id}/card-interactions with Idempotency-Key); no complete response within 30 seconds (headers not arrived, or the body not fully read) counts as a timeout. On success it includes the settled record when the response is complete enough to build it (for yes/no and business cards the answerer is the current member, sharing the one /me with the identity reads; for form cards the answerer and the answers come from the response). Form-card answers become the request body through formAnswersBody. A 401 after the refresh-and-resend, no response, 408 and 5xx are rejected unchanged; any other 4xx becomes a verdict per Card verdicts. The same for all three kinds |
directMessages |
Find or create a direct conversation: POST /api/v1/conversations/dm (body only { peer_member_id }; it returns the existing one or creates one, without asking /me first). The conversation in the response is mapped to the package's shape as a member (the response carries no per-user state: unread, pinned and muted count as 0 / no). Failures throw ChatSdkRequestError per the status-to-kind table (for example 404 ⇒ not_found, 403 ⇒ forbidden), with the error envelope's code carried over |
subConversations |
Find or create a context sub-conversation: POST /api/v1/conversations/{parent}/subconversations with { context_key, title? }, or POST /api/v1/conversations/dm/subconversations with { peer_member_id, context_key, title? } when the parent is the direct conversation with a member (the backend finds or creates that direct conversation; the response carries the sub-conversation only). The sub-conversation in the response is mapped like the direct conversation above. The backend takes the owner from the credential: the deprecated owner is sent only with a parent id (the other request has no such field). Failures throw ChatSdkRequestError per the status-to-kind table with the sentence for the backend code, for example 409 COMM_SUBCONVERSATION_LIMIT_REACHED (the parent has reached its limit of open sub-conversations), 403 SUBCONVERSATION_NOT_ENABLED (not enabled for the organization), 400 COMM_INVALID_CONTEXT_KEY. The conversation list also carries each row's has_unread_subconversations |
mentions |
The "@me" jump: list unread @mentions (GET /api/v1/conversations/{id}/unread-mentions; is_mention_all true becomes "all", counts come from total_me / total_all and are not cut by paging), mark some read (POST …/{id}/mention-read, the body has only message_ids), mark all read (POST …/{id}/mention-read-all, no body, the backend decides the scope). Non-2xx throws ChatSdkRequestError |
profiles |
Profile card data: the card from GET /api/v1/members/{id} (the organization role name as subtitle, omitted when there is none; owner, identity, agentOrigin (agent_origin) and memberStatus (status) only on Agents, the last two used only by the SDK's conversation header and not passed to the card; 404 returns undefined), the owned Agents from GET /api/v1/members/{id}/owned-agents (the model name as subtitle). Raw values only; the SDK fills the "Member" and "Unnamed" defaults. For profile cards you also pass profileCardActions to createChatHost |
workItems |
# work-item candidates (GET /api/v1/work-references): query is the query trimmed, left out when empty; project_id only when projectId is given; limit is always 50; no cursor. An issue's label is "project name / title" (title only when there is no project name), in the order returned. Non-2xx throws ChatSdkRequestError |
agentConfig |
Agent model configuration: loadModelState reads GET /api/v1/agents/{id}/model-config (snake_case to camelCase, an unknown apply_state becomes ready; rethrows only expired credentials, otherwise returns undefined), setModel sends PATCH …/model-config (body only { model }), setModelVisibility sends PATCH …/model-visibility (body only { visible }); non-2xx writes throw ChatSdkRequestError. No extra timeout |
capabilityTags |
Agents' capability tags: GET /api/v1/agent-profiles with member_id repeated (one request per call; the adapter declares maxBatchSize: 50, so the SDK passes at most 50) and include=capabilities, the read the Agent directory uses; matched by member_id, not by position. An Agent missing from the reply is left out (no tags); tags of an unknown kind or without text are dropped |
groupManagement |
All six group-management methods: create POST /api/v1/conversations/groups (body { name, member_ids, description? }, no description when it is an empty string; returns data.id); update profile PATCH /api/v1/conversations/{id} (only the name / description given); add POST …/{id}/members:batch-add (role is MEMBER), remove POST …/{id}/members:batch-remove, the bulk endpoints even for one person, ids deduplicated by their trimmed value, and no request for an empty list; leave POST …/{id}/leave (new_owner_id when a successor is given), conversation_deleted ⇒ dissolved, new_owner_id ⇒ newOwnerId; dissolve DELETE /api/v1/conversations/{id}. The bulk endpoints answer 200 for the whole call with a result per person: each person who failed gets a kind from that row's status (status to kind) and a message from that row's code (none when the code is unknown; AUTH_ORG_MEMBERSHIP_REQUIRED says "This member is not in the current organization."); the backend's text for that row never goes into message. The backend also writes no permission and no such group into every row (403 / 404, code COMM_ERROR): when every row fails with the same such reason the call is rejected as a whole with ChatSdkRequestError; removing a single person who is not in the group or whose role is not lower than yours is reported the same way (same status and code, indistinguishable). A failed call throws ChatSdkRequestError (creating a group that gets 403 AUTH_ORG_MEMBERSHIP_REQUIRED says the neutral sentence, see errors). Leaving is idempotent on the backend: leaving a group you are no longer in, or one that does not exist, succeeds. Writes are not retried; refreshing after a write and the "no longer in this conversation" handling are done by createChatHost |
conversationResources |
A conversation's images, files and links: GET /api/v1/conversations/{id}/resources, with kind (the kinds joined by commas), sender_id, since, until, query (trimmed) and cursor sent only when given and not empty; limit sent only when it is a positive integer, lowered to 100 when larger (the backend rejects a limit above 100; like the in-memory adapter, this one reads it as 100 instead of failing). since / until are sent as given: one that is not an RFC 3339 timestamp with a time zone (date-only, zone-less) gets 422 from the backend and throws ChatSdkRequestError of kind validation. Rows of the cursor-list envelope are mapped to ChatConversationResource (message_at ⇒ messageAt, url_host ⇒ host, link_text ⇒ title); an image or file row without artifact_id, a link row without url or a row of an unknown kind is dropped. A pagination.next_cursor that is empty, null or absent (or no pagination at all) means no nextCursor. Visibility and permissions are the server's. Non-2xx throws ChatSdkRequestError; signal is passed to the request |
messageSearch |
Message search in one conversation: POST /api/v1/conversations/{id}/messages/search with { query, limit?, cursor? } (the query trimmed; a blank query resolves an empty page without a request; limit as above, sent only when a positive integer and lowered to 100). The snippet comes from the first non-empty highlight, its <em> marks turned into match: true parts and everything else kept as plain text; a hit without highlights gets the message's current text unhighlighted. Hits whose message comes back recalled or deleted are dropped as well; that every hit is still visible, and that hits and snippets are based on the current text of edited messages (a hit that only matches pre-edit text is not returned), is the server's guarantee (it checks hits against the messages); the adapter does not re-check snippets against the text itself. Non-2xx throws ChatSdkRequestError; signal is passed to the request |
session |
Not provided: the end of the organization scope is told to the SDK by the host application (for example by adding session on its own adapter) |
OpenMaxChatConfig
interface OpenMaxChatConfig {
baseUrl: string;
wsUrl?: string;
realtime?: "off";
auth: OpenMaxAuth;
agentActivity?: boolean;
storage?: ChatSdkStorage;
currentUser?: () => ChatSdkAdapterCurrentUser | undefined;
workspaceId?: string;
orgId?: string;
instanceKey?: string;
locale?: string | (() => string);
ports?: ChatSdkPortOverrides;
markdown?: ChatSdkMarkdownOptions | false;
}
The config shared by createOpenMaxAdapter and the one-line createChatHost. There is no built-in backend: baseUrl is required, the package contains no environment's URL, and it reads no environment variables.
| Field | Default | Description |
|---|---|---|
baseUrl |
Required | REST base URL, without /api/v1; for OpenMax, https://openmax.com. An absolute http(s):// URL, or a path starting with / (such as /openmax-api); see Paths below |
wsUrl |
Realtime URL; for OpenMax, wss://openmax.com/ws. An absolute ws(s):// URL, or a path starting with / (such as /ws). Not derived from baseUrl |
|
realtime |
Its only value is "off": no WebSocket, and messages from others do not appear on their own. Exactly one of wsUrl and realtime: "off" must be given |
|
auth |
Required | Where credentials come from, see OpenMaxAuth. Only token is accepted |
agentActivity |
true |
Agent runs, read-only progress (experimental · transitional). Replaced when the planned Agent runs capability lands. true: the realtime channel recognizes agent_activity frames and messaging decodes agent_run; false: neither happens (not even decoding), so the SDK receives nothing about runs. Also true by default with realtime: "off": no frames arrive, but the summary bar on replies still shows. It is a factory option, not an adapter member; this package reads no environment variables, the caller passes the switch |
storage |
"memory" |
Where the device id, the host's drafts and instanceScope.storage are kept. With "memory" every page load is a new device (the server's sync cursor starts over); with "localStorage" the device id is kept under the key cws:chat-sdk:device_id, never reading or writing cws:web:device_id, and falls back to memory when storage is unavailable or does not read back what was written. When the device id is persisted (an existing one was read, or the new one reads back), the realtime connection acks each sync frame (POST /api/v1/sync/ack), paging first through POST /api/v1/sync (at most 5 pages) when it has has_more; when it is not persisted there is no ack and no paging, and every connect replays the oldest 100 events of the inbox. Pass "localStorage" if you want the ack; ack and paging need the messages:read_state:write and messages:sync:read scopes, see item 1 of Known gaps With realtime: "off" there is no realtime connection, and no device id is computed or written |
currentUser |
The current user the host already holds, so the adapter does not request GET /api/v1/me a second time. Read when the adapter first needs the current user (the SDK's identity.me(), or creating a direct message); a user with a memberId is used as is and kept for the adapter's lifetime, like a fetched one. Returning undefined (or a user without memberId) ⇒ the adapter requests GET /api/v1/me itself, once, shared by everything that needs "me". The adapter does not check the user's organization: return only a user of the organization in orgId |
|
workspaceId |
Sent as X-Workspace-ID on REST requests that share the page's origin; not sent cross-origin, or when there is no page origin (outside a browser). The backend does not read this header; the organization comes from orgId. May be renamed or removed |
|
orgId |
Sent as X-Org-ID on every REST request; the backend uses it to pick the organization, so it is required with a personal API Key (the Key carries no organization; without it the conversation list returns 401); a session token that already carries an organization can omit it. May be renamed or removed |
|
locale |
"zh-CN" |
The UI language (primary subtag en ⇒ English, anything else Chinese). The adapter uses it to pick the language of message when a request fails (see Errors); given a function, it is read on every failure, so the host need not rebuild the adapter when the UI language changes. The one-line entry point also passes it to the SDK's default i18n, same as the field of the same name in ChatSdkAdapterHostConfig; given a function, it takes the value at the moment the host is built and the default i18n does not follow later changes; pass ports.i18n for that |
instanceKey, ports, markdown |
Host settings, used only by the one-line entry point; same as the fields of the same name in ChatSdkAdapterHostConfig |
At construction the config is checked in this order, and when several are wrong the first is reported; each throws ChatSdkConfigError synchronously: auth.mode is not token (logto and cookie do not silently fall back); getToken is not a function; baseUrl is missing, or neither http(s) nor a path starting with /; wsUrl is given but neither ws(s) nor such a path; neither wsUrl nor realtime: "off" is given; both are given. Construction only looks at the shape: it resolves nothing and does not touch window.
Paths
baseUrl and wsUrl can be paths starting with /, for deployments where the page and the backend sit on one origin behind a same-origin reverse proxy, for example baseUrl: "/openmax-api" and wsUrl: "/openmax-ws".
- When they are resolved: not at construction but on first use:
baseUrlon the first REST request,wsUrlwhen the first realtime connection starts. They are always resolved asnew URL(path, location.origin), ignoring<base href>and the current page path; a successful result is kept and not computed again. The scheme ofwsUrlfollows the page:https:pages getwss:,http:pages getws:, and the query string is kept. The ticket exchange (POST /auth/ws-ticket) is a REST request and followsbaseUrl. - When there is no usable origin: only
location.originitself counts. On the server (nowindow), whenlocation.originis"null"(about:blank,data:), or when the page is not served over http(s) (file:,chrome-extension:,capacitor:), the first request rejects with aChatSdkConfigErrornamingbaseUrl; a pathwsUrlopens no connection, requests no ticket and does not reconnect, and reports once throughsink.erroraChatSdkErrorwithkindunknownandcodews_url_unresolved, whosecauseis theChatSdkConfigErrornamingwsUrl(with an absolutebaseUrl, REST keeps working). In development builds it also logs oneconsole.error(once per host) namingwsUrlwith the reason and the fix; production builds print nothing. The address is resolved before a token is requested, sogetTokenis not called in this case. A REST failure is not kept: used later in a browser, the address resolves as usual; giving up on realtime is final for that host. - Sandboxed iframes: resolved against the document address. In a sandboxed frame without
allow-same-originthe document origin (window.origin) is"null", butlocation.originis still the http(s) origin of its address, so paths resolve, a token is requested and requests are sent as usual; whether they succeed (cross-origin requests withOrigin: null) is up to the server's CORS. - Protocol-relative forms are not special-cased:
//host/apifollows the URL standard and becomes an absolute URL on that host with the page scheme (https://host/apion anhttps:page, thenwss:forwsUrl). That is another origin, so the cross-origin requirements (CORS, registering the page origin) apply andX-Workspace-IDis not sent. The standard reads/\host/apithe same way. - Not accepted: relative forms that do not start with
/(api,./api) throw at construction. - What the proxy has to forward: a path such as
/openmax-apiis same-origin with the page, soX-Workspace-ID(fromworkspaceId) is sent as usual; the proxy forwards it to the backend together withAuthorizationandX-Org-ID. The proxy in front ofwsUrlhas to forward WebSocket upgrades; if it cannot, givewsUrlas an absolute URL.
The device id (see storage in the table above) is also read when the first connection starts, and is fixed for the host after that; the storage key is unchanged, so a value stored before an upgrade is still used. A host created at module top level therefore does not touch window during server-side rendering.
OpenMaxAuth
type OpenMaxAuth =
| {
mode: "logto";
}
| {
mode: "cookie";
}
| {
mode: "token";
getToken: (options?: OpenMaxGetTokenOptions) => Promise<string | OpenMaxToken>;
};
Where credentials come from. The package does not issue credentials, it only uses them: renewing them is up to you. Only token is implemented: logto and cookie stay in the type and throw at construction.
In token mode, getToken() is called once the first time a request goes out and the result is cached; on a 401 it is asked again with { refresh: true } and the request is re-sent once with the new token; see OpenMaxGetTokenOptions and Errors · Renewal. Return an OpenMaxToken ({ token, expiresAt }) instead, and the token is renewed before it expires and only an expired-token 401 renews. A getToken call that has not settled within 30 seconds counts as failed with kind timeout (not expired credentials), and the next request or reconnect calls it again; what the timed-out call returns later is ignored. Keep long-lived credentials (secrets, private app keys) out of the browser.
OpenMaxGetTokenOptions
interface OpenMaxGetTokenOptions {
refresh?: boolean;
}
The hint passed when the package asks getToken:
- No argument: give me a token (the first time, or again after a failed renewal). Return the one you have if it still works.
{ refresh: true }: the token you gave was just refused by the backend with401; really renew it now (for example with a refresh token) and return a new one. If you return the refused one, the package still re-sends once, most likely gets401again and fails withunauthorized. Several requests refused at the same time (or one after another) ask only once; one request asks at most once, with no loop.
When no token can be had, what you throw says why (the same for both forms):
- The credentials are gone and the user must sign in again: throw a plain
Error, or return an empty string. That call fails withunauthorized, the host callsonUnauthorizedonce (or shows "session expired" once when it is not given), and realtime stops reconnecting. - The renewal did not go through, but the credentials may still be fine (the renewal endpoint is offline, timed out,
5xx): throw aChatSdkErrorwithkindnetwork(ortimeout,unavailableand so on). That call fails with that kind,onUnauthorizedis not called, realtime backs off and reconnects as usual, and the next401renews again. A bareTypeError,TimeoutErrororAbortErrorcounts asnetwork,timeoutandcancelled. Do not report network failures as expired credentials: if the callback ignores them, that one call per episode is used up, and a real credential failure later does not call it again.
An old getToken that ignores the argument (async () => token) still works; it just most likely returns the same token after a 401.
OpenMaxToken
interface OpenMaxToken {
token: string;
expiresAt: number | string;
}
What getToken may return instead of a plain string: the token with its expiry (expiresAt, epoch milliseconds or an ISO 8601 string). Meant for short-lived tokens your server exchanges for the user.
- Renewed before it expires. When a request goes out with less than 60 seconds left (or less than half the token's lifetime when it arrived, for tokens shorter than two minutes),
getToken({ refresh: true })is asked first, so the request does not fail with401and retry. Requests that notice it together share one call. The check happens when a request goes out, so a page that comes back after a long time in the background renews before its first request. If that call fails while the old token has not expired, the old one is used and the next request tries again. - Realtime is handed over, not dropped. At the same moment a second connection is opened with a new ticket; once it is open, the old one is closed two seconds later. A push that arrives on both is delivered once, and the open conversations catch up once afterwards. If the handover cannot finish in time (timers held back in a background tab, for example), the server closes the old connection at expiry and the adapter reconnects with a new token, as without an expiry.
401is told apart.AUTH_TOKEN_EXPIRED⇒ askgetToken({ refresh: true })once and re-send once. Any other401(the token or its key was revoked) ⇒ no renewal and no re-send: the call fails withunauthorized,onUnauthorizedis called, and realtime stops reconnecting.
A token that has already expired by the page's clock when it arrives (the page's clock is ahead), and a renewal that returns the same token or one that expires no later, are not renewed ahead of time: they are used until the backend answers AUTH_TOKEN_EXPIRED, so renewing cannot loop. An expiresAt that cannot be read is ignored. A plain string behaves as before: no renewal ahead of time, and every 401 renews once.
openMaxSharedRealtime
function openMaxSharedRealtime(source: OpenMaxFrameSource, options?: OpenMaxSharedRealtimeOptions): ChatSdkRealtime;
Feeds the SDK with the frames from an OpenMax realtime connection the host already owns. Use it to replace realtime on what createOpenMaxAdapter returns. Decoding and translating frames is the same code as on the wsUrl path, so the same frame gives the same signals.
When to use it: the page already has its own /ws connection (it exchanges the ticket, sends the device id, reconnects and acknowledges sync), and you mount the SDK on it too. If the adapter also connects by itself through wsUrl, the page opens two connections: two tickets, two device ids, every push sent twice by the server, and two backoffs reconnecting independently. If you have no connection of your own, give wsUrl as usual and do not use this.
import { createOpenMaxAdapter, openMaxSharedRealtime } from "@openmaxai/chat-openmax";
const base = createOpenMaxAdapter({ baseUrl, auth, realtime: "off" });
const adapter = { ...base, realtime: openMaxSharedRealtime(source) };
- It opens no WebSocket, exchanges no ticket, sends no device id, never acknowledges
syncand never callssink.errororsink.closed. Expired credentials are handled by the host's connection and its own exit, and close records are kept by that connection too. A browser must have only one path acknowledgingsync, so this one never does. - It calls
subscribeinrealtime.connect()and unsubscribes inclose(). When the same adapter is handed to several hosts one after another, eachconnectis its own subscription, and after the host'sdispose()the listener count is back where it was. connect()subscribes first, then asksisOpen(). If the connection is already open, nothing is sent: every frame from the subscription on arrives, so there is nothing to catch up. If it is not open yet, its firstopen()gives oneconnected. Eachopen()after the first one thisconnect()has seen gives exactly onereconnected("was disconnected and is connected again", as the adapter contract says). Failed attempts of the host's connection are not visible here, so a firstopen()after them still givesconnected.- Frames never give
reconnected.syncevents the host fetched by paging go toframe()in the shape of asyncframe (the JSON text of{ type: "sync", payload: { events } }) and give onemessagesper conversation, like a pushedsync. - Text that is not JSON, or a frame that cannot be decoded, is dropped whole; nothing is thrown.
connect()returns synchronously and never throws: ifsource.subscribethrows, the subscription counts as not made; ifsource.isOpenthrows, the connection counts as not open.close()unsubscribes once however many times it is called.- It does not filter by organization: passing in only the current organization's frames is up to
source.
OpenMaxFrameSource
interface OpenMaxFrameSource {
subscribe(listener: OpenMaxFrameListener): () => void;
isOpen(): boolean;
}
The connection the host owns. subscribe registers a listener and returns the unsubscribe function: it removes that listener by reference, and calling it twice is fine. Frames that arrived before registering are not replayed, and subscribe must not call the listener synchronously (when the connection is already open, isOpen says so and the SDK sends that one reconnected itself; if open() is called synchronously anyway, it still counts as the only one). isOpen tells whether the connection is open right now; ask the connection itself (for example readyState === OPEN) instead of keeping a boolean in the close callback, since the close callback may not fire when you disconnect on purpose.
OpenMaxFrameListener
interface OpenMaxFrameListener {
frame(raw: string): void;
open(): void;
catchUp?(onError?: (error: unknown) => void): void;
}
A listener of OpenMaxFrameSource. frame(raw) is called once per frame; raw is the text of the WebSocket MessageEvent.data, undecoded and unchanged; open() is called each time the connection really opens. catchUp() (optional, experimental; call it as listener.catchUp?.()) asks the SDK to catch up the open conversations once although nothing in particular happened, for example on a timer while the connection looks open or when the browser comes back online. It gives { kind: "catchUp" }, which claims no new messages: tabs do not move, nothing counts as new, and the conversation list is not refetched; each mounted thread fetches forward from its watermark once, and one already catching up is skipped. There is no need to call it when the page returns to the foreground: the threads catch up by themselves then. Pass onError to hear when the catch-up fails in a mounted thread (a request rejected); it is called once for each failure, with its reason. A host calling catchUp on a timer uses it to back off, and should count only the reasons worth backing off for (network error, timeout, 429, 5xx): a 403 or 404 of one conversation, such as one the user was removed from, says nothing about the server, and backing off for it would slow the catch-up of every other conversation.
OpenMaxSharedRealtimeOptions
interface OpenMaxSharedRealtimeOptions {
agentActivity?: boolean;
}
| Field | Default | Description |
|---|---|---|
agentActivity |
true |
Whether agent_activity frames are handled; same as agentActivity on OpenMaxChatConfig. Usually give both the same value |
