仓库
createChatStore、ChatStore、会话快照 ChatConversationSnapshot 和请求结果缓存 createChatRequestCache。
仓库
@openmaxai/chat-store 根入口里关于仓库本体的导出。状态、在宿主里怎么接和全部导出的索引见概览。
createChatStore
function createChatStore(options: ChatStoreOptions = {}): ChatStore;
建一个消息仓库。每次调用得到一个独立的仓库,仓库之间不共享数据。数据只经 dispatch 写进来;每个会话最多保留 500 条已加载的消息(不开放配置),超出时卸掉离视图最远的那一端。本机数据放在哪、是否加密由 options.localData 指定,见 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>;
}
| 方法 | 说明 |
|---|---|
dispatch(event) |
唯一写入口。同步生效;改到了数据时通知这个会话的订阅者一次,什么都没改时不通知。收到不认识的事件类型(以及没带 client_msg_id 的 sendStarted、不认识的 outcome)时抛 TypeError,什么都不改。 |
subscribe(conversationId, listener) |
订阅一个会话的变化,返回取消订阅的函数,重复调用无害。回调里增删订阅不影响这一次通知谁。 |
getSnapshot(conversationId) |
一个会话此刻的数据。仓库里没有这个会话时返回一个共用的空快照。快照和里面的消息(连同消息里的数组、对象)都是冻结的:写进仓库的消息对象会被冻结,交出去以后不要再改它。 |
openLocalData(userId) |
打开 userId 在本机的数据。这台设备上次打开本机数据的是另一个用户时,先删掉那个用户的本机数据(消息、水位、请求结果),再打开当前用户的。用 createIndexedDbStorage() 时「上次的用户」跨页面刷新记着;用别的存储时只记本页里上次打开的用户。打开之后,经 dispatch 写进来的服务端消息和水位也写进本机,见下文写进本机。 |
openLocalData(userId, { readOnly: true }) |
只读打开,给离线时只看本机已有数据用:不删上一个用户的数据;这份数据用不了时以 LocalDataUnavailable 拒绝(原因见那一节),库原样留着;打开之后什么都不往本机写(消息、水位、本机段记录),换入的区间也不记成已落盘(之后可写打开时整段重写)。用 createIndexedDbStorage() 时打开路径上也不写,见那一节「只读打开」。 |
closeLocalData() |
关掉本机数据:关存储的连接、放单标签页锁、关跨标签页通道、不再接「别的标签页清掉了」,不删数据,可等待完成,可以重复调;之前排着的本机读写照做,之后排的不做;之后与没打开过一样(不读也不写本机),再 openLocalData 同一个用户时数据还在,接到最新时整段重写。不改设备上记的「上一个用户」,之后的 clearLocalData() 照样删他的数据。createChatStore 建的仓库都有它;接口上是可选的,自己实现 ChatStore 时可以不给,调用方先判有没有。 |
clearLocalData() |
删掉当前用户在本机的消息、水位和请求结果,然后关闭本机数据,可等待完成。退出登录时、收到无法恢复的 401 时都调用它。设备 id 和草稿不在仓库里,clearLocalData() 不碰:草稿由宿主自己删,设备 id 保留。还没打开过时,删掉这台设备上次打开本机数据的那个用户的。 |
clearConversation(conversationId) |
清掉一个会话在这台设备上的消息,退群、群被解散、被移出之后调用,可等待完成。内存里这个会话的区间、水位、本端消息和在途改动都丢掉,快照回到没加载过(之前有数据时订阅者收到一次 window);本机数据打开着(或正在打开)时,排在已经排着的本机写入后面,删掉这个会话本机的消息、水位和本机段记录。别的会话不动。清之前开始的取数在清之后才回来时不写进来:取数协调、补洞调度读本机读出的一窗、为换入一窗发的请求取回的一窗都丢掉;清之后才到的推送、改动对它就像对没加载过的会话一样(不建区间、不写本机)。用 createIndexedDbStorage 而本页没拿到单标签页锁(存储退回了内存)时,本机那份在拿着锁的那个标签页:清理经跨标签页通道送过去,由它删本机那份、丢它内存里那份(见那一节「别的标签页清掉的会话」);这时返回的 Promise 在清理记进设备库的待办之后落定,不等那一页删完。清之后再打开照常取数、照常写本机。本机那份删失败时以存储的错误拒绝(内存已经清掉)。按 id 取回、存在请求结果缓存里的单条消息不在仓库里,用缓存的 remove 删。 |
openLocalData、closeLocalData 和 clearLocalData 不等待地连着调用时按调用顺序生效;上一个失败不挡住下一个。
写进本机
本机数据打开着时,仓库把写进来的服务端消息和水位排队写进 ChatStorage,写失败不影响内存里的数据;一次写失败之后,那时已经排着的写入作废,下一次写入整段重写:
- 每个会话存一段连续的消息。 区间接到最新(或补到一半)时整段写下,之后区间的变化(接在前后、原地替换)逐次写;跳到没接到最新的一窗时不写,直到再接到最新。和本机已有的那一段相接就并起来,不相接(离开太久、补洞换入了最新一窗)就换成新的一段。
- 只写服务端那一版。 本端的消息(发送中、失败、被拦)不写;有在途改动的消息写服务端给的那一版。
messageDeleted删掉本机那条。 - 本机那份旧了就作废。 表态、对已有消息的编辑改到的那条不在内存里(会话关着、在卸掉的一端),或区间没在往本机写时,本机那一段作废,之后打开、读回都从后端取。编辑只在那条落在这一段里时才算;比水位新的推送是新消息,不算。
- 只写进换入区间时那个用户的本机。 换成另一个用户之后(
clearLocalData后再openLocalData另一个用户,或直接openLocalData另一个用户),之前换入内存的区间不写进本机,直到再换入一窗;打开本机数据之前换入的区间也一样。取数协调和补洞调度为换入一窗发请求之后才换的用户,取回的这一窗也不写;你自己dispatch的windowLoaded不受这一条保护,换用户之前发出的请求,回来后要由你自己丢掉。 - 这一段的范围记在一条请求结果里,键以
@openmaxai/chat-store/segment/开头,你自己的请求结果别用这个前缀。本机没有这个会话的水位时(被配额淘汰过)不认这条记录。这一段的改动水位也记在这条记录里,和范围同一次写下:这一段作废、换成新的一段、被淘汰时,改动水位跟着没了或换掉;和本机已有的一段并起来时取两者中小的。 - 关着、断线期间的改动由补洞调度补回。 网页关着或断线期间别人对已有消息做的编辑、撤回、删除、表态和卡片落定,不在补洞取回的新消息里。读接口有改动日志时,重新打开会话先画本机那一段(这时还是旧的那份),补完新消息后,补洞调度从这一段记着的改动水位往后取改动日志,把改到的消息按 id 取回、写进内存和本机,之后才推进改动水位,见补洞调度 · 补改动。离开太久、改动日志已经清理掉时,这一段作废、换入最新一窗。改动日志上线之前存下的、没有改动水位的一段不用,改取最新一窗。会话开着时这些改动由实时推送带到。
- 读回。 取数协调打开会话时先画这一段最新的一页、再从它的末尾补洞;卸掉的一端没有游标时先从这一段读回。读的期间这一段作废了(见上)、删了消息、或换了用户时,读出的不用,改从后端取。
ChatStoreOptions
interface ChatStoreOptions {
localData?: ChatLocalDataOptions;
}
createChatStore 的参数,都可以不给。
| 字段 | 说明 |
|---|---|
localData |
本机数据放在哪、是否加密,见 ChatLocalDataOptions。不给时用内存存储、不加密。 |
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;
}
没有变化时 getSnapshot 返回同一个对象;某条消息没变时它在 messages 里也是同一个对象。
| 字段 | 说明 |
|---|---|
messages |
已加载区间,按 seq 升序,seq 相同时按 id,最多 500 条。本端的消息(不计入 500 条)也在这里:失败、被拦的插在它们所在的位置,发送中和已确认还没对上的排在最后(区间没接到最新、hasNewer 为 true 时不显示:最新那条之后不在这一窗里),见 ChatStoreSendSettledEvent。 |
hasOlder |
区间之前还有更早的消息。 |
olderCursor |
往更早翻的游标;卸掉更早一端后没有,只能按 seq 取。 |
hasNewer |
区间没接到最新:围着某条取的一窗、新端被卸掉了,最新一窗的末尾低于水位(迟到了,或水位那条被删掉了),或从水位补到一半(接上的一批服务端说后面还有;这时区间末尾就是水位,补洞从水位接着取)。 |
newerCursor |
往更新翻的游标;卸掉新端后没有,按 seq 从区间最新那条往后取。 |
watermark |
水位:已经连续拿到的最大 seq,补洞从这里往后取。没接到过最新时没有。卸掉消息不影响它。 |
newerPending |
仓库知道有更新的消息没在区间里:见过比水位新、但没能接进来的推送(从水位补洞),或区间被告知到了最新、末尾却低于水位(这时 hasNewer 同时为 true,从区间末尾按 seq 往后取)。 |
createChatRequestCache
function createChatRequestCache(): ChatRequestCache;
建一个请求结果缓存(消息以外的请求结果:成员资料、通讯录搜索、会话列表等),每个宿主(每个登录用户)一份。按键存请求的结果,同一个键在途时只发一次请求。它不发请求(取数函数由调用方给)、不读时间,失效后不自己重取:相关事件到达时由调用方调 invalidate,订阅者收到通知后自己再 load。失败和成功一样缓存:取失败后不算失效,再 load 直接以同一个原因 reject,所以收到失败的通知再 load 不会变成重试循环;要重试(用户点重试、过一会儿再试)由调用方先 invalidate 再 load,退避也由调用方定。
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;
}
| 方法 | 说明 |
|---|---|
get(key) |
一个键此刻的结果。没取过时返回一个共用的 idle 结果;没有变化时返回同一个对象。 |
load(key, loader) |
有值且没失效时直接给缓存的值,不调 loader;这个键正在取时等那一次,不再调 loader;其他情况调 loader 取一次。失败时 reject(loader 同步抛错也一样),结果记成 error(留着上一次的值);之后没失效时再 load 直接以同一个原因 reject、不调 loader。失效之前发出的请求在失效之后才回来:值照样记下,但仍算失效;已经有失效之后发出的请求时,它的结果不再写进来。 |
set(key, value) |
直接写一个键的值(比如写操作的响应里已经带着新值),算没失效。在途的那次请求的结果不再写进来。 |
invalidate(prefix) |
让以 prefix 开头的键(含它本身)失效,空数组即全部。在途的请求回来后也算失效。不重取。 |
subscribe(key, listener) |
订阅一个键的结果变化,返回取消订阅的函数,重复调用无害。回调里增删订阅不影响这一次通知谁。 |
remove(prefix) |
删掉以 prefix 开头的键(含它本身)的结果,比如退群之后删掉那个会话按 id 取回的单条消息(键 ["@openmaxai/chat-store", "message", conversationId] 开头)。在途请求的结果不再写进来;订阅保留,有结果的键的订阅者各收到一次通知。 |
clear() |
清掉全部结果(退出登录时)。在途请求的结果不再写进来;订阅保留,有结果的键的订阅者各收到一次通知。 |
ChatRequestEntry
interface ChatRequestEntry<T = unknown> {
readonly status: "idle" | "loading" | "success" | "error";
readonly value: T | undefined;
readonly error: unknown;
readonly stale: boolean;
readonly fetching: boolean;
}
| 字段 | 说明 |
|---|---|
status |
idle:没取过;loading:第一次取,还没有值;success:有值;error:最近一次取失败了。 |
value |
最近一次取到的值;取失败后仍留着上一次的值。 |
error |
最近一次取失败的原因;之后取成功了就没有。 |
stale |
失效了,下一次 load 会重新取。失效后到重新取到之前仍给旧值。取失败后不算失效(失败也缓存)。 |
fetching |
正在取(第一次取,或失效后重新取)。 |
ChatRequestKey
type ChatRequestKey = readonly (string | number | boolean | null)[];
请求的键,按元素逐个比较("1" 和 1 不同,NaN 和 null 不同,-0 和 0 相同)。前缀相同的键可以一起失效:["members", orgId] 是 ["members", orgId, memberId] 的前缀。
ChatRequestListener
type ChatRequestListener = () => void;
一个键的结果变了时的回调,见 subscribe。新结果用 get 读。
createChatMemberStore
function createChatMemberStore(): ChatMemberStore;
建一个成员仓库,每个宿主(每个登录用户)一份:参与者表(跨会话按 id 一份)、每个会话的成员关系(会话内角色、加入时间),以及当前用户和他的组织角色。和请求结果缓存一样只在内存:它不拿本机存储,也不碰任何浏览器存储,每次打开会话取一次成员表交给它。成员没有改动日志,离线期间的角色变化补不回来,落本机反而会显示过期的角色。
它不发请求、不读时间,数据只经 dispatch 写进来。@openmaxai/chat-sdk 的宿主各建一份:宿主上同步的 identity.getMember、listMembers 从它读,适配器取回的成员表(连同会话内角色、加入时间)经 membersLoaded 写进来,当前用户取回后经 currentUserLoaded 交进来(带适配器 me() 给的组织角色);useChatSdkPermissions 从它读当前用户的角色。@openmaxai/chat 的组件还不读它。
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;
}
| 方法 | 说明 |
|---|---|
dispatch(event) |
唯一写入口,收 ChatMemberStoreEvent。同步生效;改到了数据时,受影响的每个会话的订阅者各收到一次通知,什么都没改时不通知。不认识的事件类型(以及同一个 id 出现两次、不认识的 kind、participant.id 和 memberId 不同)抛 TypeError,什么都不改。 |
getMembers(conversationId) |
一个会话的成员关系,按 membersLoaded 的顺序,之后进来的接在最后。成员表没取过时返回 undefined,取过而没有人时是空数组。数组和每一行都是冻结的,没有变化时返回同一个对象,没变的行也是同一个对象。 |
getParticipant(id) |
一个参与者,跨会话按 id 找(历史消息的发送者不在当前成员表里也取得到);不认识时返回 undefined。冻结的,没有变化时返回同一个对象。 |
getMyRoles(conversationId) |
当前用户在这个会话里的会话内角色和组织角色,见 ChatMyRoles。冻结的,没有变化时返回同一个对象。 |
subscribe(conversationId, listener) |
订阅一个会话:它的 getMembers、getMyRoles、或它的某个成员的 getParticipant 变了时收到通知,每次 dispatch 至多一次。返回取消订阅的函数,重复调用无害。回调里增删订阅不影响这一次通知谁。 |
clear() |
清掉全部数据(退出登录、换组织时)。订阅保留,每个订阅着、之前有数据的会话收到一次通知。 |
快照式的读接口在没有变化时返回同一个对象,所以 React 里可以直接用 useSyncExternalStore 接 subscribe 和三个读接口。
ChatMemberStoreEvent
type ChatMemberStoreEvent =
| ChatMemberStoreMembersLoadedEvent
| ChatMemberStoreMemberUpsertedEvent
| ChatMemberStoreMemberRemovedEvent
| ChatMemberStoreCurrentUserLoadedEvent;
成员仓库写入口收的事件,下面四种的联合。
ChatMemberStoreMembersLoadedEvent
interface ChatMemberStoreMembersLoadedEvent {
type: "membersLoaded";
conversationId: string;
members: readonly ChatLoadedMember[];
}
取到一个会话的成员表,整表换入:表里没有的人从这个会话去掉(参与者本身留着,历史消息还要显示他的名字),顺序照这一表。参与者按 id 写进参与者表,其他会话里看到的同一个人也跟着变。内容没变时什么都不改、不通知。同一个 id 出现两次、或 kind 不认识时抛 TypeError,什么都不改。
ChatMemberStoreMemberUpsertedEvent
interface ChatMemberStoreMemberUpsertedEvent {
type: "memberUpserted";
conversationId: string;
memberId: string;
role: ChatConversationRole;
joinedAt?: string;
participant?: ChatStoreParticipant;
}
一个人进了会话,或他的会话内角色变了。
- 这个会话的成员表取过:按
memberId改那一行(不给joinedAt时留着原来的,位置不动),没有就接到最后。 - 没取过:不为它建成员表(一行不是整表,
getMembers仍返回undefined),只写参与者。 - 带了
participant时按id写进参与者表;不带时只改成员关系(比如换群主的信号只给 id)。
participant.id 和 memberId 不同、或 kind 不认识时抛 TypeError,什么都不改。
ChatMemberStoreMemberRemovedEvent
interface ChatMemberStoreMemberRemovedEvent {
type: "memberRemoved";
conversationId: string;
memberId: string;
}
一个人离开了会话(被移除、自己退出):从这个会话的成员表去掉,参与者留着。成员表没取过、或他本来就不在里面时什么都不做。
ChatMemberStoreCurrentUserLoadedEvent
interface ChatMemberStoreCurrentUserLoadedEvent {
type: "currentUserLoaded";
userId?: string;
orgRole?: ChatOrgRole;
}
当前用户是谁、组织角色是什么。登录后、换组织后由宿主交进来,组织角色变了再交一次;两项都和上一次相同时什么都不做。变了时每个订阅着的会话各收到一次通知(组织角色在每个会话的 getMyRoles 里都有)。会话内角色不在这里:它从当前用户在各会话成员表里的那一行读,所以只有一份,换群主、被移出时跟着成员表变。
ChatMemberStoreListener
type ChatMemberStoreListener = () => void;
一个会话的成员数据变了时的回调,见 subscribe。新数据用 getMembers、getParticipant、getMyRoles 读。
ChatStoreParticipant
interface ChatStoreParticipant {
readonly id: string;
readonly displayName: string;
readonly avatarUrl?: string;
readonly kind: ChatParticipantKind;
}
一个参与者(人、Agent 或系统成员),跨会话按 id 只有一份。displayName 的取名兜底由写入方做好;没有头像时不给 avatarUrl。仓库只留这四个字段,交出去的是冻结的副本。
ChatParticipantKind
type ChatParticipantKind =
| "human"
| "agent"
| "system";
参与者的类别,取值和 @openmaxai/chat/host 契约里的成员类别相同。没有 bot:内部、外部的 Agent 都是 agent;system 是调度中心这类系统成员。
ChatMembership
interface ChatMembership {
readonly memberId: string;
readonly role: ChatConversationRole;
readonly joinedAt?: string;
}
一个人在一个会话里的成员关系:只有会话内角色和加入时间(原样的 ISO 8601 字符串)。「我」的静音、置顶不在这里,它们属于会话列表那一行。
ChatConversationRole
type ChatConversationRole =
| "OWNER"
| "ADMIN"
| "MEMBER"
| "PUBLISHER"
| "SUBSCRIBER"
| "UNSPECIFIED";
会话内角色,取值照成员接口每行的 role(大写,UNSPECIFIED 是后端没给角色)。后端目前不推普通角色变更,只推换群主。
ChatOrgRole
type ChatOrgRole =
| "org-owner"
| "org-admin"
| "org-member"
| (string & {});
当前用户在组织里的角色 slug。内置角色有四种:org-owner、org-admin、org-member,外加给系统成员(调度中心这类)用的 org-system;系统成员不是登录用户,当前用户不会是它,所以类型里不单列。组织还可能有自定义角色,所以也收别的字符串。
ChatMyRoles
interface ChatMyRoles {
readonly conversationRole: ChatConversationRole | undefined;
readonly orgRole: ChatOrgRole | undefined;
}
| 字段 | 说明 |
|---|---|
conversationRole |
会话内角色:按当前用户 id 在这个会话的成员关系里找。成员表没取过、当前用户不知道、不是成员时没有。 |
orgRole |
组织角色,来自 currentUserLoaded;不知道时没有。 |
按钮可点、可见都由它定:判断在 @openmaxai/chat/host 的 can() 里做(@openmaxai/chat-sdk 的 useChatSdkPermissions 读它交给 can()),这里只给数据。注意 conversationRole 没有时分不清「没取过」「不知道我是谁」「不是成员」,can() 把它当「不知道」,不当「没权限」。
ChatLoadedMember
interface ChatLoadedMember {
participant: ChatStoreParticipant;
role: ChatConversationRole;
joinedAt?: string;
}
membersLoaded 里的一行:参与者和他在这个会话里的会话内角色、加入时间。
createChatConversationStore
function createChatConversationStore<C extends ChatStoreConversationRow>(options: ChatConversationStoreOptions<C>): ChatConversationStore<C>;
建一个会话仓库,每个宿主(每个登录用户)一份:会话列表(分页、游标、重取)、按 id 存的会话行,以及取它们的那部分。和成员仓库一样只在内存:会话列表没有改动日志,离线期间的置顶、隐藏、未读变化补不回来,落本机反而会先画出过期的列表。
- 行内容按 id 一份。 列表、按 id 读(
getConversation)、未读(getUnread)读的是同一行。列表顺序只由取到的页决定:按 id 写入和补丁都不改顺序,也不把行加进列表或移出列表。 - 什么时候取列表,只认这几种: 还没有数据(第一个读者到来,
openList);被失效(invalidate:写操作之后、信号合并之后,以及你在重连、页面从隐藏变可见时交进来的失效);读者显式refetch/retryList。读者挂载本身不触发重取:已有数据、没失效过时,新读者直接读现有的。失效时有读者就重取,没有就记下、等下一个读者;正有列表取数(第一页、重取或翻页)在途时不另发请求,等它落地后有读者就再重取一次。所以光靠失效,网络上不会同时有两个列表请求。 - 「在列表里」和「有这一行」分开记。 行缓存留到
clear()(按 id 读、顶部栏用得上),列表成员以最近一次取到的页为准,读取状态的listed读它。不在当前列表里的会话,读者到来时按 id 再取一次,不因为行缓存还在就当作已列出。 - 重取按已取到的页数。 从第一页起依次取同样多页,全部到了才一次换入;中途失败什么都不换。
- 没变的行沿用原对象。 取回的行与仓库里那行结构相等时沿用原对象,列表的顺序和行都没变时列表数组也沿用,读的一侧据此不重渲染。
- 不读时间的部分和读时间的部分分开。 合并窗口和重试等待用参数里的计时器(
timers),测试交假时钟进来。
@openmaxai/chat-sdk 还没接它。
conversation-store-wiring.ts
import { createChatConversationStore } from "@openmaxai/chat-store";
const conversations = createChatConversationStore({
source: host.conversations,
// 凭据失效不重试,其余失败最多再试 3 次,指数退避。
retry: (n, error) => (isUnauthorized(error) || n > 3 ? false : Math.min(1000 * 2 ** (n - 1), 30_000)),
});
// 新消息、已读等信号:一秒内合并成一次重取。
host.signals.subscribe(() => conversations.invalidate({ coalesce: true }));
// 置顶成功:先改那一行,再立即重取(顺序按服务端的来)。
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;
}
| 方法 | 说明 |
|---|---|
dispatch(event) |
唯一写入口,收 ChatConversationStoreEvent。同步生效,改到了数据才通知。不认识的事件类型抛 TypeError。 |
getList()、subscribeList(listener) |
会话列表的读取状态(ChatConversationListState)和订阅。读取状态没有变化时是同一个对象。 |
openList() |
来了一个列表的读者,返回它离开时调的函数。还没有数据、或上次第一页失败了时取第一页;失效过且已有数据时重取;都不是时不取。 |
loadMore() |
取下一页接到后面。没有下一页时什么都不做;正在取(第一页、翻页、重取)时返回在途的那一次。失败时 reject,已有数据不动。 |
refetch() |
现在就重取(还没取过时取第一页)。在途的重取、翻页作废,它们的 Promise 照样 resolve。失败时 reject。 |
invalidate(options?) |
列表失效。有读者时重取,coalesce: true 时等合并窗口(默认 1000 毫秒)结束再重取,窗口内再叫几次都只重取一次;窗口内来了一次不带 coalesce 的失效,立即重取并取消这个窗口。没有读者时只记下。正有列表取数在途时不作废它,等它落地(或失败)后再重取一次。重连、页面从隐藏变可见时由你各叫一次。 |
retryList() |
再做一次最近失败的那一步(第一页、翻页或重取);没有失败、或正在取时什么都不做。 |
ensureList() |
第一页已取到时立即 resolve;否则取第一页(在取就等那一次)。给「按 id 打开前先看列表里有没有」用。 |
getConversation(id)、subscribeConversation(id, listener) |
一个会话的读取状态(ChatConversationReadState)和订阅;这个会话的行或未读变了时通知。 |
openConversation(id) |
来了一个读这个会话的读者,返回它离开时调的函数。不在当前默认列表里、读接口有 loadConversation 时:列表第一页在取就先等它,仍不在列表里就按 id 取一次,取到后写入(不进列表),取回 undefined 时连留着的旧行一起删掉。行缓存还在不算在列表里:重取把它去掉之后,读者会再按 id 取一次(开着的读者随即取)。按 id 取到过、conversationUpserted 写过之后,在某一次第一页 / 重取把它从列表里去掉之前不再取(本来就不在列表里的,列表重取去不掉它,也就不让它再取);被明确移除之后(移除时有没有读者都一样),在某一次第一页 / 重取把它带回列表之前不再取。取回 undefined 只记到读者都离开为止,下一个读者再真去取(可能刚建出来)。读接口没有 loadConversation 时只能等列表:第一页还没取就取第一页。 |
retryConversation(id) |
按 id 取失败了、或取回 undefined 时再取一次;其他情况什么都不做。 |
findConversation(id) |
仓库里的这个会话,不发请求。 |
getUnread(id) |
一个会话的未读(ChatUnreadState),随 subscribeConversation 通知。 |
clear() |
清掉全部数据和取数状态(退出登录、换组织时)。在途取数的结果不再写进来,合并窗口和等着的重试取消。订阅和读者保留:之后有列表读者就重取第一页,有会话读者就照 openConversation 再取。 |
end() |
结束这个仓库(它服务的作用域结束了,@openmaxai/chat-sdk 的宿主在作用域结束时调它):清法同 clear(),但不发请求,之后也不再发;在途取数的结果不再写进来,订阅者收到一次通知。之后列表一直是空的「加载中」,读取、失效、事件都不再让它取数。 |
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;
};
}
| 字段 | 说明 |
|---|---|
source |
读接口,见 ChatConversationSource。 |
retry |
一次取数失败后要不要再试:返回等多少毫秒再试,false 表示不再试、把这次失败交出去。failureCount 是这一次取数到现在失败了几次(第一次失败时是 1)。列表的每一次取数和按 id 取都按它。不给时不重试。等待期间这次取数被顶替、或仓库被 clear() 时不再试。 |
coalesceMs |
合并窗口,毫秒,默认 1000。 |
timers |
计时器,合并窗口和重试等待用;不给时用全局的 setTimeout、clearTimeout。 |
ChatConversationSource
interface ChatConversationSource<C extends ChatStoreConversationRow> {
list(input: {
cursor?: string;
}): Promise<ChatConversationSourcePage<C>>;
loadConversation?(conversationId: string): Promise<C | undefined>;
}
会话仓库用的读接口,形状和宿主的 conversations 相同,可以直接把它交进来。list 只带 cursor:取的是默认列表(不含已隐藏);搜索、已隐藏那一支不进会话仓库。loadConversation 可选,没有时只读列表里有的。
ChatConversationSourcePage
interface ChatConversationSourcePage<C extends ChatStoreConversationRow> {
conversations: readonly C[];
nextCursor?: string;
}
会话列表的一页,同宿主 conversations.list 的返回值。nextCursor 不给或为空串表示到底了。
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;
}
仓库读写的会话行至少要有的几格,字段名照宿主的 ChatConversation,可以直接把那一行交进来;别的字段原样存、原样给。done 是产品里的「隐藏」。
ChatUnreadMention
type ChatUnreadMention =
| "none"
| "direct"
| "all";
未读 @ 标记:direct 有人直接 @ 我,all 有 @所有人,none 没有。
ChatConversationStoreEvent
type ChatConversationStoreEvent<C extends ChatStoreConversationRow> =
| {
type: "conversationUpserted";
conversation: C;
}
| {
type: "conversationPatched";
conversationId: string;
patch: ChatConversationPatch;
}
| {
type: "conversationRemoved";
conversationId: string;
};
会话仓库写入口收的事件:
conversationUpserted:取到一个会话的新内容(按 id 打开时取到的、写操作的响应里带回的),按 id 整行换入。在列表里时原地替换,列表顺序不变;不在时只能按 id 读到,不加进列表。内容没变时沿用原对象、不通知。conversationPatched:改一个会话的当前用户态,见ChatConversationPatch。只改那一行的字段,列表的顺序和成员都不变:隐藏了的仍在列表里、置顶了的不挪到前面,等下一次重取按服务端的来。在途的取数在补丁之后才回来时,回来的行上补上这次补丁(这一行当时还不在仓库里也一样);没有在途取数、仓库里又没有这个会话,或值没变时什么都不做。conversationRemoved:收到明确的「被移出 / 删除」。这一行从列表里去掉,行本身也删掉,按 id 读到「没有」、不再按 id 去取;之后的重取又带回它时照常回来。在途的取数在移除之后才回来时,不再把这一行写回来。
ChatConversationPatch
interface ChatConversationPatch {
pinned?: boolean;
hidden?: boolean;
muted?: boolean;
unreadCount?: number;
unreadMention?: ChatUnreadMention;
lastReadSeq?: number;
}
对一个会话的当前用户态的改动,只改给了的那几格:pinned 写 pinned,hidden 写 done,muted 写 muted,unreadCount 写 unread_count,unreadMention 写 unread_mention,lastReadSeq 写 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;
}
| 字段 | 说明 |
|---|---|
conversations |
已取到的各页按顺序接起来;同一个 id 只出现一次(位置按先出现的,内容按后来的)。 |
status |
loading 还没有数据、正在取(含第一页失败后正在重试);ready 有数据;error 第一页取失败了,没有数据。 |
error |
最近一次失败的原因,读接口 reject 的原样值;之后取成功了就没有。已有数据时取数失败,数据保留,status 仍是 ready。 |
isFetching |
正在取(第一页、翻页、重取都算)。 |
hasMore |
还有下一页。 |
ChatConversationReadState
interface ChatConversationReadState<C extends ChatStoreConversationRow> {
readonly conversation: C | undefined;
readonly listed: boolean;
readonly status: ChatReadStatus;
readonly error: unknown;
readonly isFetching: boolean;
}
一个会话的读取状态。listed 是它此刻在不在默认列表里(最近一次取到的各页里有它、之后没被移除);有 conversation 不代表 listed。status:仓库里有这一行就是 ready;没有时,读接口有 loadConversation 且还没取过(或正在取)是 loading,取失败是 error(error 是原样值),取回 undefined(不存在、看不到)或被移除是 ready、没有 conversation。读接口没有 loadConversation 时跟着列表走:第一页到之前是 loading,第一页失败是 error(error 是列表那次的原因),到了之后不在里面是 ready、没有 conversation。isFetching 是正在按 id 取。
ChatUnreadState
interface ChatUnreadState {
readonly count: number;
readonly mention: ChatUnreadMention;
readonly lastReadSeq?: number;
}
一个会话的未读:count 来自 unread_count,mention 来自 unread_mention(不给时为 none),lastReadSeq 来自 last_read_seq。仓库里没有这个会话时 count 为 0、mention 为 none。没有变化时是同一个对象。
createChatReadCursorStore
function createChatReadCursorStore(): ChatReadCursorStore;
建一个已读游标块,每个宿主一份、只在内存:每个会话自己的已读位置(服务端确认过的、在途的那一笔)和回执用的别人的游标(每人读到 / 送达到哪条、会话级送达水位、成员数、快照是否截断、回执可不可用)。不发请求、不读时间、不写存储,也不知道当前用户是谁:「自己」那一行由取数层(createChatReadCursorLoader)翻译成 ownConfirmed。所有游标按最大值合并,ack 不小于 read。
只有 tracked、receiptsLoaded、receiptsFailed、ownReportStarted 四种事件会在没有记录时建一条;其余(memberRead、delivered、ownConfirmed、ownReportSettled)只合并进已有记录,没有记录就丢掉 ⇒ 实时连接对所有会话都送的 read 信号不会给没打开过的会话建记录。回执快照取失败时,没有记录或还是 pending 的记为 unavailable,已经 available 的保持可用;unavailable 的不因之后的信号变成可用,重取快照成功才变。
@openmaxai/chat-sdk 的宿主各建一份,作用域结束(换组织、被移出、退出登录、凭据失效)时 clear();新消息区的回执经 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;
}
| 方法 | 说明 |
|---|---|
dispatch(event) |
唯一写入口,收 ChatReadCursorEvent。同步生效;改到了才通知这个会话的订阅者一次。不认识的事件类型抛 TypeError,什么都不改。 |
getState(conversationId) |
这个会话的 ChatReadCursorState,冻结的;没有变化时同一个对象,只改了自己那半时 receipts 仍是同一个对象(反之亦然)。没有记录时是所有会话共用的空状态(status 为 pending、游标全 0)。 |
has(conversationId) |
这个会话有没有记录。 |
subscribe(conversationId, listener) |
订阅一个会话,返回取消订阅的函数,重复调用无害。回调里增删订阅不影响这一次通知谁。 |
clear() |
清掉所有记录,代号加一;订阅保留,之前有记录的会话各收到一次通知。 |
epoch() |
代号,每次 clear() 加一。取数层发请求时记下,落定时代号变了就丢掉结果。 |
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;
};
}
一个会话的游标状态。own.confirmed 是服务端确认过的自己的已读位置(来自快照里自己那一行、自己那条 read 信号、上报成功),own.inFlight 是正在写的那一笔。receipts.byMember 含自己那一行,画回执时由调用方排除。
ChatMemberCursor
interface ChatMemberCursor {
read: number;
ack: number;
}
一个成员读到哪条 seq(含)、送达到哪条 seq(含),ack 不小于 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;
};
游标块写入口收的事件。
| 事件 | 没有记录时 | 有记录时 |
|---|---|---|
tracked |
建一条(pending,游标全 0) |
不变 |
receiptsLoaded |
建一条再合并 | 按最大值合并进 byMember;memberCount 取新旧最大值,truncated 取快照的;deliveredUntil 不动;status 变成 available |
receiptsFailed |
建一条 unavailable |
pending ⇒ unavailable;其余不变 |
memberRead / delivered |
丢掉 | 按最大值合并;status 不变 |
ownConfirmed |
丢掉 | own.confirmed 取最大值 |
ownReportStarted |
建一条再记在途 | seq 大于 max(confirmed, inFlight) 时记为 inFlight |
ownReportSettled |
丢掉 | 成功:confirmed 取最大值;inFlight 等于 seq 时清掉(成败都是) |
ChatReadCursorSnapshotShape
interface ChatReadCursorSnapshotShape {
cursors: readonly {
memberId: string;
readUntilSeq: number;
ackUntilSeq: number;
}[];
memberCount: number;
truncated: boolean;
}
一个会话的游标快照,与宿主 messaging.loadReadCursors 交回的 ChatReadCursorSnapshot 同形(仓库包不依赖 @openmaxai/chat,按结构自己声明)。
ChatReadCursorSignal
type ChatReadCursorSignal =
| {
kind: "read";
conversationId: string;
memberId: string;
readUntilSeq: number;
}
| {
kind: "delivery";
conversationId: string;
ackUntilSeq: number;
}
| {
kind: "reconnected";
}
| {
kind: "connected";
};
取数层认的三种实时信号,与宿主入站信号里的 read、delivery、reconnected 同形。
createChatReadCursorLoader
function createChatReadCursorLoader(options: ChatReadCursorLoaderOptions): ChatReadCursorLoader;
建一个已读游标的取数层,和游标块同一处建(每个宿主一份)。它把快照、实时信号和已读上报翻译成游标块的事件,吞掉所有 reject:
- 打开:
open计数从 0 到 1 时发tracked(不管有没有回执能力),有loadReadCursors时取一次快照:成功发receiptsLoaded,失败(任何原因,含回执关闭的 412)发receiptsFailed。返回关闭函数。有会话打开着时才订阅signals。 - 自己是谁:每次用到时调
currentUserId()。快照里或read信号里memberId是自己的那一行,照常进byMember,另发一个ownConfirmed;身份还没取回(空串)时不翻译。 - 信号:
read→memberRead(自己的另加ownConfirmed);delivery→delivered;reconnected与connected(第一次连上)→ 对打开着的会话各重取一次快照。其余种类忽略。 - 代号:每个请求发出时记下
store.epoch(),落定时代号变了就丢掉结果。 reportRead:观察中的会话不写;没有markReadUntil不写;seq不大于max(confirmed, inFlight)不写;每个会话同时只有一笔在途,其余只记排着的最大值,在途落定后(成功或失败)排着的值仍更大就再写一次;失败只回退在途、不重试那一笔。
ChatReadCursorLoader
interface ChatReadCursorLoader {
open(conversationId: string): () => void;
reportRead(conversationId: string, seq: number, options: {
observed: boolean;
}): void;
dispose(): void;
}
取数层:open 打开一个会话(计数),reportRead 写已读上报(从不 reject、不抛),dispose 退订信号、清掉打开计数与排着的上报(之后还能再 open)。
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;
};
}
取数层的端口。loadReadCursors 与 markReadUntil 都要是宿主已经套过凭据闩的那份(凭据失效由它们自己的闩处理,取数层不另判);markReadUntil 在 SDK 里接宿主的 conversations.markReadUntil(成功后会话列表失效那一层在宿主里)。signals 接宿主的 inboundDelivery,没有实时连接时不给,回执按打开时的快照静态画。
createChatAgentActivityStore
function createChatAgentActivityStore<S extends {
readonly id: string;
readonly at: number;
} = ChatAgentActivityStep, R extends string = ChatAgentActivityEndReason>(): ChatAgentActivityStore<S, R>;
本节到 ChatAgentActivitySummaryRef 都属 Agent 执行过程,只读进度(实验性 · 过渡),规划中的 Agent 运行能力落地时替换它。
建一个运行表,只在内存:一份 Agent 执行过程的「会话 → run」表(ChatAgentActivityRuns)加整表订阅。推进与扫描内部调 applyAgentActivityFrame 与 sweepAgentActivityRuns,表换了才通知。不读时钟、不建定时器、不发请求:时刻由调用方给,扫描的定时器也由调用方建(表里有 run 时才需要跑,size() 就是给它判的)。类型参数是步骤与结束原因,默认取本包的结构复本 ChatAgentActivityStep 与 ChatAgentActivityEndReason。
与已读游标块生命周期相同(读者订阅、作用域结束时 clear()),订阅粒度不同:已读游标块按会话订阅,运行表是整表订阅,读者收到通知后自己按会话取。今天 @openmaxai/chat-sdk 的宿主还没有建它;自己维护执行过程 store 的宿主可以调同一组纯函数。
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;
}
| 方法 | 说明 |
|---|---|
applyFrame(frame, now) |
推进一帧(内部调 applyAgentActivityFrame)。表换了才通知;重复、乱序、终态之后的非终态帧不换表、不通知。 |
sweep(now) |
扫失联与淘汰(内部调 sweepAgentActivityRuns)。表换了才通知。 |
getRuns(conversationId) |
某会话的 run(内部调 selectConversationAgentActivityRuns),按 startedAt 升序;两次通知之间回同一个数组,没有 run 时回同一个冻结的空数组。 |
size() |
表里 run 的总数,跨会话合计。 |
subscribe(listener) |
整表订阅,返回取消订阅的函数,重复调用无害。回调里增删订阅不影响这一次通知谁。 |
clear() |
清掉全部 run,清之前有 run 才通知一次;可重复调用,空表上什么都不做。清完照样能推进,停收由调用方管。 |
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>;
按一帧推进一份运行表,回新的那份;丢弃的帧回原来那份(引用不变,调用方据此判要不要通知)。规则:
- run 的键是 (会话, 发送者,
runId),见agentActivityRunKey; sequence不大于这个 run 上次的就丢(帧可重复、可乱序,服务端的判重只在副本内且会忘,去重在这里做);终态之后的非终态帧也丢(终态不回退),终态之后的终态帧照收;- 首帧
sequence > 1置joinedLate;跳号置gap,之后不清; - 步骤按 id 整条替换、按
at排序,只留最后AGENT_ACTIVITY_MAX_STEPS条;帧上没有步骤时沿用原来那个数组; execStartedAt一旦出现就保留;stepCount与sourceMessageId帧上缺省时沿用上一帧;其余字段以这一帧为准;- 来帧清
syncLost,now记成lastFrameAt; - 推进后 run 总数超过
AGENT_ACTIVITY_MAX_RUNS时按lastFrameAt淘汰最旧的。
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>;
扫失联与淘汰:非终态且 now - lastFrameAt > ttlMs ⇒ 置 syncLost(状态不变,不推断终态:终态帧可能丢,Agent 崩溃时服务端也不补终态帧);终态或失联、且闲置超过 AGENT_ACTIVITY_EVICT_AFTER_MS ⇒ 淘汰,会话没有 run 了那一格一并去掉。没有变化时回原来那份表;只有部分会话变了时,没变的会话那格不换。
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>[];
某会话的 run,按 startedAt 升序、冻结。那格 Map 没换就回同一个数组(可以直接当 useSyncExternalStore 的快照);没有 run 时回所有会话共用的同一个冻结空数组。
agentActivityRunKey
function agentActivityRunKey(conversationId: string, senderId: string, runId: string): string;
run 的键:会话、发送者、runId 用 | 连起来。runId 只在一个 Agent 内唯一,同一会话里两个 Agent 可以撞号,所以键里带发送者。
AGENT_ACTIVITY_MAX_STEPS
const AGENT_ACTIVITY_MAX_STEPS = 500;
每个 run 最多留的步骤条数,超出丢最早的。
AGENT_ACTIVITY_EVICT_AFTER_MS
const AGENT_ACTIVITY_EVICT_AFTER_MS = 10 * 60000;
终态或失联之后再闲置多久(毫秒,10 分钟)淘汰。
AGENT_ACTIVITY_MAX_RUNS
const AGENT_ACTIVITY_MAX_RUNS = 100;
一份表最多留的 run 数,跨会话合计;超出按 lastFrameAt 淘汰最旧的。
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;
}
解码、校验过的一帧。本包不解码:OpenMax 适配器在内部解码,自写的一方按这个形状交。steps 是本帧带来的增量步骤(按 id 整条替换);ttlMs 是这一帧之后多久没有新帧就算失联;startedAt 是等待计时起点,execStartedAt 是执行计时起点。
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;
}
归并出的一个 run。key 见 agentActivityRunKey;syncLost 是失联;firstSequence / lastSequence 是首帧与最后一帧的 sequence;joinedLate 是首帧 sequence > 1(刷新、中途打开、另一台设备);gap 是出现过跳号;lastFrameAt 是调用方给的最后一帧的本地时刻,失联与淘汰都按它算。
ChatAgentActivityRuns
type ChatAgentActivityRuns<Step extends {
readonly id: string;
readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> = ReadonlyMap<string, ReadonlyMap<string, ChatAgentActivityRun<Step, EndReason>>>;
一份运行表:会话 → (run 键 → run),收全部会话。每次变化换新 Map,没变的会话那格不换。
ChatAgentActivityState
type ChatAgentActivityState =
| "queued"
| "thinking"
| "tool"
| "done"
| "failed";
帧与 run 上的状态:queued 等待处理,thinking 与 tool 都是处理中,done 与 failed 是终态。
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;
};
解码后的一步(schema v3):工具步、思考步、提示步。本包只读 id 与 at,其余字段原样交给画块的那一层。
ChatAgentActivityEndReason
type ChatAgentActivityEndReason =
| "runtime_restarted"
| "interrupted"
| "no_reply";
失败的结束原因。
ChatAgentActivitySummary
type ChatAgentActivitySummary<Step extends {
readonly id: string;
readonly at: number;
} = ChatAgentActivityStep, EndReason extends string = ChatAgentActivityEndReason> =
| ChatAgentActivitySummaryFull<Step, EndReason>
| ChatAgentActivitySummaryRef;
消息上的中立运行字段(ChatMessage 的 agent_run_summary):适配层把后端的运行摘要解码成这个形状再交出(OpenMax 适配器在内部解码),画摘要条、判回复接管都只看它,不读后端原样的 agent_run。完整形态画摘要条,完整与引用形态都让同 run 的实时块让位;不填就没有摘要条。
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[];
}
中立运行字段的完整形态:一次运行结束后落在回复上的摘要(schema v3)。
ChatAgentActivitySummaryRef
interface ChatAgentActivitySummaryRef {
form: "ref";
runId: string;
}
中立运行字段的引用形态:同一 run 的后续回复,或解析不了但带合法 run 号的老插件回复。只用于接管判定,不画摘要条。
