OpenMax
Free Trial

Overview

Overview of the message store package @openmaxai/chat-store: status, the two entry points, wiring it into a host, and an index of every export.

Overview

@openmaxai/chat-store is the message store package of the Chat SDK: for each conversation it keeps a loaded range sorted by seq and a watermark, takes data through a single write entry point, and leaves missing messages to the gap-fill scheduler, which fetches forward from the watermark. It does not depend on React, does not touch the DOM, sends no requests, and depends on no other chat package.

These pages are written from the package's current source and are the reference for the package itself: this page is the overview (status, entry points, wiring it into a host, an index of every export), and the signature and details of each export are on the eight pages below. When and how gaps are filled is on Realtime and sync · Gap-fill.

In this section

  • Store: createChatStore, ChatStore, the store options ChatStoreOptions, the conversation snapshot ChatConversationSnapshot, the request result cache createChatRequestCache, the memory-only member store createChatMemberStore, the memory-only conversation store createChatConversationStore, the memory-only read cursor block createChatReadCursorStore with its loader createChatReadCursorLoader, and the pure functions that merge Agent run frames, applyAgentActivityFrame, sweepAgentActivityRuns and selectConversationAgentActivityRuns, with the memory-only run table createChatAgentActivityStore.
  • Write events: The ChatStoreEvent that the single write entry point dispatch takes and its thirteen events, including the watermark at request time requestWatermark, optimistic sending and optimistic changes.
  • Subscriptions: The callback ChatStoreListener, one change ChatStoreChange and the range change ChatStoreDataEvent.
  • Gap fill: createChatGapFillScheduler with its options, read methods, entry points for each moment and results, and catching up on changes from the change log.
  • Storage and data types: The storage interface ChatStorage and createMemoryStorage, createIndexedDbStorage, the local data options ChatLocalDataOptions and encryption ChatStorageEncryption, ChatMessage and the other message data types, CHAT_STORE_VERSION.
  • Thread loader: createChatThreadLoader with its options, the read methods ChatThreadSource, the read state of a conversation and of a single message, and jumping to a message (ChatMessageTarget, ChatJumpResult); usable by pages without React too.
  • React binding: ChatStoreProvider of @openmaxai/chat-store/react and the hooks that read the store, useMessages, useMessage and useMessageByClientId, plus useConversationList, useConversation and useUnread, which read the conversation store, and useReadCursors, which reads the read cursor block.
  • Inspection API: inspectChatStore of @openmaxai/chat-store/inspect: read-only inspection snapshots per conversation and global, the stream of store events, and a storage estimate.

Status

  • The code is on main. Everything under "Available" below is in the repository, and these pages are written from that source.
  • Not wired to the UI yet. Today the @openmaxai/chat components do not read it, and @openmaxai/chat-sdk does not re-export it yet. The exception is the member store: each @openmaxai/chat-sdk host has one, the host's synchronous identity.getMember and listMembers read from it, and fetched member lists are written into it.
  • The API may still change. Every export is marked @experimental; names and shapes may change.
  • Available: the store and its single write entry point dispatch (including optimistic-send reconciliation and optimistic reactions, edits and recalls), the gap-fill scheduler, the request result cache, the memory-only member store (participants, each conversation's memberships, the current user's conversation role and org role), the memory-only conversation store (paging and refetching the conversation list, coalesced invalidation, list membership kept apart from the row cache, fetching one conversation by id, patches for pin, hide, mute and unread, explicit removal, an injectable retry policy), the memory-only read cursor block and its loader (your own read position and the receipt cursors, merging snapshots and live signals, dropping by epoch the results of requests sent before a clear, read reports with one write in flight per conversation), the pure functions that merge Agent run frames and the memory-only run table (client-side deduplication, gaps, lost sync, eviction, a total limit, with the time given by the caller), the thread loader, the storage interface ChatStorage with its in-memory and IndexedDB implementations (single-tab lock, eviction when the quota is full, the encryption switch), openLocalData and clearLocalData on the store handle to open and clear local data (including the automatic wipe when a different user signs in) and clearConversation to clear one conversation, server messages and watermarks written through the store landing on the device, drawing the messages already on the device first when a conversation opens and then filling the gap, catching up from the change log on changes to existing messages made while away (edits, recalls, deletes, reactions, settled cards), keeping only the watermark of a conversation switched away from, reading an unloaded end back by seq (from the device when it has it), jumping to a message from outside (by server id, or by the client_msg_id of a message you sent; when it is not in the window, the window around it is swapped in, from the device when it has it), reading a message you sent by client_msg_id, the message data types, in the React entry point ChatStoreProvider with seven hooks, useMessages, useMessage, useMessageByClientId, useConversationList, useConversation, useUnread and useReadCursors, and in the inspection entry point the read-only inspection API inspectChatStore.
  • Not yet: hooks for data the store does not hold yet (the total unread count, agent runs and so on). The conversation store is not wired into @openmaxai/chat-sdk yet. Eviction by conversation when the quota is full only knows which conversations the IndexedDB storage read least recently, not which ones are open in the store.

Entry points

Entry point What is in it Dependencies
@openmaxai/chat-store The store, the gap-fill scheduler, the request result cache, the member store, the conversation store, the Agent run merge functions and run table, the thread loader, the storage interface and its in-memory and IndexedDB implementations, the message data types, the version constant No runtime dependencies
@openmaxai/chat-store/react The Provider that hands the store to components, the hooks that read the store, the version constant peer react 19 (optional); only this entry point may depend on it
@openmaxai/chat-store/inspect The read-only inspection API: inspection snapshots, the event stream, a storage estimate No runtime dependencies

Using it in a host

The store does not know the host and sends no requests: the host (or, later, the SDK's common layer) fetches data and hands the result to dispatch; the UI reads from getSnapshot and uses subscribe to know when to read again. The gap-fill scheduler needs only two read methods, shaped like the host's messaging, so you can pass that in directly.

chat-store-wiring.ts

import { createChatGapFillScheduler, createChatStore } from "@openmaxai/chat-store";

// One per host (per signed-in user).
const store = createChatStore();
const gapFill = createChatGapFillScheduler({ store, source: host.messaging });

async function openConversation(conversationId: string) {
  // Note the watermark before the request and pass it to windowLoaded: this tells a late window
  // apart from "the message at the watermark was deleted".
  const requestWatermark = store.getSnapshot(conversationId).watermark;
  const page = await host.messaging.loadThread(conversationId);
  store.dispatch({
    type: "windowLoaded",
    conversationId,
    messages: page.messages,
    hasOlder: page.nextCursor !== undefined,
    olderCursor: page.nextCursor,
    hasNewer: false,
    requestWatermark,
  });
  await gapFill.open(conversationId);
}

// UI: a change only says which conversation and how its range changed; read the data from the snapshot.
const unsubscribe = store.subscribe(conversationId, (change) => {
  render(store.getSnapshot(conversationId), change);
});

Everything else goes to the matching entry point:

When Call
A push brings new content for a message (new message, edit, recall, reactions, card result) store.dispatch({ type: "messageUpserted", conversationId, message })
A message is hard-deleted store.dispatch({ type: "messageDeleted", conversationId, messageId })
A page of history arrives while scrolling up store.dispatch({ type: "olderLoaded", … }); beforeSeq is the seq of the earliest message in the range when the request was sent
A page arrives while scrolling down (the window is not at the latest) store.dispatch({ type: "newerLoaded", … })
The message the view rests near changes store.dispatch({ type: "viewChanged", conversationId, anchorMessageId })
You send a message (or retry) store.dispatch({ type: "sendStarted", conversationId, message }); message.client_msg_id is required and goes to the backend too
The send has a result store.dispatch({ type: "sendSettled", conversationId, clientMsgId, outcome, … }); when it succeeded but the send method returned no message, also call gapFill.sent(conversationId)
You react, edit or recall store.dispatch({ type: "patchStarted", … }) first, then patchSettled when the request ends
A reaction change in a realtime signal (who, which code, added or removed) store.dispatch({ type: "reactionChanged", conversationId, messageId, reactorId, code, added, byMe })
Realtime messages signal (the conversation has new messages) gapFill.messages(conversationId)
The realtime connection reconnected gapFill.reconnected()
The page came back to the foreground gapFill.foreground()
Switching away from or closing a conversation gapFill.close(conversationId)
After sign-in, before opening a conversation await store.openLocalData(userId)
Signing out, an unrecoverable 401 await store.clearLocalData(); the host deletes drafts itself, and the device id is kept
Leaving a group, the group being dissolved, being removed await store.clearConversation(conversationId); single messages fetched by id are deleted with requestCache.remove(["@openmaxai/chat-store", "message", conversationId]), and the host deletes drafts itself
Signing out, tearing down the host gapFill.dispose()

A snapshot is the same object while nothing changed, and an unchanged message is the same object too, so in React you can connect subscribe and getSnapshot with useSyncExternalStore directly.

@openmaxai/chat-store

The root entry point. The table lists every export; each link goes to the page with its signature and details.

Export Kind Description
createChatStore Function Create a message store
ChatStore Interface The store: dispatch, subscribe, getSnapshot
ChatStoreOptions Interface Options of createChatStore
ChatConversationSnapshot Interface A conversation's data right now
createChatRequestCache Function Create a request result cache
ChatRequestCache Interface The request result cache
ChatRequestEntry Interface A key's result right now
ChatRequestKey Type The key of a request
ChatRequestListener Type Called when a key's result changes
createChatMemberStore Function Create a memory-only member store
ChatMemberStore Interface The member store: dispatch, getMembers, getParticipant, getMyRoles, subscribe, clear
ChatMemberStoreEvent Type Events the member store's write entry point takes, a union of the four below
ChatMemberStoreMembersLoadedEvent Interface A conversation's member list arrived and replaces the whole list
ChatMemberStoreMemberUpsertedEvent Interface Someone joined or their role changed
ChatMemberStoreMemberRemovedEvent Interface Someone left the conversation
ChatMemberStoreCurrentUserLoadedEvent Interface The current user and their org role
ChatMemberStoreListener Type Callback for a change to a conversation's member data
ChatStoreParticipant Interface A participant, one entry per id across conversations
ChatParticipantKind Type A participant's kind (no bot)
ChatMembership Interface One person's membership in one conversation
ChatConversationRole Type Conversation role
ChatOrgRole Type Org role slug
ChatMyRoles Interface The current user's conversation role and org role in a conversation
ChatLoadedMember Interface One row of membersLoaded
createChatConversationStore Function Create a memory-only conversation store
ChatConversationStore Interface The conversation store: the conversation list, conversations read by id, unread counts, and the part that fetches them
ChatConversationStoreOptions Interface The options of createChatConversationStore
ChatConversationSource Interface The read methods the conversation store uses
ChatConversationSourcePage Interface One page of the conversation list
ChatStoreConversationRow Interface The fields a conversation row must have
ChatUnreadMention Type The unread-mention marker
ChatConversationStoreEvent Type The events the conversation store's write entry point takes
ChatConversationPatch Interface A change to the current user's state of one conversation
ChatConversationListState Interface The read state of the conversation list
ChatConversationReadState Interface The read state of one conversation
ChatUnreadState Interface The unread state of one conversation
createChatReadCursorStore Function Creates a memory-only read cursor block
ChatReadCursorStore Interface The read cursor block: dispatch, getState, has, subscribe, clear, epoch
ChatReadCursorState Interface One conversation's cursor state
ChatMemberCursor Interface One member's cursor
ChatReadCursorEvent Type The events the block's write entry point takes
ChatReadCursorSnapshotShape Interface One conversation's cursor snapshot
ChatReadCursorSignal Type The three live signals the loader understands
createChatReadCursorLoader Function Creates the read cursor loader
ChatReadCursorLoader Interface The loader: open, read reports, dispose
ChatReadCursorLoaderOptions Interface The loader's ports
createChatAgentActivityStore Function Creates a memory-only run table (Agent runs, read-only progress (experimental · transitional); everything from this row to ChatAgentActivitySummaryRef belongs to the same capability)
ChatAgentActivityStore Interface The run table: applyFrame, sweep, getRuns, size, subscribe, clear
applyAgentActivityFrame Function Advances a run table by one frame
sweepAgentActivityRuns Function Sweeps for lost sync and eviction
selectConversationAgentActivityRuns Function Reads one conversation's runs
agentActivityRunKey Function A run's key
AGENT_ACTIVITY_MAX_STEPS Constant The step limit per run
AGENT_ACTIVITY_EVICT_AFTER_MS Constant How long a terminal or lost run stays
AGENT_ACTIVITY_MAX_RUNS Constant The run limit per table
ChatAgentActivityFrame Interface One decoded, validated frame
ChatAgentActivityRun Interface One merged run
ChatAgentActivityRuns Type One run table
ChatAgentActivityState Type The state on frames and runs
ChatAgentActivityStep Type One decoded step
ChatAgentActivityEndReason Type Why a run failed
ChatAgentActivitySummary Type The neutral run field on a message (ChatMessage.agent_run_summary)
ChatAgentActivitySummaryFull Interface The full form of the neutral run field
ChatAgentActivitySummaryRef Interface The reference form of the neutral run field
ChatStoreEvent Type What the write entry point takes: a union of the thirteen below
ChatStoreWindowLoadedEvent Interface A window arrived; it replaces the range
ChatStoreOlderLoadedEvent Interface An older page arrived; it goes in front
ChatStoreNewerLoadedEvent Interface A newer batch arrived; it goes after
ChatStoreMessageUpsertedEvent Interface New content for one message
ChatStoreMessageDeletedEvent Interface A message was deleted
ChatStoreConversationClosedEvent Interface Close a conversation, keeping only its watermark
ChatStoreViewChangedEvent Interface Which message the view rests near
ChatStoreSendStartedEvent Interface You send a message; it is written as sending first
ChatStoreSendSettledEvent Type The result of a send
ChatStoreLocalMessageRemovedEvent Interface Remove a local message
ChatStorePatchStartedEvent Interface You change a message; the store changes first
ChatStorePatchSettledEvent Interface The request for a change ended
ChatStoreReactionChangedEvent Interface One reaction change (incremental), written to the base directly
ChatStoreListener Type Subscription callback
ChatStoreCardChangedEvent Interface New values for a message's card fields (incremental), written to the base directly
ChatStoreChange Interface What one dispatch changed for one conversation
ChatStoreDataEvent Type One kind of change to the loaded range
createChatGapFillScheduler Function Create a gap-fill scheduler
ChatGapFillSchedulerOptions Interface Options for creating the scheduler
ChatGapFillSource Interface The two injected read methods
ChatGapFillSincePage Interface A batch fetched forward from the watermark
ChatGapFillLatestPage Interface The latest window
ChatGapFillChange Interface One row of the change log
ChatGapFillChangesPage Interface One page of the change log
ChatGapFillMessagesPage Interface A batch of messages fetched by id
ChatGapFillScheduler Interface The scheduler: one entry point per gap-fill moment
ChatGapFillResult Interface The result of one gap-fill
ChatGapFillOutcome Type How a gap-fill ended
ChatGapFillChangesResult Interface The result of one catch-up on changes
ChatGapFillChangesOutcome Type How a catch-up on changes ended
createChatThreadLoader Function Create a thread loader
ChatThreadLoaderOptions Interface Options for creating a thread loader
ChatThreadLoader Interface The thread loader: opening, read state, paging, retrying
ChatThreadReadState Interface A conversation's read state
ChatMessageReadState Interface A message's read state
ChatReadStatus Type Loading status
ChatThreadSource Interface The read methods the thread loader fetches with
ChatThreadSourcePage Interface A page from loadThread
ChatMessageTarget Type Which message to jump to
ChatJumpResult Type The result of a jump
ChatJumpOptions Type Options for a jump (abort signal)
ChatStorage Interface The local storage interface
createMemoryStorage Function An in-memory ChatStorage
createIndexedDbStorage Function A ChatStorage in IndexedDB
IndexedDbStorageOptions Interface Options of createIndexedDbStorage
ChatLocalDataOptions Interface Where local data lives and whether it is encrypted
ChatStorageOpenOptions Interface Options for opening local data (read-only open)
LocalDataUnavailable Class Local data cannot be used by a read-only open
LocalDataUnavailableReason Type Why a read-only open was rejected
ChatStorageEncryption Interface The key for encryption at rest
ChatMessage Interface A message
ChatAttachment Interface Attachment metadata
ChatMessageReaction Interface The summary of one reaction
ChatMessageMention Interface One @ mention
ChatCardState Interface The last action that took effect on a card
ChatCardFormAnswer Interface The settled answer to one question on a form card
ChatMessageType Type Message type
ChatMessageSenderType Type Sender type
ChatMessageDeliveryStatus Type Send status that exists only on this client
CHAT_STORE_VERSION Constant The package version
registerPackageInstance Function (@internal) Registers one copy of a package in the page-wide registry; the other @openmaxai/chat* packages use it, apps do not
isProductionBuild Function (@internal) Whether this is a production build; @openmaxai/chat-sdk uses it, apps do not
PackageInstanceEnv Interface (@internal) The environment registerPackageInstance runs in
DuplicateWarningSink Interface (@internal) Where the duplicate-copy warning goes

The signature blocks are generated from the source code; the descriptions are written by hand. A test in the package checks that neither leaves out any export.

@openmaxai/chat-store/react

The React binding entry point. Only this entry point may depend on react (an optional peer dependency of the package). The hooks only subscribe; fetching is handed to the thread loader of the root entry point.

Export Kind Description
ChatStoreProvider Component Hands the store to the components below it
ChatStoreProviderProps Interface The Provider's props
useChatStore Hook Returns the store handed down by the Provider
useMessages Hook Reads a conversation's message window, with paging
UseMessagesResult Interface The return value of useMessages
useMessage Hook Reads one message
useMessageByClientId Hook Reads a message you sent by client_msg_id
UseMessageResult Interface The return value of useMessage and useMessageByClientId
useConversationList Hook Reads the conversation list, with paging
UseConversationListResult Interface The return value of useConversationList
useConversation Hook Reads one conversation, fetching it by id when it is not in the store
UseConversationResult Interface The return value of useConversation
useUnread Hook Reads the unread state of one conversation
useReadCursors Hook Reads the read cursors of one conversation
CHAT_STORE_VERSION Constant Same as the root entry point

Of the hooks application code will read the store with, this entry point implements only useMessages, useMessage, useConversation and useUnread so far (plus useMessageByClientId and useConversationList); see React binding for how they differ from the target.

@openmaxai/chat-store/inspect

The inspection entry point: a read-only view of the store's internal state right now; Devtools is built on it. It does not depend on React; apps that do not use it are not affected, and until inspectChatStore is first called the store records nothing extra for it (it always keeps only the reason the IndexedDB storage fell back to memory).

Export Kind Description
inspectChatStore Function Gets the inspector of a store
ChatStoreInspector Interface The inspector: two snapshots, one event stream, one storage estimate
ChatStoreConversationInspection Interface The inspection snapshot of one conversation
ChatStoreWindowInspection Interface The range in memory
ChatStoreGap Interface A seq stretch the store does not have
ChatStoreGapFillInspection Interface Gap-fill progress
ChatStoreGapFillRun Interface A finished gap-fill run
ChatGapFillTrigger Type The moment that triggered a gap-fill
ChatStoreChangeLogInspection Interface The change watermark and catch-up progress
ChatStoreCatchUpRun Interface The last catch-up
ChatStoreSendInspection Interface One local message
ChatStorePatchInspection Interface One change in flight
ChatStoreLocalSegmentInspection Interface The local segment
ChatStoreGlobalInspection Interface The global inspection snapshot: conversations, storage, realtime signals
ChatStoreStorageInspection Interface Local storage
ChatStoreWriteError Interface The last failed write
ChatStoreRealtimeInspection Interface Realtime signals
ChatStoreSignal Interface A realtime signal the gap-fill scheduler got
ChatStoreInspectRecord Type One entry of the event stream
ChatStoreSnapshotArea Type Which part of a snapshot a snapshot record says changed
ChatStoreEventSource Type Who sent a dispatch
ChatStoreInspectListener Type The event stream's callback
ChatStoreStorageEstimate Interface Roughly how much local storage is used