OpenMax
Free Trial

Store

createChatStore, ChatStore, the conversation snapshot ChatConversationSnapshot and the request result cache createChatRequestCache.

Store

Exports of the @openmaxai/chat-store root entry point for the store itself. Status, wiring it into a host and an index of every export are on the Overview.

createChatStore

function createChatStore(options: ChatStoreOptions = {}): ChatStore;

Creates a message store. Each call returns an independent store; stores share no data. Data comes in only through dispatch. Each conversation keeps at most 500 loaded messages (not configurable); beyond that, the end farthest from the view is unloaded. Where local data lives and whether it is encrypted is set by options.localData, see ChatStoreOptions.

ChatStore

interface ChatStore {
  dispatch(event: ChatStoreEvent): void;
  subscribe(conversationId: string, listener: ChatStoreListener): () => void;
  getSnapshot(conversationId: string): ChatConversationSnapshot;
  openLocalData(userId: string, options?: ChatStorageOpenOptions): Promise<void>;
  closeLocalData?(): Promise<void>;
  clearLocalData(): Promise<void>;
  clearConversation(conversationId: string): Promise<void>;
}
Method Description
dispatch(event) The single write entry point. Takes effect synchronously; when it changed data, the conversation's subscribers are notified once, and when it changed nothing, nobody is notified. An unknown event type (as well as a sendStarted without client_msg_id, or an unknown outcome) throws TypeError and changes nothing.
subscribe(conversationId, listener) Subscribe to one conversation's changes. Returns an unsubscribe function; calling it twice is harmless. Subscribing or unsubscribing inside a callback does not change who this notification goes to.
getSnapshot(conversationId) A conversation's data right now. For a conversation the store does not have, returns a shared empty snapshot. Snapshots and the messages in them (with their arrays and objects) are frozen: a message object written into the store gets frozen, so do not change it after handing it over.
openLocalData(userId) Open the local data of userId. When the user who last opened local data on this device was someone else, that user's local data (messages, watermarks, request results) is deleted first, then the current user's is opened. With createIndexedDbStorage() the "last user" is remembered across page reloads; with other storage only the user last opened in this page is remembered. Once open, server messages and watermarks written through dispatch are also written to the device; see Writing to the device below.
openLocalData(userId, { readOnly: true }) Open read-only, for showing only what is already on the device while offline: the previous user's data is not deleted; when the data cannot be used it rejects with LocalDataUnavailable (reasons there) and leaves the databases as they are; once open, nothing is written to the device (messages, watermarks, local segment records), and swapped-in ranges are not recorded as written (a later writable open rewrites the whole stretch). With createIndexedDbStorage() opening writes nothing either; see "Read-only open" there.
closeLocalData() Close local data: closes the storage connection, releases the single-tab lock, closes the cross-tab channel and stops hearing about conversations cleared elsewhere; deletes nothing, can be awaited and called again. Local reads and writes queued before it still run, those queued after do not; afterwards it is as if never opened (nothing is read from or written to the device), opening the same user again finds the data still there, and the next catch-up to the latest rewrites the whole stretch. The device's "last user" is unchanged, so a later clearLocalData() still deletes that user's data. Every store from createChatStore has it; it is optional on the interface, so your own ChatStore may omit it and callers check that it exists.
clearLocalData() Delete the current user's local messages, watermarks and request results, then close local data; awaitable. Call it on sign-out and on an unrecoverable 401. The device id and drafts are not in the store, and clearLocalData() does not touch them: the host deletes drafts itself, and the device id is kept. When nothing was opened yet, it deletes the data of the user who last opened local data on this device.
clearConversation(conversationId) Clear one conversation's messages on this device; call it after leaving a group, the group being dissolved, or being removed. Awaitable. In memory, the conversation's range, watermark, local messages and in-flight patches are dropped and the snapshot goes back to never loaded (subscribers get one window if there was data); when local data is open (or opening), the conversation's local messages, watermark and local segment record are deleted, queued after the local writes already queued. Other conversations are not touched. Fetches started before the clear that settle after it are not written: a window read from the device or fetched to swap in by the thread loader or the gap-fill scheduler is dropped; pushes and changes arriving after the clear are treated as for a conversation never loaded (no range, nothing written to the device). With createIndexedDbStorage in a tab that did not get the single-tab lock (its storage fell back to memory), the local copy lives in the tab holding the lock: the clear is forwarded over the cross-tab channel and that tab deletes its local copy and drops its copy in memory (see "Conversations cleared in another tab" there); the returned promise then settles once the clear is recorded in the device database, without waiting for that tab. Opening it again later fetches and writes to the device as usual. Rejects with the storage's error when deleting the local copy fails (memory is already cleared). Single messages fetched by id live in the request cache, not in the store; delete them with the cache's remove.

Calls to openLocalData, closeLocalData and clearLocalData made without awaiting take effect in call order; a failed call does not block the next one.

Writing to the device

While local data is open, the store queues the server messages and watermarks written into it for ChatStorage; a failed write does not affect the data in memory. After a write fails, the writes already queued at that point are dropped and the next write rewrites the whole range:

  • Each conversation stores one contiguous stretch of messages. When the range reaches the latest (or is halfway through catching up) the whole range is written, and later changes to the range (attached before or after, replaced in place) are written one at a time; a jump to a window that does not reach the latest is not written until it reaches the latest again. A stretch that touches the one already on the device is merged with it; one that does not (away too long, gap fill swapped in the latest window) replaces it.
  • Only the server's version is written. Local messages (sending, failed, blocked) are not written; a message with optimistic changes in flight is written as the server gave it. messageDeleted deletes the copy on the device.
  • A stale copy on the device is dropped. When a reaction or an edit of an existing message changes a message that is not in memory (the conversation is closed, or the message is in an unloaded end), or the range is not being written to the device, the stretch on the device is dropped: from then on opening and reading back fetch from the backend. An edit only counts when the message falls inside the stretch; a push newer than the watermark is a new message and does not count.
  • Written only to the device data of the user the range was swapped in for. After switching to another user (clearLocalData then openLocalData with another user, or openLocalData with another user directly), ranges swapped into memory before are not written to the device until a window is swapped in again; the same goes for ranges swapped in before local data was opened. A window that the thread loader or the gap-fill scheduler requested before the user switched is not written either; a windowLoaded you dispatch yourself is not covered by this, so drop responses to requests sent before a user switch yourself.
  • The stretch's range is kept in one request result whose key starts with @openmaxai/chat-store/segment/; do not use that prefix for your own request results. When the device has no watermark for the conversation (it was evicted for quota) the record is ignored. The stretch's change watermark is kept in the same record and written together with the range: when the stretch is dropped, replaced by a new one or evicted, the change watermark goes or is replaced with it; when it is merged with a stretch already on the device, the lower of the two is kept.
  • Changes made while closed or offline are caught up by the gap-fill scheduler. Edits, recalls, deletes, reactions and settled cards that others made to existing messages while the page was closed or offline are not among the new messages gap-fill fetches. When the read methods have a change log, reopening a conversation first draws the stretch on the device (still the old copy at that point); after fetching new messages, the gap-fill scheduler fetches the change log forward from the change watermark recorded with that stretch, fetches the changed messages by id, writes them to memory and to the device, and only then moves the change watermark; see Gap fill · Catching up on changes. After too long away, when the change log has been purged, the stretch is dropped and the latest window swapped in. A stretch stored before the change log existed, with no change watermark, is not used; the latest window is fetched instead. While a conversation is open these changes arrive by realtime push.
  • Reading back. The thread loader draws the newest page of the stretch first when a conversation opens, then fills the gap from its end; an unloaded end without a cursor is read back from the stretch first. When the stretch is dropped (see above), a message is deleted, or the user switches while reading, what was read is not used and the backend is asked instead.

ChatStoreOptions

interface ChatStoreOptions {
  localData?: ChatLocalDataOptions;
}

Options of createChatStore; all optional.

Field Description
localData Where local data lives and whether it is encrypted, see ChatLocalDataOptions. Leave it out for in-memory storage without encryption.

ChatConversationSnapshot

interface ChatConversationSnapshot {
  readonly messages: readonly ChatMessage[];
  readonly hasOlder: boolean;
  readonly olderCursor: string | undefined;
  readonly hasNewer: boolean;
  readonly newerCursor: string | undefined;
  readonly watermark: number | undefined;
  readonly newerPending: boolean;
}

While nothing changed, getSnapshot returns the same object; an unchanged message is the same object in messages too.

Field Description
messages The loaded range, ascending by seq, by id when seq is equal; at most 500. Local messages (not counted in the 500) are here too: failed and blocked ones sit at their position, sending ones and confirmed ones not matched yet come last (not shown while the range does not reach the latest, hasNewer being true: after the newest message is outside this window); see ChatStoreSendSettledEvent.
hasOlder There are older messages before the range.
olderCursor Cursor for paging older; gone after the older end was unloaded, which can then only be fetched by seq.
hasNewer The range does not reach the latest: a window fetched around a message, the newer end was unloaded, the latest window ends below the watermark (it arrived late, or the message at the watermark was deleted), or a gap-fill from the watermark is part-way (the batch just attached says there is more; the range then ends at the watermark and gap-fill continues from there).
newerCursor Cursor for paging newer; gone after the newer end was unloaded, which is then fetched by seq forward from the newest message in the range.
watermark The watermark: the highest seq received without gaps; gap-fill fetches forward from here. Absent until the range has reached the latest once. Unloading messages does not affect it.
newerPending The store knows of newer messages that are not in the range: it saw a push newer than the watermark that could not be attached (gap-fill from the watermark), or the range was told it reached the latest but ends below the watermark (then hasNewer is true as well; fetch by seq forward from the end of the range).

createChatRequestCache

function createChatRequestCache(): ChatRequestCache;

Create a request result cache (results of requests other than messages: member profiles, directory search, the conversation list and so on), one per host (per signed-in user). It keeps each request's result by key and sends only one request while the same key is in flight. It sends no requests itself (the caller passes the loader), reads no clock, and does not refetch on its own after invalidation: the caller calls invalidate when a related event arrives, and subscribers call load again when notified. Failures are cached like successes: after a failed fetch the key is not stale, and load rejects again with the same reason, so calling load on the failure notification does not turn into a retry loop; to retry (the user clicks retry, or try again later), the caller calls invalidate and then load, and decides any backoff.

ChatRequestCache

interface ChatRequestCache {
  get<T>(key: ChatRequestKey): ChatRequestEntry<T>;
  load<T>(key: ChatRequestKey, loader: () => Promise<T>): Promise<T>;
  set<T>(key: ChatRequestKey, value: T): void;
  invalidate(prefix: ChatRequestKey): void;
  subscribe(key: ChatRequestKey, listener: ChatRequestListener): () => void;
  remove(prefix: ChatRequestKey): void;
  clear(): void;
}
Method Meaning
get(key) A key's result right now. Returns a shared idle result for a key never loaded, and the same object while nothing changed.
load(key, loader) With a value that is not stale, returns the cached value without calling loader; while the key is being fetched, waits for that fetch without calling loader again; otherwise calls loader once. Rejects on failure (also when loader throws synchronously) and records error (keeping the previous value); while not invalidated afterwards, load rejects again with the same reason without calling loader. A request sent before an invalidation that returns after it: its value is recorded but still counts as stale; when a request sent after the invalidation exists, its result is not written.
set(key, value) Write a key's value directly (for example when a write's response already carries the new value); it counts as not stale. The result of a request in flight is no longer written.
invalidate(prefix) Mark the keys starting with prefix (including itself) stale; an empty array means all of them. A request in flight counts as stale when it returns. Does not refetch.
subscribe(key, listener) Subscribe to a key's result changes. Returns an unsubscribe function; calling it twice is harmless. Subscribing or unsubscribing inside a callback does not change who this notification goes to.
remove(prefix) Drop the results of the keys starting with prefix (including itself), for example the single messages fetched by id for a conversation you left (keys starting with ["@openmaxai/chat-store", "message", conversationId]). Results of requests in flight are no longer written; subscriptions stay, and the subscribers of each key that had a result are notified once.
clear() Drop every result (on sign-out). Results of requests in flight are no longer written; subscriptions stay, and the subscribers of each key that had a result are notified once.

ChatRequestEntry

interface ChatRequestEntry<T = unknown> {
  readonly status: "idle" | "loading" | "success" | "error";
  readonly value: T | undefined;
  readonly error: unknown;
  readonly stale: boolean;
  readonly fetching: boolean;
}
Field Meaning
status idle: never loaded; loading: first load, no value yet; success: has a value; error: the last load failed.
value The last value loaded; kept after a failed load.
error Why the last load failed; gone after a later load succeeds.
stale Invalidated; the next load fetches again. The old value is still given until the new one arrives. After a failed fetch the key is not stale (failures are cached too).
fetching A load is in flight (the first one, or a refetch after invalidation).

ChatRequestKey

type ChatRequestKey = readonly (string | number | boolean | null)[];

The key of a request, compared element by element ("1" and 1 differ, NaN and null differ, -0 and 0 are the same). Keys with the same prefix can be invalidated together: ["members", orgId] is a prefix of ["members", orgId, memberId].

ChatRequestListener

type ChatRequestListener = () => void;

Called when a key's result changes; see subscribe. Read the new result with get.

createChatMemberStore

function createChatMemberStore(): ChatMemberStore;

Creates a member store, one per host (per signed-in user): a participant table (one entry per id across conversations), each conversation's memberships (conversation role and join time), and the current user with their org role. Like the request result cache it is memory-only: it holds no local storage and touches no browser storage; fetch the member list once each time a conversation opens and hand it over. Members have no change log, so role changes made while offline cannot be caught up, and keeping them on the device would show stale roles.

It sends no requests and does not read the clock; data comes in only through dispatch. Each @openmaxai/chat-sdk host creates one: the host's synchronous identity.getMember and listMembers read from it, member lists fetched by the adapter (with conversation roles and join times) are written through membersLoaded, and the current user is passed in through currentUserLoaded once fetched (with the org role from the adapter's me()); useChatSdkPermissions reads the current user's roles from it. The @openmaxai/chat components do not read it yet.

member-store-wiring.ts

import { createChatMemberStore } from "@openmaxai/chat-store";

const members = createChatMemberStore();
members.dispatch({ type: "currentUserLoaded", userId: me.memberId, orgRole: me.roleSlug });

const rows = await host.fetchMembers(conversationId);
members.dispatch({
  type: "membersLoaded",
  conversationId,
  members: rows.map((r) => ({
    participant: { id: r.member_id, displayName: r.display_name, avatarUrl: r.avatar_url ?? undefined, kind: r.kind ?? "human" },
    role: r.role,
    joinedAt: r.joined_at,
  })),
});

members.getMyRoles(conversationId); // { conversationRole: "OWNER", orgRole: "org-admin" }

ChatMemberStore

interface ChatMemberStore {
  dispatch(event: ChatMemberStoreEvent): void;
  getMembers(conversationId: string): readonly ChatMembership[] | undefined;
  getParticipant(id: string): ChatStoreParticipant | undefined;
  getMyRoles(conversationId: string): ChatMyRoles;
  subscribe(conversationId: string, listener: ChatMemberStoreListener): () => void;
  clear(): void;
}
Method Description
dispatch(event) The single write entry point; takes a ChatMemberStoreEvent. Takes effect synchronously; when it changed data, the subscribers of each affected conversation are notified once, and when it changed nothing, nobody is notified. An unknown event type (as well as a duplicate id, an unknown kind, or a participant.id that differs from memberId) throws TypeError and changes nothing.
getMembers(conversationId) A conversation's memberships, in membersLoaded order, with later arrivals appended. undefined when the member list was never loaded; an empty array when it was loaded and has nobody. The array and each row are frozen; with no change it returns the same object, and unchanged rows are the same objects too.
getParticipant(id) A participant, looked up by id across conversations (a sender of past messages who is not in any current member list can still be found); undefined when unknown. Frozen; the same object while unchanged.
getMyRoles(conversationId) The current user's conversation role and org role in this conversation, see ChatMyRoles. Frozen; the same object while unchanged.
subscribe(conversationId, listener) Subscribe to one conversation: notified when its getMembers, its getMyRoles, or getParticipant for one of its members changes, at most once per dispatch. Returns an unsubscribe function; calling it twice is harmless. Subscribing or unsubscribing inside a callback does not change who this notification goes to.
clear() Clear everything (on sign-out or org switch). Subscriptions stay; each subscribed conversation that had data is notified once.

The read methods return the same object while nothing changed, so in React you can wire subscribe and the three read methods straight into useSyncExternalStore.

ChatMemberStoreEvent

type ChatMemberStoreEvent =
  | ChatMemberStoreMembersLoadedEvent
  | ChatMemberStoreMemberUpsertedEvent
  | ChatMemberStoreMemberRemovedEvent
  | ChatMemberStoreCurrentUserLoadedEvent;

The events the member store's write entry point takes: a union of the four below.

ChatMemberStoreMembersLoadedEvent

interface ChatMemberStoreMembersLoadedEvent {
  type: "membersLoaded";
  conversationId: string;
  members: readonly ChatLoadedMember[];
}

A conversation's member list arrived and replaces the whole list: people not in it are removed from this conversation (the participant entry itself stays, since past messages still show their name), and the order follows this list. Participants are written into the participant table by id, so the same person seen in other conversations changes too. When nothing changed, nothing is written and nobody is notified. A duplicate id or an unknown kind throws TypeError and changes nothing.

ChatMemberStoreMemberUpsertedEvent

interface ChatMemberStoreMemberUpsertedEvent {
  type: "memberUpserted";
  conversationId: string;
  memberId: string;
  role: ChatConversationRole;
  joinedAt?: string;
  participant?: ChatStoreParticipant;
}

Someone joined the conversation, or their conversation role changed.

  • The conversation's member list was loaded: the row with memberId is updated in place (without joinedAt the old one is kept), or appended when missing.
  • It was never loaded: no member list is created for it (one row is not the whole list, so getMembers still returns undefined); only the participant is written.
  • With participant, it is written into the participant table by id; without it only the membership changes (for example, the owner-changed signal carries only an id).

A participant.id that differs from memberId, or an unknown kind, throws TypeError and changes nothing.

ChatMemberStoreMemberRemovedEvent

interface ChatMemberStoreMemberRemovedEvent {
  type: "memberRemoved";
  conversationId: string;
  memberId: string;
}

Someone left the conversation (removed, or left themselves): removed from this conversation's member list; the participant stays. When the member list was never loaded, or they were not in it, nothing happens.

ChatMemberStoreCurrentUserLoadedEvent

interface ChatMemberStoreCurrentUserLoadedEvent {
  type: "currentUserLoaded";
  userId?: string;
  orgRole?: ChatOrgRole;
}

Who the current user is and what their org role is. The host hands it in after sign-in and after an org switch, and again when the org role changes; when both fields equal the previous ones nothing happens. When they change, every subscribed conversation is notified once (the org role is part of every conversation's getMyRoles). The conversation role is not here: it is read from the current user's row in each conversation's member list, so there is only one copy, and it follows the member list when the owner changes or the user is removed.

ChatMemberStoreListener

type ChatMemberStoreListener = () => void;

The callback for a change to a conversation's member data, see subscribe. Read the new data with getMembers, getParticipant and getMyRoles.

ChatStoreParticipant

interface ChatStoreParticipant {
  readonly id: string;
  readonly displayName: string;
  readonly avatarUrl?: string;
  readonly kind: ChatParticipantKind;
}

One participant (a person, an agent or a system member), one entry per id across conversations. The writer resolves the displayName fallbacks; avatarUrl is left out when there is no avatar. The store keeps only these four fields and hands out frozen copies.

ChatParticipantKind

type ChatParticipantKind =
  | "human"
  | "agent"
  | "system";

A participant's kind, with the same values as the member kind in the @openmaxai/chat/host contract. There is no bot: internal and external agents are both agent; system is a system member such as the dispatch center.

ChatMembership

interface ChatMembership {
  readonly memberId: string;
  readonly role: ChatConversationRole;
  readonly joinedAt?: string;
}

One person's membership in one conversation: only the conversation role and the join time (an ISO 8601 string, as given). The current user's mute and pin are not here; they belong to the conversation list row.

ChatConversationRole

type ChatConversationRole =
  | "OWNER"
  | "ADMIN"
  | "MEMBER"
  | "PUBLISHER"
  | "SUBSCRIBER"
  | "UNSPECIFIED";

A conversation role, with the values of role on each row of the members API (upper case; UNSPECIFIED means the backend gave no role). The backend does not push ordinary role changes today, only owner changes.

ChatOrgRole

type ChatOrgRole =
  | "org-owner"
  | "org-admin"
  | "org-member"
  | (string & {});

The current user's role slug in the organization. There are four built-in roles: org-owner, org-admin and org-member, plus org-system for system members (such as the dispatch center); a system member is not a signed-in user, so the current user is never it and the type does not list it. An organization may also have custom roles, so other strings are accepted too.

ChatMyRoles

interface ChatMyRoles {
  readonly conversationRole: ChatConversationRole | undefined;
  readonly orgRole: ChatOrgRole | undefined;
}
Field Description
conversationRole The conversation role: the current user's row in this conversation's memberships. Absent when the member list was never loaded, the current user is unknown, or they are not a member.
orgRole The org role, from currentUserLoaded; absent when unknown.

Whether buttons are enabled or shown is decided from this: the check is can() in @openmaxai/chat/host (useChatSdkPermissions in @openmaxai/chat-sdk reads this and passes it to can()). This store only provides the data. Note that a missing conversationRole cannot tell "never fetched", "current user unknown" and "not a member" apart; can() treats it as unknown, not as "no permission".

ChatLoadedMember

interface ChatLoadedMember {
  participant: ChatStoreParticipant;
  role: ChatConversationRole;
  joinedAt?: string;
}

One row of membersLoaded: a participant with their conversation role and join time in this conversation.

createChatConversationStore

function createChatConversationStore<C extends ChatStoreConversationRow>(options: ChatConversationStoreOptions<C>): ChatConversationStore<C>;

Creates a conversation store, one per host (per signed-in user): the conversation list (pages, cursor, refetch), conversation rows stored by id, and the part that fetches them. Like the member store it is memory-only: the conversation list has no change log, so pin, hide and unread changes made while offline cannot be caught up, and persisting it would only draw an outdated list first.

  • One copy of each row, by id. The list, reads by id (getConversation) and unread state (getUnread) read the same row. Only fetched pages decide the list order: writes by id and patches neither reorder it nor add rows to it or remove rows from it.
  • The list is fetched only on these triggers: no data yet (the first reader arrives, openList); an invalidation (invalidate: after a write, after coalesced signals, and the ones you pass in on reconnect and when the page becomes visible again); a reader calling refetch / retryList. A reader mounting does not trigger a refetch by itself: with data and no invalidation, a new reader reads what is there. An invalidation refetches when there are readers and is otherwise remembered for the next reader; while a list fetch (first page, refetch or next page) is in flight it sends nothing new and refetches once after that fetch lands, provided there are readers. So invalidations alone never put a second list request on the network.
  • "In the list" and "has the row" are kept apart. The row cache stays until clear() (reads by id and the header use it), while list membership follows the latest fetched pages and is read through listed on the read state. When a reader arrives for a conversation that is not in the current list, it is fetched by id again; a cached row does not count as listed.
  • Refetch keeps the number of pages. It fetches as many pages as were loaded, starting from the first, and swaps them in at once when all have arrived; a failure part-way swaps nothing in.
  • Unchanged rows keep their object. A fetched row structurally equal to the stored one keeps the stored object, and when neither the order nor any row changed the list array is kept too, so readers do not re-render.
  • Timing is kept apart. The coalescing window and retry waits use the timers from the options (timers); tests pass a fake clock.

@openmaxai/chat-sdk does not use it yet.

conversation-store-wiring.ts

import { createChatConversationStore } from "@openmaxai/chat-store";

const conversations = createChatConversationStore({
  source: host.conversations,
  // Do not retry expired credentials; retry other failures up to 3 times with exponential backoff.
  retry: (n, error) => (isUnauthorized(error) || n > 3 ? false : Math.min(1000 * 2 ** (n - 1), 30_000)),
});

// New-message, read and similar signals: coalesced into one refetch per second.
host.signals.subscribe(() => conversations.invalidate({ coalesce: true }));

// Pin succeeded: patch the row, then refetch right away (the order follows the server).
await host.conversations.setPinned(id, true);
conversations.dispatch({ type: "conversationPatched", conversationId: id, patch: { pinned: true } });
conversations.invalidate();

ChatConversationStore

interface ChatConversationStore<C extends ChatStoreConversationRow> {
  dispatch(event: ChatConversationStoreEvent<C>): void;
  getList(): ChatConversationListState<C>;
  subscribeList(listener: () => void): () => void;
  openList(): () => void;
  loadMore(): Promise<void>;
  refetch(): Promise<void>;
  invalidate(options?: {
    coalesce?: boolean;
  }): void;
  retryList(): void;
  ensureList(): Promise<void>;
  getConversation(conversationId: string): ChatConversationReadState<C>;
  subscribeConversation(conversationId: string, listener: () => void): () => void;
  openConversation(conversationId: string): () => void;
  retryConversation(conversationId: string): void;
  findConversation(conversationId: string): C | undefined;
  getUnread(conversationId: string): ChatUnreadState;
  clear(): void;
  end(): void;
}
Method Description
dispatch(event) The single write entry point; takes a ChatConversationStoreEvent. Applies synchronously and notifies only when data changed. Throws TypeError on an unknown event type.
getList(), subscribeList(listener) The read state of the conversation list (ChatConversationListState) and its subscription. The read state is the same object while nothing changed.
openList() A list reader arrived; returns the function to call when it leaves. Fetches the first page when there is no data yet or the first page failed last time; refetches when invalidated and data exists; otherwise fetches nothing.
loadMore() Fetches the next page and appends it. Does nothing when there is no next page; while a fetch (first page, next page, refetch) is in flight, returns that one. Rejects on failure, leaving existing data alone.
refetch() Refetches now (fetches the first page if nothing was fetched yet). An in-flight refetch or next page is discarded; its promise still resolves. Rejects on failure.
invalidate(options?) Invalidates the list. Refetches when there are readers; with coalesce: true it waits for the coalescing window (1000 ms by default) to end, refetching once however many times it is called inside the window; an invalidation without coalesce inside the window refetches at once and cancels the window. Without readers it is only remembered. While a list fetch is in flight it does not discard it: the list is refetched once after that fetch lands (or fails). Call it once on reconnect and once when the page becomes visible again.
retryList() Redoes the step that failed last (first page, next page or refetch); does nothing when nothing failed or a fetch is in flight.
ensureList() Resolves at once when the first page is loaded; otherwise fetches it (or waits for the one in flight). Meant for "check the list before opening by id".
getConversation(id), subscribeConversation(id, listener) The read state of one conversation (ChatConversationReadState) and its subscription; notifies when the row or its unread state changed.
openConversation(id) A reader of this conversation arrived; returns the function to call when it leaves. When it is not in the current default list and the source has loadConversation: waits for the first list page if it is in flight, and if it is still not listed fetches it by id once and writes the result (not into the list); a result of undefined also deletes the cached row. A cached row does not count as listed: after a refetch drops it from the list, readers fetch it by id again (open readers right away). After a fetch by id that found it or a conversationUpserted, it is not fetched again until a first page or refetch drops it from the list (one that was never in the list is not dropped by a refetch, so a refetch does not fetch it again); after an explicit removal (whether or not it had a reader then), it is not fetched again until a first page or refetch brings it back into the list. A result of undefined is only remembered until all readers leave, and the next reader really fetches again (it may just have been created). Without loadConversation it can only wait for the list: the first page is fetched if it has not been.
retryConversation(id) Fetches by id again after a failure or a result of undefined; does nothing otherwise.
findConversation(id) The conversation in the store, without a request.
getUnread(id) The unread state of one conversation (ChatUnreadState), notified through subscribeConversation.
clear() Clears all data and fetch state (on sign-out or org switch). Results of in-flight fetches are no longer written; the coalescing window and pending retries are cancelled. Subscriptions and readers stay: a list reader makes it fetch the first page again, and a conversation reader fetches as openConversation does.
end() Ends the store for good (the scope it served is over; @openmaxai/chat-sdk hosts call it when the scope ends): drops everything like clear(), but sends no request, now or later. Results of in-flight fetches are no longer written; subscribers are notified once. Afterwards the list stays empty and loading, and no read, invalidation or event makes it fetch again.

ChatConversationStoreOptions

interface ChatConversationStoreOptions<C extends ChatStoreConversationRow> {
  source: ChatConversationSource<C>;
  retry?: (failureCount: number, error: unknown) => number | false;
  coalesceMs?: number;
  timers?: {
    setTimeout(callback: () => void, ms: number): unknown;
    clearTimeout(handle: unknown): void;
  };
}
Field Description
source The read methods, see ChatConversationSource.
retry Whether to try again after a fetch failed: return how many milliseconds to wait before the next attempt, or false to stop and hand the failure on. failureCount is how many times this fetch has failed so far (1 on the first failure). Applies to every list fetch and to fetches by id. Without it nothing is retried. A fetch that is superseded while waiting, or whose store is cleared with clear(), is not tried again.
coalesceMs The coalescing window in milliseconds, 1000 by default.
timers The timers for the coalescing window and retry waits; the global setTimeout and clearTimeout when not given.

ChatConversationSource

interface ChatConversationSource<C extends ChatStoreConversationRow> {
  list(input: {
    cursor?: string;
  }): Promise<ChatConversationSourcePage<C>>;
  loadConversation?(conversationId: string): Promise<C | undefined>;
}

The read methods the conversation store uses, shaped like the host's conversations, which can be passed in as is. list is called with cursor only: it reads the default list (without hidden conversations); search and the hidden list do not go into the conversation store. loadConversation is optional; without it only conversations in the list can be read.

ChatConversationSourcePage

interface ChatConversationSourcePage<C extends ChatStoreConversationRow> {
  conversations: readonly C[];
  nextCursor?: string;
}

One page of the conversation list, the return value of the host's conversations.list. A missing or empty nextCursor means the end.

ChatStoreConversationRow

interface ChatStoreConversationRow {
  readonly id: string;
  readonly pinned?: boolean;
  readonly done?: boolean;
  readonly muted?: boolean;
  readonly unread_count: number;
  readonly unread_mention?: ChatUnreadMention;
  readonly last_read_seq?: number;
}

The fields a conversation row the store reads and writes must have, named as on the host's ChatConversation, so that row can be passed in as is; other fields are stored and returned unchanged. done is what the product calls "hidden".

ChatUnreadMention

type ChatUnreadMention =
  | "none"
  | "direct"
  | "all";

The unread-mention marker: direct someone mentioned me directly, all there is an @all, none there is none.

ChatConversationStoreEvent

type ChatConversationStoreEvent<C extends ChatStoreConversationRow> =
  | {
      type: "conversationUpserted";
      conversation: C;
    }
  | {
      type: "conversationPatched";
      conversationId: string;
      patch: ChatConversationPatch;
    }
  | {
      type: "conversationRemoved";
      conversationId: string;
    };

The events the conversation store's write entry point takes:

  • conversationUpserted: new content of one conversation (fetched when opening by id, or returned in a write response), swapped in as a whole row by id. When it is in the list it is replaced in place and the order stays; otherwise it can only be read by id and is not added to the list. When nothing changed the stored object is kept and nobody is notified.
  • conversationPatched: changes the current user's state of one conversation, see ChatConversationPatch. Only that row's fields change; neither the order nor the members of the list change: a hidden row stays in the list and a pinned row does not move to the top until the next refetch follows the server. When an in-flight fetch returns after the patch, the patch is applied to the row it brings back (also when the row was not in the store yet); without an in-flight fetch, it does nothing when the store does not have the conversation, and it does nothing when the values are unchanged.
  • conversationRemoved: an explicit "removed / deleted". The row leaves the list and is deleted; reads by id get nothing and do not fetch by id; a later refetch that brings it back brings it back as usual. When an in-flight fetch returns after the removal, it does not write the row back.

ChatConversationPatch

interface ChatConversationPatch {
  pinned?: boolean;
  hidden?: boolean;
  muted?: boolean;
  unreadCount?: number;
  unreadMention?: ChatUnreadMention;
  lastReadSeq?: number;
}

A change to the current user's state of one conversation; only the given fields change: pinned writes pinned, hidden writes done, muted writes muted, unreadCount writes unread_count, unreadMention writes unread_mention and lastReadSeq writes last_read_seq.

ChatConversationListState

interface ChatConversationListState<C extends ChatStoreConversationRow> {
  readonly conversations: readonly C[];
  readonly status: ChatReadStatus;
  readonly error: unknown;
  readonly isFetching: boolean;
  readonly hasMore: boolean;
}
Field Description
conversations The fetched pages joined in order; each id appears once (at its first position, with the latest content).
status loading no data yet and fetching (including retrying after the first page failed); ready there is data; error the first page failed and there is no data.
error Why the latest fetch failed, the raw value the read method rejected with; gone after a later fetch succeeds. When a fetch fails while there is data, the data stays and status is still ready.
isFetching A fetch is in flight (first page, next page and refetch all count).
hasMore There is a next page.

ChatConversationReadState

interface ChatConversationReadState<C extends ChatStoreConversationRow> {
  readonly conversation: C | undefined;
  readonly listed: boolean;
  readonly status: ChatReadStatus;
  readonly error: unknown;
  readonly isFetching: boolean;
}

The read state of one conversation. listed is whether it is in the default list right now (in the latest fetched pages and not removed since); having a conversation does not imply listed. status: ready when the store has the row; otherwise loading when the source has loadConversation and it was not fetched yet (or is being fetched), error when fetching failed (error is the raw value), and ready without a conversation when the fetch returned undefined (it does not exist or cannot be seen) or it was removed. Without loadConversation it follows the list: loading until the first page arrives, error when the first page failed (error is the list's reason), and ready without a conversation when the page arrived without it. isFetching means it is being fetched by id.

ChatUnreadState

interface ChatUnreadState {
  readonly count: number;
  readonly mention: ChatUnreadMention;
  readonly lastReadSeq?: number;
}

The unread state of one conversation: count from unread_count, mention from unread_mention (none when not given) and lastReadSeq from last_read_seq. When the store does not have the conversation, count is 0 and mention is none. The same object while nothing changed.

createChatReadCursorStore

function createChatReadCursorStore(): ChatReadCursorStore;

Creates a read cursor block, one per host and memory-only: each conversation's own read position (confirmed by the server, and the one write in flight) and the other members' cursors used for receipts (how far each member has read and been delivered, the conversation-level delivered watermark, the member count, whether the snapshot was truncated, and whether receipts are available). It sends no requests, reads no clock, writes no storage and does not know who the current user is: the loader (createChatReadCursorLoader) translates the current user's row into ownConfirmed. Every cursor merges by maximum, and ack is never below read.

Only four events create a record when there is none: tracked, receiptsLoaded, receiptsFailed and ownReportStarted. The rest (memberRead, delivered, ownConfirmed, ownReportSettled) only merge into an existing record and are dropped otherwise, so the read signal the live connection sends for every conversation does not create records for conversations that were never opened. When the receipt snapshot fails, a missing or still pending record becomes unavailable while an available one stays available; an unavailable record does not become available through later signals, only through a snapshot that succeeds.

Each @openmaxai/chat-sdk host creates one and calls clear() when the scope ends (switching org, being removed, signing out, credentials expiring); receipts in the new message area read it through useReadCursors.

ChatReadCursorStore

interface ChatReadCursorStore {
  dispatch(event: ChatReadCursorEvent): void;
  getState(conversationId: string): ChatReadCursorState;
  has(conversationId: string): boolean;
  subscribe(conversationId: string, listener: () => void): () => void;
  clear(): void;
  epoch(): number;
}
Method Description
dispatch(event) The single write entry point, takes a ChatReadCursorEvent. Takes effect synchronously and notifies the conversation's subscribers once, only when something changed. Throws TypeError on an unknown event type and changes nothing.
getState(conversationId) The conversation's ChatReadCursorState, frozen; the same object while nothing changed, and when only the own half changed receipts is still the same object (and vice versa). Without a record it is the empty state shared by all conversations (status is pending, all cursors 0).
has(conversationId) Whether the conversation has a record.
subscribe(conversationId, listener) Subscribes to one conversation and returns the unsubscribe function, safe to call twice. Adding or removing subscriptions inside a callback does not change who this notification reaches.
clear() Drops every record and bumps the epoch; subscriptions stay, and each conversation that had a record is notified once.
epoch() The epoch, bumped by every clear(). The loader records it when it sends a request and drops the result if it changed by the time the request settles.

ChatReadCursorState

interface ChatReadCursorState {
  own: {
    confirmed: number;
    inFlight: number | undefined;
  };
  receipts: {
    status: "pending" | "available" | "unavailable";
    byMember: Readonly<Record<string, ChatMemberCursor>>;
    deliveredUntil: number;
    memberCount: number;
    truncated: boolean;
  };
}

One conversation's cursor state. own.confirmed is your read position confirmed by the server (from your own row in a snapshot, your own read signal, or a report that succeeded); own.inFlight is the write in progress. receipts.byMember includes your own row; callers exclude it when drawing receipts.

ChatMemberCursor

interface ChatMemberCursor {
  read: number;
  ack: number;
}

How far one member has read and been delivered (inclusive seq); ack is never below read.

ChatReadCursorEvent

type ChatReadCursorEvent =
  | {
      type: "tracked";
      conversationId: string;
    }
  | {
      type: "receiptsLoaded";
      conversationId: string;
      snapshot: ChatReadCursorSnapshotShape;
    }
  | {
      type: "receiptsFailed";
      conversationId: string;
    }
  | {
      type: "memberRead";
      conversationId: string;
      memberId: string;
      readUntilSeq: number;
    }
  | {
      type: "delivered";
      conversationId: string;
      ackUntilSeq: number;
    }
  | {
      type: "ownConfirmed";
      conversationId: string;
      readUntilSeq: number;
    }
  | {
      type: "ownReportStarted";
      conversationId: string;
      seq: number;
    }
  | {
      type: "ownReportSettled";
      conversationId: string;
      seq: number;
      ok: boolean;
    };

The events the block's write entry point takes.

Event Without a record With a record
tracked Creates one (pending, all cursors 0) No change
receiptsLoaded Creates one, then merges Merges into byMember by maximum; memberCount takes the larger of old and new, truncated comes from the snapshot; deliveredUntil is untouched; status becomes available
receiptsFailed Creates one, unavailable pending ⇒ unavailable; otherwise no change
memberRead / delivered Dropped Merges by maximum; status unchanged
ownConfirmed Dropped own.confirmed takes the maximum
ownReportStarted Creates one, then records the write Records seq as inFlight when it is above max(confirmed, inFlight)
ownReportSettled Dropped On success confirmed takes the maximum; inFlight is cleared when it equals seq (success or failure)

ChatReadCursorSnapshotShape

interface ChatReadCursorSnapshotShape {
  cursors: readonly {
    memberId: string;
    readUntilSeq: number;
    ackUntilSeq: number;
  }[];
  memberCount: number;
  truncated: boolean;
}

One conversation's cursor snapshot, the same shape as the ChatReadCursorSnapshot the host's messaging.loadReadCursors returns (the store package does not depend on @openmaxai/chat, so it declares the shape itself).

ChatReadCursorSignal

type ChatReadCursorSignal =
  | {
      kind: "read";
      conversationId: string;
      memberId: string;
      readUntilSeq: number;
    }
  | {
      kind: "delivery";
      conversationId: string;
      ackUntilSeq: number;
    }
  | {
      kind: "reconnected";
    }
  | {
      kind: "connected";
    };

The three live signals the loader understands, the same shape as read, delivery and reconnected among the host's inbound signals.

createChatReadCursorLoader

function createChatReadCursorLoader(options: ChatReadCursorLoaderOptions): ChatReadCursorLoader;

Creates the read cursor loader, created alongside the block (one per host). It turns snapshots, live signals and read reports into block events and swallows every rejection:

  • Opening: when the open count for a conversation goes from 0 to 1 it dispatches tracked (whether or not the host has receipts) and, with loadReadCursors, fetches one snapshot: receiptsLoaded on success, receiptsFailed on any failure (including the 412 of receipts turned off). Returns the close function. It subscribes to signals only while some conversation is open.
  • Who you are: it calls currentUserId() each time. The row in a snapshot or read signal whose memberId is you goes into byMember as usual and also dispatches ownConfirmed; while the identity is not back yet (empty string) it is not translated.
  • Signals: read → memberRead (plus ownConfirmed for your own); delivery → delivered; reconnected and connected (the first open) → one snapshot refetch for each open conversation. Other kinds are ignored.
  • Epoch: each request records store.epoch() when sent and drops its result if the epoch changed by the time it settles.
  • reportRead: no write for an observed conversation, without markReadUntil, or when seq is not above max(confirmed, inFlight); one write in flight per conversation, later calls only keep the largest queued value, written once after the write in flight settles (success or failure) if it is still larger; a failure only rolls back the in-flight value and is not retried itself.

ChatReadCursorLoader

interface ChatReadCursorLoader {
  open(conversationId: string): () => void;
  reportRead(conversationId: string, seq: number, options: {
    observed: boolean;
  }): void;
  dispose(): void;
}

The loader: open opens a conversation (counted), reportRead writes a read report (never rejects or throws), dispose unsubscribes from signals and drops open counts and queued reports (it can open again afterwards).

ChatReadCursorLoaderOptions

interface ChatReadCursorLoaderOptions {
  store: ChatReadCursorStore;
  currentUserId: () => string;
  loadReadCursors?: (conversationId: string) => Promise<ChatReadCursorSnapshotShape>;
  markReadUntil?: (conversationId: string, readUntilSeq: number) => Promise<void>;
  signals?: {
    subscribe(listener: (signal: ChatReadCursorSignal | {
      kind: string;
    }) => void): () => void;
  };
}

The loader's ports. loadReadCursors and markReadUntil must both be the host's versions already wrapped by the credential latch (credential expiry is handled by their own latch, the loader does not check it); in the SDK markReadUntil is the host's conversations.markReadUntil (the conversation-list invalidation after success lives in the host). signals is the host's inboundDelivery, omitted without a live connection, in which case receipts are drawn statically from the snapshot taken on open.

createChatAgentActivityStore

function createChatAgentActivityStore<S extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, R extends string = ChatAgentActivityEndReason>(): ChatAgentActivityStore<S, R>;

Everything from here to ChatAgentActivitySummaryRef belongs to Agent runs, read-only progress (experimental · transitional). Replaced when the planned Agent runs capability lands.

Creates a run table, memory-only: one Agent run table "conversation → run" (ChatAgentActivityRuns) plus a whole-table subscription. Advancing and sweeping call applyAgentActivityFrame and sweepAgentActivityRuns internally, and readers are notified only when the table changed. It reads no clock, creates no timers and sends no requests: the caller gives the time and creates the sweep timer (it only needs to run while the table has runs, which is what size() is for). The type parameters are the step and the end reason, defaulting to this package's structural copies ChatAgentActivityStep and ChatAgentActivityEndReason.

It has the same lifecycle as the read cursor block (readers subscribe, clear() when the scope ends) with a different subscription grain: the read cursor block is subscribed per conversation, the run table as a whole, and readers read their conversation after a notification. Today @openmaxai/chat-sdk hosts do not create one yet; a host that keeps its own run store can call the same pure functions.

ChatAgentActivityStore

interface ChatAgentActivityStore<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> {
  applyFrame(frame: ChatAgentActivityFrame<Step, EndReason>, now: number): void;
  sweep(now: number): void;
  getRuns(conversationId: string): readonly ChatAgentActivityRun<Step, EndReason>[];
  size(): number;
  subscribe(listener: () => void): () => void;
  clear(): void;
}
Method Description
applyFrame(frame, now) Advances by one frame (calls applyAgentActivityFrame). Notifies only when the table changed; duplicate, out-of-order and non-terminal-after-terminal frames neither change the table nor notify.
sweep(now) Sweeps for lost sync and eviction (calls sweepAgentActivityRuns). Notifies only when the table changed.
getRuns(conversationId) One conversation's runs (calls selectConversationAgentActivityRuns), ascending by startedAt; the same array between two notifications, and the same frozen empty array when there are none.
size() The number of runs in the table, summed across conversations.
subscribe(listener) Subscribes to the whole table and returns the unsubscribe function, which is harmless to call twice. Subscribing or unsubscribing inside a callback does not change who this notification reaches.
clear() Drops every run and notifies once only if there were runs; safe to call again, a no-op on an empty table. The table still advances afterwards; stopping intake is the caller's job.

applyAgentActivityFrame

function applyAgentActivityFrame<S extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, R extends string = ChatAgentActivityEndReason>(runs: ChatAgentActivityRuns<S, R>, frame: ChatAgentActivityFrame<S, R>, now: number): ChatAgentActivityRuns<S, R>;

Advances a run table by one frame and returns the new table; a dropped frame returns the same table (same reference, so the caller can tell whether to notify). Rules:

  • a run's key is (conversation, sender, runId), see agentActivityRunKey;
  • a frame whose sequence is not greater than the run's last one is dropped (frames can repeat and arrive out of order, and the server only deduplicates within one replica and forgets, so deduplication happens here); a non-terminal frame after a terminal one is dropped too (terminal states do not go back), while a terminal frame after a terminal one is taken;
  • a first frame with sequence > 1 sets joinedLate; a skipped sequence sets gap, which stays set;
  • steps are replaced whole by id, sorted by at, and only the last AGENT_ACTIVITY_MAX_STEPS are kept; a frame without steps keeps the same array;
  • execStartedAt is kept once it has appeared; stepCount and sourceMessageId carry over from the previous frame when the frame omits them; the other fields follow this frame;
  • a frame clears syncLost, and now becomes lastFrameAt;
  • when the run count then exceeds AGENT_ACTIVITY_MAX_RUNS, the runs with the oldest lastFrameAt are evicted.

sweepAgentActivityRuns

function sweepAgentActivityRuns<S extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, R extends string = ChatAgentActivityEndReason>(runs: ChatAgentActivityRuns<S, R>, now: number): ChatAgentActivityRuns<S, R>;

Sweeps for lost sync and eviction: a non-terminal run with now - lastFrameAt > ttlMs gets syncLost (the state stays, no terminal state is inferred: terminal frames can be lost and the server sends none when an Agent crashes); a terminal or lost run idle for more than AGENT_ACTIVITY_EVICT_AFTER_MS is evicted, and a conversation left without runs is dropped. Returns the same table when nothing changed; when only some conversations changed, the others keep their inner Map.

selectConversationAgentActivityRuns

function selectConversationAgentActivityRuns<S extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, R extends string = ChatAgentActivityEndReason>(runs: ChatAgentActivityRuns<S, R>, conversationId: string): readonly ChatAgentActivityRun<S, R>[];

One conversation's runs, ascending by startedAt, frozen. The same array while that conversation's inner Map is unchanged (usable directly as a useSyncExternalStore snapshot); with no runs, the same frozen empty array shared by every conversation.

agentActivityRunKey

function agentActivityRunKey(conversationId: string, senderId: string, runId: string): string;

A run's key: conversation, sender and runId joined with |. A runId is only unique within one Agent, and two Agents in one conversation can collide, so the key includes the sender.

AGENT_ACTIVITY_MAX_STEPS

const AGENT_ACTIVITY_MAX_STEPS = 500;

The most steps kept per run; beyond it the earliest are dropped.

AGENT_ACTIVITY_EVICT_AFTER_MS

const AGENT_ACTIVITY_EVICT_AFTER_MS = 10 * 60000;

How long (milliseconds, 10 minutes) a terminal or lost run may sit idle before it is evicted.

AGENT_ACTIVITY_MAX_RUNS

const AGENT_ACTIVITY_MAX_RUNS = 100;

The most runs one table keeps, summed across conversations; beyond it the runs with the oldest lastFrameAt are evicted.

ChatAgentActivityFrame

interface ChatAgentActivityFrame<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> {
  conversationId: string;
  runId: string;
  sourceMessageId?: string;
  senderId: string;
  sequence: number;
  state: ChatAgentActivityState;
  startedAt: number;
  execStartedAt?: number;
  endedAt?: number;
  stepCount?: number;
  endReason?: EndReason;
  steps: Step[];
  dropped: number;
  ttlMs: number;
  serverTs: number;
}

One decoded, validated frame. This package does not decode: the OpenMax adapter decodes frames internally, and other callers hand frames in this shape. steps are the steps this frame brings (replaced whole by id); ttlMs is how long after this frame the run counts as lost without a new one; startedAt starts the waiting timer and execStartedAt the execution timer.

ChatAgentActivityRun

interface ChatAgentActivityRun<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> {
  key: string;
  conversationId: string;
  senderId: string;
  runId: string;
  sourceMessageId?: string;
  state: ChatAgentActivityState;
  syncLost: boolean;
  startedAt: number;
  execStartedAt?: number;
  endedAt?: number;
  stepCount?: number;
  endReason?: EndReason;
  steps: readonly Step[];
  dropped: number;
  firstSequence: number;
  lastSequence: number;
  joinedLate: boolean;
  gap: boolean;
  lastFrameAt: number;
  ttlMs: number;
}

One merged run. key is described at agentActivityRunKey; syncLost means sync was lost; firstSequence / lastSequence are the sequence of the first and last frame; joinedLate means the first frame had sequence > 1 (refresh, opened midway, another device); gap means a sequence was skipped; lastFrameAt is the caller's local time of the last frame, which lost sync and eviction are measured from.

ChatAgentActivityRuns

type ChatAgentActivityRuns<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> = ReadonlyMap<string, ReadonlyMap<string, ChatAgentActivityRun<Step, EndReason>>>;

One run table: conversation → (run key → run), across all conversations. Every change makes a new Map, and unchanged conversations keep theirs.

ChatAgentActivityState

type ChatAgentActivityState =
  | "queued"
  | "thinking"
  | "tool"
  | "done"
  | "failed";

The state on frames and runs: queued is waiting, thinking and tool both mean working, done and failed are terminal.

ChatAgentActivityStep

type ChatAgentActivityStep =
  | {
      readonly id: string;
      readonly kind: "tool";
      readonly category: "command" | "read" | "write" | "edit" | "search_files" | "search_web" | "fetch_web" | "image" | "delegate" | "kb" | "skill" | "tool";
      readonly status: "running" | "ok" | "error";
      readonly at: number;
      readonly endedAt?: number;
      readonly title?: string;
      readonly object?: string;
      readonly progress?: string;
      readonly waitFor?: "command_result" | "search_results" | "page_response" | "subagent_result" | "kb_result" | "tool_result";
      readonly livePreview: boolean;
      readonly detail?: {
        readonly type: "text";
        readonly text: string;
        readonly truncated: boolean;
      } | {
        readonly type: "links";
        readonly items: readonly {
          readonly title?: string;
          readonly url: string;
          readonly site: string;
        }[];
        readonly total: number;
        readonly truncated: boolean;
      } | {
        readonly type: "output";
        readonly exitCode?: number;
        readonly lines: number;
        readonly truncated: boolean;
      } | {
        readonly type: "diff";
        readonly file: string;
        readonly added: number;
        readonly removed: number;
        readonly preview?: string;
        readonly truncated: boolean;
      } | {
        readonly type: "children";
        readonly items: readonly {
          readonly title?: string;
          readonly object?: string;
          readonly status: "running" | "ok" | "error";
        }[];
        readonly total: number;
        readonly truncated: boolean;
      };
    }
  | {
      readonly id: string;
      readonly kind: "thinking";
      readonly at: number;
      readonly body: string;
    }
  | {
      readonly id: string;
      readonly kind: "note";
      readonly at: number;
      readonly code: "merged_turn" | "steps_omitted";
      readonly count?: number;
    };

One decoded step (schema v3): a tool step, a thinking step or a note step. This package reads only id and at and passes the other fields through to the layer that draws the block.

ChatAgentActivityEndReason

type ChatAgentActivityEndReason =
  | "runtime_restarted"
  | "interrupted"
  | "no_reply";

Why a run failed.

ChatAgentActivitySummary

type ChatAgentActivitySummary<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> =
  | ChatAgentActivitySummaryFull<Step, EndReason>
  | ChatAgentActivitySummaryRef;

The neutral run field on a message (agent_run_summary on ChatMessage): the adapter decodes the backend's run summary into this shape before handing the message over (the OpenMax adapter decodes it internally). The summary bar and the reply takeover read only this field, never the backend's raw agent_run. The full form draws the summary bar; both forms make the live block of the same run give way; without the field there is no summary bar.

ChatAgentActivitySummaryFull

interface ChatAgentActivitySummaryFull<Step extends {
  readonly id: string;
  readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> {
  form: "full";
  schemaVersion: 3;
  runId: string;
  sourceMessageId?: string;
  state: "done" | "failed";
  queuedAt?: number;
  execStartedAt?: number;
  endedAt?: number;
  stepCount: number;
  endReason?: EndReason;
  steps: readonly Step[];
}

The full form of the neutral run field: the summary a finished run leaves on its reply (schema v3).

ChatAgentActivitySummaryRef

interface ChatAgentActivitySummaryRef {
  form: "ref";
  runId: string;
}

The reference form of the neutral run field: a later reply of the same run, or an old plugin's reply that cannot be parsed but carries a valid run id. Used only for the takeover, never draws a summary bar.