@pmate/chat-sdk 0.13.0-profile.0 → 0.13.0-profile.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/lib/profile.d.ts +5 -2
- package/lib/profile.js +5 -2
- package/lib/runtime/profileChat.d.ts +121 -1
- package/lib/runtime/profileChat.js +126 -33
- package/lib/runtime/profileCommitQueue.d.ts +2 -1
- package/lib/runtime/profileCommitQueue.js +26 -7
- package/lib/runtime/profileCoordinator.d.ts +19 -19
- package/lib/runtime/profileCoordinator.js +127 -94
- package/lib/runtime/profileDatabase.d.ts +7 -7
- package/lib/runtime/profileDatabase.js +57 -42
- package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
- package/lib/runtime/profileGenerationBuilder.js +60 -26
- package/lib/runtime/profileInboxFeed.d.ts +1 -0
- package/lib/runtime/profileInboxFeed.js +12 -2
- package/lib/runtime/profileLegacyInbox.d.ts +8 -0
- package/lib/runtime/profileLegacyInbox.js +114 -0
- package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
- package/lib/runtime/profileLegacyOutbox.js +106 -0
- package/lib/runtime/profileLegacyReading.d.ts +7 -0
- package/lib/runtime/profileLegacyReading.js +110 -0
- package/lib/runtime/profileMemoryStore.d.ts +24 -2
- package/lib/runtime/profileMemoryStore.js +146 -12
- package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
- package/lib/runtime/profileOutboxDispatcher.js +41 -5
- package/lib/runtime/profileOwner.d.ts +11 -6
- package/lib/runtime/profileOwner.js +71 -46
- package/lib/runtime/profileProjection.d.ts +54 -5
- package/lib/runtime/profileProjection.js +336 -51
- package/lib/runtime/profileReadingIndex.d.ts +1 -0
- package/lib/runtime/profileReadingIndex.js +17 -1
- package/lib/runtime/profileStoreTypes.d.ts +15 -9
- package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
- package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +55 -102
- package/lib/runtime/profileWorkerHost.d.ts +4 -6
- package/lib/runtime/profileWorkerHost.js +58 -21
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -373,3 +373,29 @@ Empty ten-second checks and duplicate notifications do not open a projection
|
|
|
373
373
|
write transaction. Received receipt batches insert only new keys in one bulk
|
|
374
374
|
write. Own viewport read observations are coalesced over 100ms before their
|
|
375
375
|
pending intents become durable; callers resolve after commit.
|
|
376
|
+
|
|
377
|
+
## Profile Worker runtime (0.13 preview)
|
|
378
|
+
|
|
379
|
+
### Background
|
|
380
|
+
|
|
381
|
+
The Profile runtime prepares the full retained Inbox range once and exposes message windows from memory. Merry runs one application document: creating a distributed writer, lease and replica for every page is unnecessary and can block a healthy UI after a backgrounded WebView stops responding.
|
|
382
|
+
|
|
383
|
+
`ProfileCoordinator` now creates one Dedicated Worker for the active Profile and receives committed deltas over that Worker's ordered message port. `start()` is shared, `memory` retains its identity across Worker restarts, and `submit`, `synchronize`, `waitForCommand` and `voiceAttachment` delegate to the direct connection. Consumers must remove calls to the former `replica.repair()`; normal synchronization publishes its committed changes before its reply. `ProfileWorkerClient` replaces the former distributed `ProfileReplica` export.
|
|
384
|
+
|
|
385
|
+
There is no BroadcastChannel, delta journal, status poll, TTL lease, renewal or writer takeover in this runtime. A lifetime Web Lock excludes another document using the same Profile; the second gets `PROFILE_ALREADY_OPEN` and should ask the user to return to the original tab. This lock uses the previous writer lock name so an older lock-based client cannot race the upgrade. Supported browsers must provide Web Locks. Native page navigation stays inside the original document.
|
|
386
|
+
|
|
387
|
+
The per-Profile database upgrades to schema 2 by deleting only the obsolete `lease` record. Existing messages, windows, reading facts, generation progress, cursor and outbox remain. The serial commit queue still atomically persists changed records and the Inbox cursor before publication. Failed disk transactions retry after the existing ten-second interval. A revision conflict requires restarting from committed state rather than endlessly retrying a stale projection.
|
|
388
|
+
|
|
389
|
+
On a Worker error or command timeout, the coordinator terminates the old Worker before replacement. The replacement restores committed data into the same UI memory store. An interrupted command is replayed with its original IDs; a message committed before a lost reply remains one message. Waiting for remote delivery does not itself time out or repeatedly restart an offline Worker. Completed generation switches publish one prepared snapshot; routine updates send only their delta.
|
|
390
|
+
|
|
391
|
+
Tests cover v1 upgrade preservation, atomic writes, idle zero transactions, one Worker on concurrent startup, serial restart, crash after commit/before reply, immediate startup cancellation, generation switching, and memory-only reads/subscriptions. Native frame rate, real-account upgrade and server synchronization still require application acceptance.
|
|
392
|
+
|
|
393
|
+
### Projection v2 repair (0.13.0-profile.10)
|
|
394
|
+
|
|
395
|
+
An existing v1 projection remains committed while a new generation rebuilds from the retained Inbox range. It is marked `restoring`, so the application cannot treat an incomplete or obsolete projection as an empty ready conversation. The rebuild resumes its saved progress after interruption, validates complete message/window references and atomically switches the active generation. Incompatible unfinished generations are eligible for bounded cleanup; the active generation and current-version builds remain protected.
|
|
396
|
+
|
|
397
|
+
Thread assignment carries group controls and metadata, child discussions, reading sources, pending controls/receipts and local reading intents into the destination Team. Later source events still resolve into that canonical Thread. Organization retains its assigned agent; reply counts remain independent of agent ownership. Confirmed and pending reading sources and per-message played/preserved facts survive generation reconciliation, as do durable pending sends.
|
|
398
|
+
|
|
399
|
+
The upgrade regression starts with an obsolete cached projection containing inaccessible discussion children, a locally played voice and a failed outgoing message. It interrupts the rebuild with HTTP 503, reopens the owner, resumes the same generation and verifies group/discussion metadata, reading and the exact durable outgoing message without clearing any store. Full SDK suite: 766 passed, one production-only test skipped.
|
|
400
|
+
|
|
401
|
+
Duplicate Inbox events, registrations and already-read observations are rejected as no-op batches before opening an IndexedDB write transaction; queue and store tests verify zero transactions as well as unchanged revisions.
|
package/lib/profile.d.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
2
|
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
3
|
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
-
export {
|
|
4
|
+
export { ProfileWorkerClient, serveProfileWorker } from "./runtime/profileWorkerClient.js";
|
|
5
5
|
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
6
|
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
8
|
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
9
|
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
-
export {
|
|
10
|
+
export { migrateLegacyInbox } from "./runtime/profileLegacyInbox.js";
|
|
11
|
+
export { migrateLegacyOutbox } from "./runtime/profileLegacyOutbox.js";
|
|
12
|
+
export { migrateLegacyReading } from "./runtime/profileLegacyReading.js";
|
|
13
|
+
export { createProfileChat, getProfileChatRuntime, handleProfileChatReach, revokeProfileChatAccess } from "./runtime/profileChat.js";
|
|
11
14
|
export type { ProfileChatHost } from "./runtime/profileChat.js";
|
|
12
15
|
export type { ProfileWorkerConfiguration } from "./runtime/profileWorkerHost.js";
|
|
13
16
|
export type { ProfileSnapshot, ProfileDelta } from "./runtime/profileMemoryStore.js";
|
package/lib/profile.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
2
|
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
3
|
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
-
export {
|
|
4
|
+
export { ProfileWorkerClient, serveProfileWorker } from "./runtime/profileWorkerClient.js";
|
|
5
5
|
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
6
|
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
8
|
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
9
|
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
-
export {
|
|
10
|
+
export { migrateLegacyInbox } from "./runtime/profileLegacyInbox.js";
|
|
11
|
+
export { migrateLegacyOutbox } from "./runtime/profileLegacyOutbox.js";
|
|
12
|
+
export { migrateLegacyReading } from "./runtime/profileLegacyReading.js";
|
|
13
|
+
export { createProfileChat, getProfileChatRuntime, handleProfileChatReach, revokeProfileChatAccess } from "./runtime/profileChat.js";
|
|
@@ -4,6 +4,7 @@ import type { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
|
4
4
|
import { type ProfileOperation } from "./profileProjection.js";
|
|
5
5
|
import type { ProfileIdentity } from "./profileStoreTypes.js";
|
|
6
6
|
import { type ChatRuntimeMessage } from "./protocol.js";
|
|
7
|
+
import type { OnlineReachEvent } from "./reach.js";
|
|
7
8
|
export type ProfileChatHost = {
|
|
8
9
|
identity: ProfileIdentity;
|
|
9
10
|
memory: ProfileMemoryStore;
|
|
@@ -15,6 +16,8 @@ export type ProfileChatHost = {
|
|
|
15
16
|
};
|
|
16
17
|
export declare function getProfileChatRuntime(chat: Chat): ProfileChat;
|
|
17
18
|
export declare function createProfileChat(host: ProfileChatHost, teamId: string): Chat;
|
|
19
|
+
export declare function handleProfileChatReach(chat: Chat, event: OnlineReachEvent): "handled" | undefined;
|
|
20
|
+
export declare function revokeProfileChatAccess(chat: Chat): Promise<void>;
|
|
18
21
|
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
19
22
|
* second outbox, reading persistence or per-team message database is created. */
|
|
20
23
|
export declare class ProfileChat implements Chat {
|
|
@@ -22,11 +25,13 @@ export declare class ProfileChat implements Chat {
|
|
|
22
25
|
readonly teamId: string;
|
|
23
26
|
private discussion?;
|
|
24
27
|
private views;
|
|
28
|
+
private preparedInputs;
|
|
25
29
|
private limits;
|
|
26
30
|
private listening;
|
|
27
31
|
private listListeners;
|
|
28
32
|
private offs;
|
|
29
33
|
private offList;
|
|
34
|
+
private readyWaiters;
|
|
30
35
|
private closed;
|
|
31
36
|
private summary;
|
|
32
37
|
constructor(host: ProfileChatHost, teamId: string, discussion?: {
|
|
@@ -37,6 +42,8 @@ export declare class ProfileChat implements Chat {
|
|
|
37
42
|
private key;
|
|
38
43
|
private thread;
|
|
39
44
|
private parent;
|
|
45
|
+
private accessError;
|
|
46
|
+
private assertAccessible;
|
|
40
47
|
private group;
|
|
41
48
|
private empty;
|
|
42
49
|
private snapshot;
|
|
@@ -126,9 +133,122 @@ export declare class ProfileChat implements Chat {
|
|
|
126
133
|
expectedRevision?: string;
|
|
127
134
|
}): Promise<ChatGroup>;
|
|
128
135
|
synchronizeReading(): Promise<void>;
|
|
129
|
-
revokeThread(id: string): Promise<void>;
|
|
130
136
|
revokeAccess(): Promise<void>;
|
|
137
|
+
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
138
|
+
grantAccess(expectedAccessRevision: number): Promise<void>;
|
|
131
139
|
firstUnread(id: string): string | undefined;
|
|
140
|
+
readPage(id: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly Readonly<{
|
|
141
|
+
id: string;
|
|
142
|
+
threadId: string;
|
|
143
|
+
threadRootId?: string;
|
|
144
|
+
timestamp: number;
|
|
145
|
+
from?: string;
|
|
146
|
+
mine: boolean;
|
|
147
|
+
status: "sending" | "sent" | "failed" | "read";
|
|
148
|
+
recalled: boolean;
|
|
149
|
+
unread?: boolean;
|
|
150
|
+
attentionEligible?: boolean;
|
|
151
|
+
reading?: Readonly<{
|
|
152
|
+
seq?: number;
|
|
153
|
+
read: boolean;
|
|
154
|
+
readPolicy: "visible" | "explicit";
|
|
155
|
+
}>;
|
|
156
|
+
reactions: readonly Readonly<{
|
|
157
|
+
emojiId: string;
|
|
158
|
+
userIds: string[];
|
|
159
|
+
mine: boolean;
|
|
160
|
+
}>[];
|
|
161
|
+
kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
|
|
162
|
+
text: string;
|
|
163
|
+
senderName?: string;
|
|
164
|
+
senderAvatar?: string;
|
|
165
|
+
timeLabel?: string;
|
|
166
|
+
file?: import("../fileMetadata.js").ChatFile;
|
|
167
|
+
image?: Readonly<{
|
|
168
|
+
url: string;
|
|
169
|
+
name?: string;
|
|
170
|
+
}>;
|
|
171
|
+
voice?: Readonly<{
|
|
172
|
+
url: string;
|
|
173
|
+
durationMs: number;
|
|
174
|
+
transcript?: string;
|
|
175
|
+
}>;
|
|
176
|
+
quote?: Readonly<{
|
|
177
|
+
messageId?: string;
|
|
178
|
+
senderName: string;
|
|
179
|
+
content: string;
|
|
180
|
+
recalled?: boolean;
|
|
181
|
+
}>;
|
|
182
|
+
attachment?: Readonly<{
|
|
183
|
+
name?: string;
|
|
184
|
+
size?: string;
|
|
185
|
+
}>;
|
|
186
|
+
richContent?: unknown;
|
|
187
|
+
mentions?: readonly import("../index.js").ChatMention[];
|
|
188
|
+
recipientCount?: number;
|
|
189
|
+
system?: Readonly<{
|
|
190
|
+
type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
|
|
191
|
+
title?: string;
|
|
192
|
+
}>;
|
|
193
|
+
}>[];
|
|
194
|
+
getWindowIds(id: string): readonly string[];
|
|
195
|
+
findMessageWindow(id: string, messageId: string): string | undefined;
|
|
196
|
+
readWindow(id: string, windowId: string): readonly Readonly<{
|
|
197
|
+
id: string;
|
|
198
|
+
threadId: string;
|
|
199
|
+
threadRootId?: string;
|
|
200
|
+
timestamp: number;
|
|
201
|
+
from?: string;
|
|
202
|
+
mine: boolean;
|
|
203
|
+
status: "sending" | "sent" | "failed" | "read";
|
|
204
|
+
recalled: boolean;
|
|
205
|
+
unread?: boolean;
|
|
206
|
+
attentionEligible?: boolean;
|
|
207
|
+
reading?: Readonly<{
|
|
208
|
+
seq?: number;
|
|
209
|
+
read: boolean;
|
|
210
|
+
readPolicy: "visible" | "explicit";
|
|
211
|
+
}>;
|
|
212
|
+
reactions: readonly Readonly<{
|
|
213
|
+
emojiId: string;
|
|
214
|
+
userIds: string[];
|
|
215
|
+
mine: boolean;
|
|
216
|
+
}>[];
|
|
217
|
+
kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
|
|
218
|
+
text: string;
|
|
219
|
+
senderName?: string;
|
|
220
|
+
senderAvatar?: string;
|
|
221
|
+
timeLabel?: string;
|
|
222
|
+
file?: import("../fileMetadata.js").ChatFile;
|
|
223
|
+
image?: Readonly<{
|
|
224
|
+
url: string;
|
|
225
|
+
name?: string;
|
|
226
|
+
}>;
|
|
227
|
+
voice?: Readonly<{
|
|
228
|
+
url: string;
|
|
229
|
+
durationMs: number;
|
|
230
|
+
transcript?: string;
|
|
231
|
+
}>;
|
|
232
|
+
quote?: Readonly<{
|
|
233
|
+
messageId?: string;
|
|
234
|
+
senderName: string;
|
|
235
|
+
content: string;
|
|
236
|
+
recalled?: boolean;
|
|
237
|
+
}>;
|
|
238
|
+
attachment?: Readonly<{
|
|
239
|
+
name?: string;
|
|
240
|
+
size?: string;
|
|
241
|
+
}>;
|
|
242
|
+
richContent?: unknown;
|
|
243
|
+
mentions?: readonly import("../index.js").ChatMention[];
|
|
244
|
+
recipientCount?: number;
|
|
245
|
+
system?: Readonly<{
|
|
246
|
+
type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
|
|
247
|
+
title?: string;
|
|
248
|
+
}>;
|
|
249
|
+
}>[];
|
|
250
|
+
subscribeWindowList(id: string, listener: () => void): () => void;
|
|
251
|
+
subscribeWindow(id: string, windowId: string, listener: () => void): () => void;
|
|
132
252
|
sharedTransport(): {
|
|
133
253
|
sendPrepared: (wire: ChatRuntimeMessage) => Promise<ChatRuntimeMessage>;
|
|
134
254
|
};
|
|
@@ -5,6 +5,8 @@ import { createRuntimeMsg } from "./protocol.js";
|
|
|
5
5
|
import { outgoingContent } from "./outgoingContent.js";
|
|
6
6
|
import { dmThreadId, groupThreadId } from "./thread.js";
|
|
7
7
|
import { createUniqueGroup } from "./groupIdentity.js";
|
|
8
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
9
|
+
import { scopedGroupDenial } from "./groupDenial.js";
|
|
8
10
|
const sessions = new WeakMap();
|
|
9
11
|
export function getProfileChatRuntime(chat) {
|
|
10
12
|
const session = sessions.get(chat);
|
|
@@ -13,6 +15,19 @@ export function getProfileChatRuntime(chat) {
|
|
|
13
15
|
return session;
|
|
14
16
|
}
|
|
15
17
|
export function createProfileChat(host, teamId) { return new ProfileChat(host, teamId); }
|
|
18
|
+
export function handleProfileChatReach(chat, event) {
|
|
19
|
+
if (!["social.readCountsChanged", "social.readStateChanged"].includes(event.eventType))
|
|
20
|
+
return;
|
|
21
|
+
const { identity } = getProfileChatRuntime(chat).host;
|
|
22
|
+
if (event.appId !== identity.appId)
|
|
23
|
+
throw Error("UNEXPECTED_READING_APPLICATION");
|
|
24
|
+
if (event.eventType === "social.readStateChanged" && event.payload.profileId !== identity.profileId)
|
|
25
|
+
throw Error("Reading reach identity mismatch");
|
|
26
|
+
// Inbox owns the ordered receipt stream. Reach is only a hint and must not
|
|
27
|
+
// create another reading store or apply facts outside that stream.
|
|
28
|
+
return "handled";
|
|
29
|
+
}
|
|
30
|
+
export function revokeProfileChatAccess(chat) { return getProfileChatRuntime(chat).revokeAccess(); }
|
|
16
31
|
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
17
32
|
* second outbox, reading persistence or per-team message database is created. */
|
|
18
33
|
export class ProfileChat {
|
|
@@ -20,11 +35,13 @@ export class ProfileChat {
|
|
|
20
35
|
teamId;
|
|
21
36
|
discussion;
|
|
22
37
|
views = new Map();
|
|
38
|
+
preparedInputs = new Map();
|
|
23
39
|
limits = new Map();
|
|
24
40
|
listening = new Map();
|
|
25
41
|
listListeners = new Set();
|
|
26
42
|
offs = new Map();
|
|
27
43
|
offList;
|
|
44
|
+
readyWaiters = new Set();
|
|
28
45
|
closed = false;
|
|
29
46
|
summary = { threads: [], unreadMessageCount: undefined, badgeCount: undefined, connection: "connecting" };
|
|
30
47
|
constructor(host, teamId, discussion) {
|
|
@@ -43,7 +60,21 @@ export class ProfileChat {
|
|
|
43
60
|
throw new ChatError("closed", "Chat session closed"); }
|
|
44
61
|
key(id) { return this.discussion ? profileDiscussionId(this.discussion.parentId, this.discussion.rootId) : id; }
|
|
45
62
|
thread(id) { return this.host.memory.getThread(this.key(id)); }
|
|
46
|
-
parent(id) {
|
|
63
|
+
parent(id) {
|
|
64
|
+
const thread = this.host.memory.getThread(this.discussion?.parentId ?? id);
|
|
65
|
+
return thread?.parentThreadId ? this.host.memory.getThread(thread.parentThreadId) : thread;
|
|
66
|
+
}
|
|
67
|
+
accessError(id) {
|
|
68
|
+
const parent = this.parent(id), thread = this.thread(id);
|
|
69
|
+
if (parent && parent.teamId !== this.teamId || thread && thread.teamId !== this.teamId)
|
|
70
|
+
return new ChatError("invalid-input", "Conversation belongs to another Team");
|
|
71
|
+
if (!this.host.memory.isTeamAvailable(this.teamId) || parent?.status === "unavailable" || thread?.status === "unavailable") {
|
|
72
|
+
const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
|
|
73
|
+
return parent?.kind === "group" ? scopedGroupDenial(error) : error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
assertAccessible(id) { this.assertOpen(); const error = this.accessError(id); if (error)
|
|
77
|
+
throw error; }
|
|
47
78
|
group(thread) {
|
|
48
79
|
const group = thread?.group;
|
|
49
80
|
if (!group)
|
|
@@ -65,14 +96,14 @@ export class ProfileChat {
|
|
|
65
96
|
}
|
|
66
97
|
prepare(id) {
|
|
67
98
|
const memory = this.host.memory, thread = this.thread(id), parent = this.parent(id);
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (thread?.status === "unavailable" || parent?.status === "unavailable") {
|
|
71
|
-
const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
|
|
99
|
+
const error = this.accessError(id);
|
|
100
|
+
if (error) {
|
|
72
101
|
const view = { ...this.empty(id), status: "error", ready: false, error };
|
|
73
102
|
this.views.set(id, view);
|
|
74
103
|
return view;
|
|
75
104
|
}
|
|
105
|
+
if (memory.getStatus().phase !== "ready" || !thread && !(this.discussion && parent?.status === "ready"))
|
|
106
|
+
return this.snapshot(id);
|
|
76
107
|
const count = Math.min(this.limits.get(id) ?? 128, thread?.messageCount ?? 0);
|
|
77
108
|
// Compatibility API accumulates requested pages; readPage remains the
|
|
78
109
|
// bounded API for page components and never materializes the whole thread.
|
|
@@ -83,6 +114,11 @@ export class ProfileChat {
|
|
|
83
114
|
pages.unshift(page);
|
|
84
115
|
anchor = page[0]?.id;
|
|
85
116
|
}
|
|
117
|
+
const inputs = this.preparedInputs.get(id);
|
|
118
|
+
if (inputs && inputs.thread === thread && inputs.parent === parent && inputs.pages.length === pages.length &&
|
|
119
|
+
pages.every((page, index) => page === inputs.pages[index]))
|
|
120
|
+
return this.snapshot(id);
|
|
121
|
+
this.preparedInputs.set(id, { thread, parent, pages });
|
|
86
122
|
const messages = pages.length === 1 ? pages[0] : pages.flat();
|
|
87
123
|
const group = this.group(parent);
|
|
88
124
|
const counts = {};
|
|
@@ -114,15 +150,37 @@ export class ProfileChat {
|
|
|
114
150
|
for (const listener of this.listListeners)
|
|
115
151
|
listener(this.summary);
|
|
116
152
|
}
|
|
117
|
-
async start() {
|
|
153
|
+
async start() {
|
|
154
|
+
this.assertOpen();
|
|
155
|
+
await this.host.start();
|
|
156
|
+
this.assertOpen();
|
|
157
|
+
if (this.host.memory.getStatus().phase !== "ready")
|
|
158
|
+
await new Promise((resolve, reject) => {
|
|
159
|
+
const cancel = () => { off(); this.readyWaiters.delete(cancel); reject(new ChatError("closed", "Chat session closed")); };
|
|
160
|
+
const check = () => {
|
|
161
|
+
if (this.host.memory.getStatus().phase !== "ready")
|
|
162
|
+
return;
|
|
163
|
+
off();
|
|
164
|
+
this.readyWaiters.delete(cancel);
|
|
165
|
+
resolve();
|
|
166
|
+
};
|
|
167
|
+
const off = this.host.memory.subscribeThreadList(check);
|
|
168
|
+
this.readyWaiters.add(cancel);
|
|
169
|
+
check();
|
|
170
|
+
});
|
|
171
|
+
this.assertOpen();
|
|
172
|
+
this.prepareSummary();
|
|
173
|
+
}
|
|
118
174
|
initialize() { return this.start(); }
|
|
119
175
|
async close() { if (this.closed)
|
|
120
|
-
return; this.closed = true;
|
|
176
|
+
return; this.closed = true; for (const cancel of this.readyWaiters)
|
|
177
|
+
cancel(); this.offList(); for (const off of this.offs.values())
|
|
121
178
|
off(); this.offs.clear(); this.listening.clear(); this.listListeners.clear(); }
|
|
122
179
|
async resolveThreadId(target, options = {}) {
|
|
123
180
|
this.assertOpen();
|
|
124
181
|
options.signal?.throwIfAborted();
|
|
125
|
-
await this.
|
|
182
|
+
await this.start();
|
|
183
|
+
options.signal?.throwIfAborted();
|
|
126
184
|
const kind = target.groupId !== undefined ? "group" : "dm", targetId = target.groupId ?? target.peerId;
|
|
127
185
|
if (this.discussion)
|
|
128
186
|
return this.discussion.parentId;
|
|
@@ -134,7 +192,16 @@ export class ProfileChat {
|
|
|
134
192
|
return id;
|
|
135
193
|
}
|
|
136
194
|
async getThread(id, options = {}) { this.assertOpen(); options.signal?.throwIfAborted(); return this.prepare(id); }
|
|
137
|
-
async loadEarlier(id, options = {}) {
|
|
195
|
+
async loadEarlier(id, options = {}) {
|
|
196
|
+
this.assertOpen();
|
|
197
|
+
options.signal?.throwIfAborted();
|
|
198
|
+
this.limits.set(id, (this.limits.get(id) ?? 128) + 128);
|
|
199
|
+
const previous = this.views.get(id), value = this.prepare(id);
|
|
200
|
+
if (previous !== value)
|
|
201
|
+
for (const listener of this.listening.get(id) ?? [])
|
|
202
|
+
listener(value);
|
|
203
|
+
return value;
|
|
204
|
+
}
|
|
138
205
|
async refreshThread(id, options = {}) { options.signal?.throwIfAborted(); await this.host.synchronize(); return this.getThread(id, options); }
|
|
139
206
|
subscribeThread(id, listener, _options = {}) {
|
|
140
207
|
this.assertOpen();
|
|
@@ -164,6 +231,7 @@ export class ProfileChat {
|
|
|
164
231
|
return new ProfileChat(this.host, this.teamId, { parentId: threadId, rootId });
|
|
165
232
|
}
|
|
166
233
|
async getMessageThreads(id, roots, options = {}) {
|
|
234
|
+
this.assertAccessible(id);
|
|
167
235
|
options.signal?.throwIfAborted();
|
|
168
236
|
return { revision: this.host.memory.getStatus().revision ?? 0, items: roots.map(root => {
|
|
169
237
|
const thread = this.host.memory.getThread(profileDiscussionId(id, root));
|
|
@@ -172,9 +240,13 @@ export class ProfileChat {
|
|
|
172
240
|
}) };
|
|
173
241
|
}
|
|
174
242
|
async sendPrepared(threadId, wire, options = {}, voiceBlob) {
|
|
175
|
-
this.
|
|
176
|
-
|
|
177
|
-
|
|
243
|
+
this.assertAccessible(threadId);
|
|
244
|
+
if (!this.discussion && this.thread(threadId)?.kind === "discussion")
|
|
245
|
+
throw new ChatError("invalid-input", "Use a discussion session to send replies");
|
|
246
|
+
const root = messageThreadRoot(wire.body);
|
|
247
|
+
const destination = this.discussion ? this.key(threadId) : root ? profileDiscussionId(threadId, root) : threadId;
|
|
248
|
+
await this.host.submit({ type: "send", threadId: destination, parentThreadId: this.discussion?.parentId ?? (root ? threadId : undefined), message: wire, command: {
|
|
249
|
+
commandId: wire.hash, messageId: wire.hash, kind: "message", threadId: destination, createdAt: wire.t,
|
|
178
250
|
payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: "pending", attempts: 0,
|
|
179
251
|
} }, true);
|
|
180
252
|
if (options.waitFor === "delivered")
|
|
@@ -182,6 +254,7 @@ export class ProfileChat {
|
|
|
182
254
|
return wire;
|
|
183
255
|
}
|
|
184
256
|
async sendMessage(id, content, options = {}) {
|
|
257
|
+
this.assertAccessible(id);
|
|
185
258
|
const parent = this.parent(id);
|
|
186
259
|
if (!parent?.internal?.targetId)
|
|
187
260
|
throw new ChatError("unavailable", "Conversation is not prepared");
|
|
@@ -197,32 +270,28 @@ export class ProfileChat {
|
|
|
197
270
|
const message = this.host.memory.getMessage(messageId);
|
|
198
271
|
if (!message)
|
|
199
272
|
throw new ChatError("invalid-input", "Message not found");
|
|
273
|
+
if (this.host.memory.getThread(message.threadId)?.teamId !== this.teamId || this.discussion && message.threadId !== this.key(this.discussion.parentId))
|
|
274
|
+
throw new ChatError("invalid-input", "Message not found");
|
|
275
|
+
this.assertAccessible(message.threadId);
|
|
200
276
|
await this.host.submit({ type: "commandResult", commandId: messageId, state: "pending" }, true);
|
|
201
277
|
return { id: messageId, timestamp: message.orderKey[0] };
|
|
202
278
|
}
|
|
203
279
|
observeMessages(id, ids, event) {
|
|
280
|
+
this.assertAccessible(id);
|
|
204
281
|
return this.host.submit({ type: "observe", threadId: this.key(id), messageIds: ids, policy: event, commandId: crypto.randomUUID(), createdAt: Date.now() }, event === "played");
|
|
205
282
|
}
|
|
206
283
|
async markRead(id) {
|
|
207
|
-
|
|
208
|
-
if (!thread)
|
|
284
|
+
this.assertAccessible(id);
|
|
285
|
+
if (!this.thread(id))
|
|
209
286
|
return;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
let anchor;
|
|
213
|
-
for (;;) {
|
|
214
|
-
const page = this.host.memory.readPage(this.key(id), anchor, 1000);
|
|
215
|
-
ids.push(...page.map(row => row.messageId));
|
|
216
|
-
if (page.length < 1000)
|
|
217
|
-
break;
|
|
218
|
-
anchor = page[0].messageId;
|
|
219
|
-
}
|
|
220
|
-
await this.observeMessages(id, ids, "visible");
|
|
287
|
+
await this.host.submit({ type: "observe", threadId: this.key(id), messageIds: [], allVisible: true,
|
|
288
|
+
policy: "visible", commandId: crypto.randomUUID(), createdAt: Date.now() });
|
|
221
289
|
}
|
|
222
290
|
async getReaders(id, messageId, options = {}) {
|
|
291
|
+
this.assertAccessible(id);
|
|
223
292
|
options.signal?.throwIfAborted();
|
|
224
293
|
const message = this.host.memory.getMessage(messageId);
|
|
225
|
-
if (!message || message.threadId !== this.key(id))
|
|
294
|
+
if (!message || message.threadId !== this.key(id) && (this.discussion || this.host.memory.getThread(message.threadId)?.parentThreadId !== id))
|
|
226
295
|
throw new ChatError("invalid-input", "Message not found");
|
|
227
296
|
if (message.receiptStatus !== "ready")
|
|
228
297
|
throw new ChatError("unavailable", "Reading receipts are not prepared");
|
|
@@ -232,9 +301,10 @@ export class ProfileChat {
|
|
|
232
301
|
}
|
|
233
302
|
async watchReaders(_id, _ids, _receiver) { }
|
|
234
303
|
async getVoiceAttachment(id, messageId, options = {}) {
|
|
304
|
+
this.assertAccessible(id);
|
|
235
305
|
options.signal?.throwIfAborted();
|
|
236
306
|
const message = this.host.memory.getMessage(messageId);
|
|
237
|
-
if (!message || message.threadId !== this.key(id))
|
|
307
|
+
if (!message || message.threadId !== this.key(id) && (this.discussion || this.host.memory.getThread(message.threadId)?.parentThreadId !== id))
|
|
238
308
|
throw new ChatError("invalid-input", "Message not found");
|
|
239
309
|
const url = this.host.memory.getPresentedMessage(messageId)?.voice?.url;
|
|
240
310
|
if (url)
|
|
@@ -245,7 +315,7 @@ export class ProfileChat {
|
|
|
245
315
|
const objectUrl = URL.createObjectURL(blob);
|
|
246
316
|
return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) };
|
|
247
317
|
}
|
|
248
|
-
async getGroup(id, options = {}) { options.signal?.throwIfAborted(); const group = this.group(this.parent(id)); if (!group)
|
|
318
|
+
async getGroup(id, options = {}) { this.assertAccessible(id); options.signal?.throwIfAborted(); const group = this.group(this.parent(id)); if (!group)
|
|
249
319
|
throw new ChatError("unavailable", "Group is not prepared"); return group; }
|
|
250
320
|
async refreshGroup(id, options = {}) { await this.host.synchronize(); return this.getGroup(id, options); }
|
|
251
321
|
async waitGroup(id, previous) {
|
|
@@ -282,11 +352,34 @@ export class ProfileChat {
|
|
|
282
352
|
async updateGroup(id, changes) { const previous = await this.getGroup(id); await this.sendControl(id, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
283
353
|
async dissolveGroup(id, options = {}) { const previous = await this.getGroup(id); await this.sendControl(id, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
284
354
|
synchronizeReading() { return this.host.synchronize(); }
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
355
|
+
revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
|
|
356
|
+
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
357
|
+
grantAccess(expectedAccessRevision) { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: true, expectedAccessRevision }, true); }
|
|
358
|
+
firstUnread(id) { this.assertAccessible(id); return this.thread(id)?.firstUnreadMessageId; }
|
|
359
|
+
readPage(id, anchor, limit, direction = "older") {
|
|
360
|
+
this.assertAccessible(id);
|
|
361
|
+
return this.host.memory.readPresentedPage(this.key(id), anchor, limit, direction);
|
|
362
|
+
}
|
|
363
|
+
getWindowIds(id) {
|
|
364
|
+
this.assertAccessible(id);
|
|
365
|
+
return this.host.memory.getWindowIds(this.key(id));
|
|
366
|
+
}
|
|
367
|
+
findMessageWindow(id, messageId) {
|
|
368
|
+
this.assertAccessible(id);
|
|
369
|
+
return this.host.memory.findMessageWindow(this.key(id), messageId);
|
|
370
|
+
}
|
|
371
|
+
readWindow(id, windowId) {
|
|
372
|
+
this.assertAccessible(id);
|
|
373
|
+
return this.host.memory.readPresentedWindow(this.key(id), windowId);
|
|
374
|
+
}
|
|
375
|
+
subscribeWindowList(id, listener) {
|
|
376
|
+
this.assertAccessible(id);
|
|
377
|
+
return this.host.memory.subscribeWindowList(this.key(id), listener);
|
|
378
|
+
}
|
|
379
|
+
subscribeWindow(id, windowId, listener) {
|
|
380
|
+
this.assertAccessible(id);
|
|
381
|
+
return this.host.memory.subscribeWindow(this.key(id), windowId, listener);
|
|
382
|
+
}
|
|
290
383
|
sharedTransport() {
|
|
291
384
|
return { sendPrepared: (wire) => {
|
|
292
385
|
const content = wire.body;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export type ProfileCommitQueueOptions<T> = {
|
|
2
|
-
commit: (events: readonly T[]) => Promise<void>;
|
|
2
|
+
commit: (events: readonly T[]) => Promise<void | readonly (Error | undefined)[]>;
|
|
3
3
|
windowMs?: number;
|
|
4
|
+
windowMsForEvent?: (event: T) => number;
|
|
4
5
|
maxEvents?: number;
|
|
5
6
|
maxBytes?: number;
|
|
6
7
|
capacityEvents?: number;
|
|
@@ -11,7 +11,7 @@ export class ProfileCommitQueue {
|
|
|
11
11
|
retryBatch;
|
|
12
12
|
options;
|
|
13
13
|
constructor(options) {
|
|
14
|
-
this.options = { commit: options.commit, onError: options.onError,
|
|
14
|
+
this.options = { commit: options.commit, onError: options.onError, windowMsForEvent: options.windowMsForEvent,
|
|
15
15
|
windowMs: options.windowMs ?? 200, maxEvents: options.maxEvents ?? 200, maxBytes: options.maxBytes ?? 512 * 1024,
|
|
16
16
|
capacityEvents: options.capacityEvents ?? 2000, capacityBytes: options.capacityBytes ?? 8 * 1024 * 1024,
|
|
17
17
|
retryMs: options.retryMs ?? 10000 };
|
|
@@ -31,7 +31,10 @@ export class ProfileCommitQueue {
|
|
|
31
31
|
if (this.entries.length >= this.options.capacityEvents ||
|
|
32
32
|
this.entries.length > 0 && this.bytes + bytes > this.options.capacityBytes)
|
|
33
33
|
throw new Error("PROFILE_COMMIT_BACKPRESSURE");
|
|
34
|
-
const
|
|
34
|
+
const windowMs = this.options.windowMsForEvent?.(event) ?? this.options.windowMs;
|
|
35
|
+
if (!Number.isSafeInteger(windowMs) || windowMs < 1)
|
|
36
|
+
throw Error("INVALID_COMMIT_EVENT_WINDOW");
|
|
37
|
+
const completion = new Promise((resolve, reject) => this.entries.push({ event, bytes, due: Date.now() + windowMs, resolve, reject, barrier }));
|
|
35
38
|
this.bytes += bytes;
|
|
36
39
|
this.urgent ||= immediate;
|
|
37
40
|
this.schedule();
|
|
@@ -48,7 +51,7 @@ export class ProfileCommitQueue {
|
|
|
48
51
|
clearTimeout(this.timer);
|
|
49
52
|
const now = Date.now();
|
|
50
53
|
const full = this.entries.length >= this.options.maxEvents || this.bytes >= this.options.maxBytes;
|
|
51
|
-
const due = Math.max(this.retryAt, this.urgent || full ? now : this.entries
|
|
54
|
+
const due = Math.max(this.retryAt, this.urgent || full ? now : Math.min(...this.entries.map(entry => entry.due)));
|
|
52
55
|
this.timer = setTimeout(() => { this.timer = undefined; void this.run(); }, Math.max(0, due - now));
|
|
53
56
|
}
|
|
54
57
|
async run() {
|
|
@@ -70,16 +73,32 @@ export class ProfileCommitQueue {
|
|
|
70
73
|
const task = Promise.resolve().then(() => this.options.commit(batch.map(entry => entry.event)));
|
|
71
74
|
this.running = task;
|
|
72
75
|
try {
|
|
73
|
-
await task;
|
|
76
|
+
const rejected = await task;
|
|
74
77
|
this.entries.splice(0, count);
|
|
75
78
|
this.bytes -= bytes;
|
|
76
79
|
this.retryAt = 0;
|
|
77
80
|
this.retryBatch = undefined;
|
|
78
|
-
batch.forEach(entry =>
|
|
81
|
+
batch.forEach((entry, index) => { const error = rejected?.[index]; if (error)
|
|
82
|
+
entry.reject(error);
|
|
83
|
+
else
|
|
84
|
+
entry.resolve(); });
|
|
79
85
|
}
|
|
80
86
|
catch (error) {
|
|
81
|
-
|
|
82
|
-
|
|
87
|
+
if (["PROFILE_REVISION_CONFLICT", "PROFILE_GENERATION_MISMATCH"].includes(error?.message)) {
|
|
88
|
+
// A stale projection cannot become valid by retrying the same batch.
|
|
89
|
+
// Restart the Worker from its last committed database state.
|
|
90
|
+
this.closed = true;
|
|
91
|
+
clearTimeout(this.timer);
|
|
92
|
+
const pending = this.entries.splice(0);
|
|
93
|
+
this.bytes = 0;
|
|
94
|
+
this.retryBatch = undefined;
|
|
95
|
+
for (const entry of pending)
|
|
96
|
+
entry.reject(error);
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
this.retryBatch = batch;
|
|
100
|
+
this.retryAt = Date.now() + this.options.retryMs;
|
|
101
|
+
}
|
|
83
102
|
try {
|
|
84
103
|
this.options.onError?.(error);
|
|
85
104
|
}
|