@pmate/chat-sdk 0.12.0-next.95 → 0.13.0-profile.0

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.
Files changed (41) hide show
  1. package/lib/framework.d.ts +2 -0
  2. package/lib/framework.js +2 -0
  3. package/lib/messageView.d.ts +5 -0
  4. package/lib/messageView.js +2 -2
  5. package/lib/profile.d.ts +14 -0
  6. package/lib/profile.js +10 -0
  7. package/lib/profileWorker.d.ts +1 -0
  8. package/lib/profileWorker.js +3 -0
  9. package/lib/runtime/inboxClient.d.ts +3 -1
  10. package/lib/runtime/inboxClient.js +19 -1
  11. package/lib/runtime/profileChat.d.ts +135 -0
  12. package/lib/runtime/profileChat.js +299 -0
  13. package/lib/runtime/profileCommitQueue.d.ts +38 -0
  14. package/lib/runtime/profileCommitQueue.js +101 -0
  15. package/lib/runtime/profileCoordinator.d.ts +46 -0
  16. package/lib/runtime/profileCoordinator.js +135 -0
  17. package/lib/runtime/profileDatabase.d.ts +42 -0
  18. package/lib/runtime/profileDatabase.js +164 -0
  19. package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
  20. package/lib/runtime/profileGenerationBuilder.js +112 -0
  21. package/lib/runtime/profileInboxFeed.d.ts +38 -0
  22. package/lib/runtime/profileInboxFeed.js +240 -0
  23. package/lib/runtime/profileMemoryStore.d.ts +113 -0
  24. package/lib/runtime/profileMemoryStore.js +259 -0
  25. package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
  26. package/lib/runtime/profileOutboxDispatcher.js +106 -0
  27. package/lib/runtime/profileOwner.d.ts +57 -0
  28. package/lib/runtime/profileOwner.js +202 -0
  29. package/lib/runtime/profileProjection.d.ts +77 -0
  30. package/lib/runtime/profileProjection.js +625 -0
  31. package/lib/runtime/profileReadingIndex.d.ts +17 -0
  32. package/lib/runtime/profileReadingIndex.js +99 -0
  33. package/lib/runtime/profileReplica.d.ts +59 -0
  34. package/lib/runtime/profileReplica.js +236 -0
  35. package/lib/runtime/profileStoreTypes.d.ts +163 -0
  36. package/lib/runtime/profileStoreTypes.js +1 -0
  37. package/lib/runtime/profileWindows.d.ts +38 -0
  38. package/lib/runtime/profileWindows.js +175 -0
  39. package/lib/runtime/profileWorkerHost.d.ts +33 -0
  40. package/lib/runtime/profileWorkerHost.js +156 -0
  41. package/package.json +11 -1
@@ -0,0 +1,625 @@
1
+ import { inboxSequence } from "./inboxStore.js";
2
+ import { messageMentionsProfile, messageRequiresPlayback } from "./readingContent.js";
3
+ import { messageThreadRoot } from "./messageThread.js";
4
+ import { projectInboxGroup } from "./inboxGroup.js";
5
+ import { validateInboxReceipt } from "./inboxProjections.js";
6
+ import { ProfileReadingIndex } from "./profileReadingIndex.js";
7
+ import { compareProfileOrder, ProfileWindowDirectory } from "./profileWindows.js";
8
+ import { projectMessageContent } from "../messageView.js";
9
+ export const profileDiscussionId = (parent, root) => `discussion:${JSON.stringify([parent, root])}`;
10
+ /** Committed authority for the replay reducer. Drafts contain only changed rows;
11
+ * failure discards the draft, leaving both entities and indexes untouched. */
12
+ export class ProfileProjection {
13
+ identity;
14
+ windowStart;
15
+ threads = new Map();
16
+ messages = new Map();
17
+ directories = new Map();
18
+ readingIndices = new Map();
19
+ children = new Map();
20
+ outbox = new Map();
21
+ current;
22
+ constructor(identity, snapshot, windowStart) {
23
+ this.identity = identity;
24
+ this.windowStart = windowStart;
25
+ this.current = snapshot.current;
26
+ for (const command of snapshot.outbox ?? [])
27
+ this.outbox.set(command.commandId, command);
28
+ for (const row of snapshot.threads)
29
+ this.threads.set(row.threadId, row);
30
+ for (const row of snapshot.messages)
31
+ this.messages.set(row.messageId, row);
32
+ const windows = new Map();
33
+ for (const row of snapshot.windows) {
34
+ const rows = windows.get(row.threadId) ?? [];
35
+ rows.push(row);
36
+ windows.set(row.threadId, rows);
37
+ }
38
+ for (const [id, rows] of windows)
39
+ this.directories.set(id, new ProfileWindowDirectory(this.current.activeGeneration, id, rows));
40
+ for (const row of snapshot.threads)
41
+ if (row.parentThreadId) {
42
+ const children = this.children.get(row.parentThreadId) ?? new Set();
43
+ children.add(row.threadId);
44
+ this.children.set(row.parentThreadId, children);
45
+ }
46
+ for (const row of snapshot.messages) {
47
+ const index = this.readingIndices.get(row.threadId) ?? new ProfileReadingIndex();
48
+ index.upsert(row, identity.profileId, this.threads.get(row.threadId)?.readingSources.find(source => source.sourceThreadId === row.sourceThreadId));
49
+ this.readingIndices.set(row.threadId, index);
50
+ }
51
+ }
52
+ prepare(events) {
53
+ const draft = new ProfileProjectionDraft(this);
54
+ for (const event of events) {
55
+ if ("type" in event)
56
+ draft.local(event);
57
+ else
58
+ draft.event(event);
59
+ }
60
+ return draft.finish();
61
+ }
62
+ prepareBasis(bootstrap) {
63
+ if (bootstrap.appId !== this.identity.appId || bootstrap.profileId !== this.identity.profileId || bootstrap.epoch !== this.current.epoch)
64
+ throw Error("INBOX_IDENTITY_MISMATCH");
65
+ const draft = new ProfileProjectionDraft(this), start = inboxSequence(bootstrap.startSeq);
66
+ for (const item of bootstrap.basis) {
67
+ if (inboxSequence(item.inboxSeq) >= start)
68
+ throw Error("INVALID_INBOX_BASIS_SEQUENCE");
69
+ draft.event({ inboxSeq: item.inboxSeq, sourceId: item.id, acceptedAt: bootstrap.windowStart - 1, kind: item.kind, fact: item.fact }, true);
70
+ }
71
+ return draft.finish();
72
+ }
73
+ accept(prepared) {
74
+ if (prepared.current.activeGeneration !== this.current.activeGeneration || prepared.current.commitRevision !== this.current.commitRevision + 1)
75
+ throw Error("PROFILE_REVISION_CONFLICT");
76
+ for (const row of prepared.threads) {
77
+ this.threads.set(row.threadId, row);
78
+ if (row.parentThreadId) {
79
+ const children = this.children.get(row.parentThreadId) ?? new Set();
80
+ children.add(row.threadId);
81
+ this.children.set(row.parentThreadId, children);
82
+ }
83
+ }
84
+ for (const row of prepared.messages) {
85
+ this.messages.set(row.messageId, row);
86
+ }
87
+ for (const [id, index] of prepared.readingIndices)
88
+ this.readingIndices.set(id, index);
89
+ for (const command of prepared.outbox)
90
+ this.outbox.set(command.commandId, command);
91
+ for (const id of prepared.deleteOutbox)
92
+ this.outbox.delete(id);
93
+ for (const row of prepared.windows) {
94
+ let directory = this.directories.get(row.threadId);
95
+ if (!directory) {
96
+ directory = new ProfileWindowDirectory(row.generation, row.threadId);
97
+ this.directories.set(row.threadId, directory);
98
+ }
99
+ directory.accept({ windows: [row], windowCount: 0 });
100
+ }
101
+ this.current = prepared.current;
102
+ }
103
+ snapshot() {
104
+ return { current: this.current, threads: [...this.threads.values()], messages: [...this.messages.values()],
105
+ windows: [...this.directories.values()].flatMap(directory => [...directory.blocks]) };
106
+ }
107
+ }
108
+ class ProfileProjectionDraft {
109
+ base;
110
+ threads = new Map();
111
+ messages = new Map();
112
+ directories = new Map();
113
+ windows = new Map();
114
+ readingIndices = new Map();
115
+ outbox = new Map();
116
+ deleteOutbox = new Set();
117
+ seq;
118
+ revision;
119
+ receiptsReady;
120
+ constructor(base) {
121
+ this.base = base;
122
+ this.seq = inboxSequence(base.current.committedSeq);
123
+ this.revision = base.current.commitRevision + 1;
124
+ this.receiptsReady = base.current.receiptsReady;
125
+ }
126
+ message(id) { return this.messages.get(id) ?? this.base.messages.get(id); }
127
+ thread(id) { return this.threads.get(id) ?? this.base.threads.get(id); }
128
+ ensure(id, kind = "group", extra = {}) {
129
+ const previous = this.thread(id);
130
+ if (previous)
131
+ return previous;
132
+ const row = { generation: this.base.current.activeGeneration, threadId: id, kind, title: "", lastActivityAt: 0,
133
+ messageCount: 0, windowCount: 0, readingStatus: "read", unreadCount: 0, mentionCount: 0, readingSources: [],
134
+ coverage: { complete: true, windowStart: this.base.windowStart }, status: "ready", revision: this.revision, ...extra };
135
+ this.threads.set(id, row);
136
+ return row;
137
+ }
138
+ putThread(row) { this.threads.set(row.threadId, { ...row, revision: this.revision }); }
139
+ directory(id) {
140
+ let value = this.directories.get(id);
141
+ if (!value) {
142
+ value = this.base.directories.get(id)?.fork() ?? new ProfileWindowDirectory(this.base.current.activeGeneration, id);
143
+ this.directories.set(id, value);
144
+ }
145
+ return value;
146
+ }
147
+ source(thread, sourceId) { return thread.readingSources.find(row => row.sourceThreadId === sourceId); }
148
+ readingIndex(id) {
149
+ let index = this.readingIndices.get(id);
150
+ if (!index) {
151
+ index = this.base.readingIndices.get(id)?.fork() ?? new ProfileReadingIndex();
152
+ this.readingIndices.set(id, index);
153
+ }
154
+ return index;
155
+ }
156
+ firstUnread(id) {
157
+ const thread = this.thread(id);
158
+ let first = this.readingIndex(id).summary(thread.readingSources).first;
159
+ const children = new Set(this.base.children.get(id));
160
+ for (const row of this.threads.values())
161
+ if (row.parentThreadId === id)
162
+ children.add(row.threadId);
163
+ for (const childId of children) {
164
+ const child = this.thread(childId);
165
+ if (!child?.unreadCount || !child.rootMessageId)
166
+ continue;
167
+ const root = this.message(child.rootMessageId);
168
+ if (root && (!first || compareProfileOrder(root.orderKey, first.orderKey) < 0))
169
+ first = { messageId: root.messageId, orderKey: root.orderKey };
170
+ }
171
+ return first?.messageId;
172
+ }
173
+ read(message, thread = this.thread(message.threadId)) {
174
+ if (message.from === this.base.identity.profileId || message.recalled)
175
+ return true;
176
+ if (message.readPolicy === "discussion")
177
+ return this.thread(message.discussionThreadId)?.readingStatus === "read";
178
+ if (!message.sourceSeq)
179
+ return false;
180
+ if (message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId))
181
+ return true;
182
+ const source = thread && this.source(thread, message.sourceThreadId);
183
+ if (source?.preservedReadMessageIds.includes(message.messageId) || source?.explicitReadMessageIds.includes(message.messageId) || source?.pendingExplicitReadMessageIds?.includes(message.messageId))
184
+ return true;
185
+ return message.readPolicy !== "explicit" && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0);
186
+ }
187
+ contribution(message, thread) {
188
+ return message && message.readPolicy !== "discussion" && !this.read(message, thread) ? { unread: 1, mentions: message.mention ? 1 : 0 } : { unread: 0, mentions: 0 };
189
+ }
190
+ updateSummary(id, unreadDelta, mentionDelta) {
191
+ if (!unreadDelta && !mentionDelta)
192
+ return;
193
+ const thread = this.thread(id);
194
+ const unreadCount = thread.unreadCount === null ? null : Math.max(0, thread.unreadCount + unreadDelta);
195
+ this.putThread({ ...thread, unreadCount, mentionCount: thread.mentionCount === null ? null : Math.max(0, thread.mentionCount + mentionDelta),
196
+ firstUnreadMessageId: this.firstUnread(id), readingStatus: unreadCount === null ? "unknown" : unreadCount > 0 ? "unread" : "read" });
197
+ if (thread.parentThreadId)
198
+ this.updateSummary(thread.parentThreadId, unreadDelta, mentionDelta);
199
+ }
200
+ setMessage(next) {
201
+ const previous = this.message(next.messageId);
202
+ const before = this.contribution(previous), after = this.contribution(next);
203
+ if (previous)
204
+ this.readingIndex(previous.threadId).remove(previous);
205
+ this.readingIndex(next.threadId).upsert(next, this.base.identity.profileId, this.source(this.thread(next.threadId), next.sourceThreadId));
206
+ this.messages.set(next.messageId, { ...next, revision: this.revision });
207
+ if (previous?.threadId === next.threadId)
208
+ this.updateSummary(next.threadId, after.unread - before.unread, after.mentions - before.mentions);
209
+ else {
210
+ if (previous)
211
+ this.updateSummary(previous.threadId, -before.unread, -before.mentions);
212
+ this.updateSummary(next.threadId, after.unread, after.mentions);
213
+ }
214
+ }
215
+ insert(message, historical = false) {
216
+ const directory = this.directory(message.threadId);
217
+ const change = directory.insert({ messageId: message.messageId, orderKey: message.orderKey }, {
218
+ historical, revision: this.revision, newWindowId: () => crypto.randomUUID()
219
+ });
220
+ for (const row of change.windows) {
221
+ const readingIndex = row.refs.map(ref => {
222
+ const entity = ref.messageId === message.messageId ? message : this.message(ref.messageId);
223
+ return { messageId: ref.messageId, sourceThreadId: entity.sourceThreadId, sourceSeq: entity.sourceSeq,
224
+ policy: entity.readPolicy ?? "visible", mention: entity.mention ?? false };
225
+ });
226
+ const next = { ...row, readingIndex };
227
+ this.windows.set(JSON.stringify([row.threadId, row.windowId]), next);
228
+ directory.accept({ ...change, windows: [next] });
229
+ }
230
+ const thread = this.thread(message.threadId);
231
+ const last = thread.lastMessageId ? this.message(thread.lastMessageId) : undefined;
232
+ const newer = !last || compareProfileOrder(last.orderKey, message.orderKey) < 0;
233
+ const participantCounts = { ...thread.internal?.participantCounts };
234
+ if (directory.count > thread.messageCount)
235
+ participantCounts[message.from] = (participantCounts[message.from] ?? 0) + 1;
236
+ this.putThread({ ...thread, messageCount: directory.count, windowCount: change.windowCount, pendingWindowId: change.pendingWindowId,
237
+ internal: { ...thread.internal, participantCounts }, participantProfileIds: Object.keys(participantCounts).filter(id => participantCounts[id] > 0).sort(),
238
+ ...(newer ? { lastMessageId: message.messageId, lastActivityAt: message.orderKey[0] } : {}) });
239
+ }
240
+ move(message, destination) {
241
+ if (message.threadId === destination)
242
+ return;
243
+ const oldThread = this.thread(message.threadId), wasRead = this.read(message);
244
+ const directory = this.directory(message.threadId), change = directory.remove(message.messageId, this.revision);
245
+ directory.accept(change);
246
+ for (const row of change.windows)
247
+ this.windows.set(JSON.stringify([row.threadId, row.windowId]), row);
248
+ const last = directory.readPage(undefined, 1)[0];
249
+ const participantCounts = { ...oldThread.internal?.participantCounts, [message.from]: Math.max(0, (oldThread.internal?.participantCounts?.[message.from] ?? 1) - 1) };
250
+ this.putThread({ ...oldThread, messageCount: directory.count, windowCount: change.windowCount,
251
+ internal: { ...oldThread.internal, participantCounts }, participantProfileIds: Object.keys(participantCounts).filter(id => participantCounts[id] > 0).sort(),
252
+ lastMessageId: last?.messageId, lastActivityAt: last?.orderKey[0] ?? 0 });
253
+ const next = { ...message, threadId: destination, explicitReadingFacts: wasRead && message.from !== this.base.identity.profileId ?
254
+ [...message.explicitReadingFacts.filter(row => row.profileId !== this.base.identity.profileId), { profileId: this.base.identity.profileId, kind: "preserved" }] : message.explicitReadingFacts };
255
+ this.setMessage(next);
256
+ this.insert(next, true);
257
+ }
258
+ event(event, basis = false) {
259
+ const seq = inboxSequence(event.inboxSeq);
260
+ if (!basis && seq <= this.seq)
261
+ return;
262
+ if (!basis && seq !== this.seq + 1n)
263
+ throw Error("INBOX_SEQUENCE_GAP");
264
+ if (event.fact.appId !== this.base.identity.appId)
265
+ throw Error("INBOX_FACT_IDENTITY_MISMATCH");
266
+ switch (event.kind) {
267
+ case "messageAdded":
268
+ this.add(event);
269
+ break;
270
+ case "readingUpdated":
271
+ this.reading(event);
272
+ break;
273
+ case "threadOrganized":
274
+ this.organize(event);
275
+ break;
276
+ case "threadAssigned":
277
+ this.assign(event);
278
+ break;
279
+ case "relationshipUpdated":
280
+ this.relationship(event);
281
+ break;
282
+ default: throw Error(`UNSUPPORTED_INBOX_EVENT:${event.kind}`);
283
+ }
284
+ if (!basis)
285
+ this.seq = seq;
286
+ }
287
+ local(operation) {
288
+ if (operation.type === "commandPayload") {
289
+ const command = this.outbox.get(operation.commandId) ?? this.base.outbox.get(operation.commandId);
290
+ if (!command || command.kind !== "message" || operation.message.hash !== command.messageId || operation.message.from !== this.base.identity.profileId)
291
+ throw Error("OUTBOX_MESSAGE_IDENTITY_MISMATCH");
292
+ this.outbox.set(command.commandId, { ...command, payload: operation.message });
293
+ const message = this.message(operation.message.hash);
294
+ if (message)
295
+ this.setMessage({ ...message, content: operation.message.body,
296
+ presentation: projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0], from: message.from,
297
+ recipients: message.recipients, body: operation.message.body, threadKind: this.thread(message.threadId)?.kind === "dm" ? "dm" : "group" }) });
298
+ return;
299
+ }
300
+ if (operation.type === "register") {
301
+ this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
302
+ return;
303
+ }
304
+ if (operation.type === "revoke") {
305
+ const thread = this.thread(operation.threadId);
306
+ if (thread && thread.status !== "unavailable")
307
+ this.putThread({ ...thread, status: "unavailable", readingStatus: "unknown", unreadCount: null, mentionCount: null });
308
+ return;
309
+ }
310
+ if (operation.type === "restoreReceipt") {
311
+ this.reading({ inboxSeq: "0", sourceId: "receipt-baseline", acceptedAt: 0, kind: "readingUpdated", fact: { ...operation.data, receiptOnly: true } });
312
+ return;
313
+ }
314
+ if (operation.type === "receiptsReady") {
315
+ if (this.receiptsReady)
316
+ return;
317
+ const ids = new Set([...this.base.messages.keys(), ...this.messages.keys()]);
318
+ for (const id of ids) {
319
+ const message = this.message(id);
320
+ if (message.from === this.base.identity.profileId && message.receiptStatus !== "ready")
321
+ this.setMessage({ ...message, receiptStatus: "ready" });
322
+ }
323
+ this.receiptsReady = true;
324
+ return;
325
+ }
326
+ if (operation.type === "restoreReading") {
327
+ this.reading({ inboxSeq: "0", sourceId: "local-restore", acceptedAt: 0, kind: "readingUpdated", fact: operation.data }, false);
328
+ return;
329
+ }
330
+ if (operation.type === "send") {
331
+ const wire = structuredClone(operation.message), payload = operation.command.payload;
332
+ const command = { ...operation.command, payload: payload?.voiceBlob instanceof Blob ? { message: wire, voiceBlob: payload.voiceBlob } : wire };
333
+ if (wire.from !== this.base.identity.profileId || command.messageId !== wire.hash || command.commandId !== wire.hash || command.threadId !== operation.threadId)
334
+ throw Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
335
+ if (this.message(wire.hash) || this.outbox.has(command.commandId) || this.base.outbox.has(command.commandId))
336
+ return;
337
+ let thread = this.thread(operation.threadId);
338
+ if (!thread && operation.parentThreadId) {
339
+ const parent = this.thread(operation.parentThreadId), root = messageThreadRoot(wire.body);
340
+ if (parent && root && profileDiscussionId(parent.threadId, root) === operation.threadId) {
341
+ thread = this.ensure(operation.threadId, "discussion", { parentThreadId: parent.threadId, rootMessageId: root, teamId: parent.teamId });
342
+ const rootMessage = this.message(root);
343
+ if (rootMessage)
344
+ this.setMessage({ ...rootMessage, readPolicy: "discussion", discussionThreadId: thread.threadId });
345
+ }
346
+ }
347
+ if (!thread || thread.status !== "ready")
348
+ throw Error("PROFILE_THREAD_NOT_READY");
349
+ const body = wire.body;
350
+ const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
351
+ const recall = body?.kind === "recall" ? body.targetMessageId : body?.content?.recall?.messageId;
352
+ if (reaction || recall || body?.kind === "group") {
353
+ if (reaction) {
354
+ const target = this.message(reaction.messageId), key = JSON.stringify(["reaction", wire.from, reaction.emojiId]);
355
+ const previous = target?.controlVersions[key];
356
+ const floor = typeof previous === "string" ? JSON.parse(previous)[0] : 0;
357
+ reaction.revision = Math.max(Number.isSafeInteger(reaction.revision) ? reaction.revision : 1, floor + 1);
358
+ }
359
+ this.outbox.set(command.commandId, command);
360
+ if (reaction || recall)
361
+ this.control(thread.parentThreadId ?? thread.threadId, {
362
+ messageId: wire.hash, threadId: thread.parentThreadId ?? thread.threadId, appId: this.base.identity.appId,
363
+ teamId: thread.teamId, threadKind: thread.kind === "dm" ? "dm" : "group", from: wire.from, to: wire.to,
364
+ recipients: wire.recipients, serverCreatedAt: wire.t, body: wire.body,
365
+ }, reaction, recall);
366
+ return;
367
+ }
368
+ const message = { generation: this.base.current.activeGeneration, messageId: wire.hash,
369
+ sourceThreadId: thread.parentThreadId ?? thread.threadId, threadId: thread.threadId,
370
+ orderKey: [wire.t, thread.parentThreadId ?? thread.threadId, Number.MAX_SAFE_INTEGER, wire.hash], from: wire.from,
371
+ recipients: wire.recipients, content: wire.body, attachmentRefs: [], reactions: [], sendStatus: "sending",
372
+ readPolicy: messageRequiresPlayback(wire.body) ? "explicit" : "visible", readBy: [], receiptStatus: "unknown",
373
+ explicitReadingFacts: [], controlVersions: {}, revision: this.revision };
374
+ message.presentation = projectMessageContent({ id: wire.hash, messageId: wire.hash, threadId: thread.threadId,
375
+ timestamp: wire.t, serverCreatedAt: wire.t, appId: this.base.identity.appId, teamId: thread.teamId,
376
+ threadKind: thread.kind === "discussion" ? "group" : thread.kind, from: wire.from, to: wire.to, recipients: wire.recipients, body: wire.body });
377
+ this.outbox.set(command.commandId, command);
378
+ this.setMessage(message);
379
+ this.insert(message);
380
+ return;
381
+ }
382
+ if (operation.type === "commandResult") {
383
+ const command = this.outbox.get(operation.commandId) ?? this.base.outbox.get(operation.commandId);
384
+ if (!command)
385
+ return;
386
+ if (operation.state === "confirmed")
387
+ this.deleteOutbox.add(command.commandId);
388
+ else
389
+ this.outbox.set(command.commandId, { ...command, state: operation.state, attempts: command.attempts + (operation.state === "sending" ? 1 : 0) });
390
+ const message = command.messageId && this.message(command.messageId);
391
+ if (message && command.kind === "message")
392
+ this.setMessage({ ...message, sendStatus: operation.state === "confirmed" ? "sent" : operation.state === "failed" ? "failed" : "sending" });
393
+ return;
394
+ }
395
+ const thread = this.thread(operation.threadId);
396
+ if (!thread || thread.status !== "ready")
397
+ throw Error("PROFILE_THREAD_NOT_READY");
398
+ const grouped = new Map();
399
+ for (const id of new Set(operation.messageIds)) {
400
+ const message = this.message(id);
401
+ if (!message || message.threadId !== thread.threadId || message.readPolicy === "discussion" || this.read(message))
402
+ continue;
403
+ if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
404
+ continue;
405
+ const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
406
+ if (operation.policy === "played" || !message.sourceSeq)
407
+ group.explicitReadMessageIds.push(id);
408
+ else if (message.sourceSeq > group.readThroughSeq) {
409
+ group.readThroughSeq = message.sourceSeq;
410
+ group.readThroughMessageId = message.messageId;
411
+ }
412
+ grouped.set(message.sourceThreadId, group);
413
+ }
414
+ for (const [sourceId, values] of grouped) {
415
+ const commandId = `${operation.commandId}:${encodeURIComponent(sourceId)}`;
416
+ this.outbox.set(commandId, { commandId, kind: operation.policy === "played" ? "played" : "reading", threadId: thread.threadId,
417
+ createdAt: operation.createdAt, payload: { appId: this.base.identity.appId, profileId: this.base.identity.profileId,
418
+ teamId: thread.teamId, threadId: sourceId, ...(thread.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), ...values }, state: "pending", attempts: 0 });
419
+ this.reading(eventForLocalReading(this.base.identity, sourceId, thread.rootMessageId, values), false);
420
+ }
421
+ }
422
+ add(event) {
423
+ const wire = event.fact;
424
+ if (!wire.messageId || !wire.threadId || !wire.from || !Number.isSafeInteger(wire.seq) || wire.seq < 1 || !["dm", "group"].includes(wire.threadKind))
425
+ throw Error("INVALID_INBOX_MESSAGE");
426
+ if (wire.from !== this.base.identity.profileId && !wire.recipients?.includes(this.base.identity.profileId) && !(wire.threadKind === "dm" && wire.to === this.base.identity.profileId))
427
+ throw Error("INBOX_MESSAGE_INACCESSIBLE");
428
+ let source = this.ensure(wire.threadId, wire.threadKind, { teamId: wire.teamId, internal: { targetId: wire.to } });
429
+ const targetId = wire.threadKind === "dm" && wire.from !== this.base.identity.profileId ? wire.from : wire.to;
430
+ if (source.kind !== wire.threadKind || source.teamId !== wire.teamId || source.internal?.targetId !== targetId) {
431
+ this.putThread({ ...source, kind: wire.threadKind, teamId: wire.teamId, internal: { ...source.internal, targetId } });
432
+ source = this.thread(source.threadId);
433
+ }
434
+ const canonical = source.internal?.assignments?.[wire.threadId];
435
+ const parent = canonical ? this.ensure(canonical, wire.threadKind, { teamId: source.teamId }) : source;
436
+ const body = wire.body;
437
+ if (body?.kind === "group") {
438
+ const controls = { ...parent.internal?.groupControls, [wire.messageId]: wire };
439
+ const group = projectInboxGroup(this.base.identity.appId, wire.to, wire.teamId, Object.values(controls));
440
+ this.putThread({ ...parent, internal: { ...parent.internal, groupControls: controls },
441
+ ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined, status: group.status === "dissolved" ? "unavailable" : "ready" } : {}) });
442
+ return;
443
+ }
444
+ const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
445
+ const recall = body?.kind === "recall" ? body.targetMessageId : body?.content?.recall?.messageId;
446
+ if (reaction || recall) {
447
+ this.control(parent.threadId, wire, reaction, recall);
448
+ return;
449
+ }
450
+ const accepted = event.fact.sourceAcceptedAt ?? event.acceptedAt;
451
+ if (accepted < this.base.windowStart)
452
+ return;
453
+ const existing = this.message(wire.messageId);
454
+ if (existing?.sourceSeq)
455
+ return;
456
+ const root = parent.internal?.messageRoots?.[wire.messageId] ?? messageThreadRoot(body);
457
+ const threadId = existing?.threadId ?? (root ? profileDiscussionId(parent.threadId, root) : parent.threadId);
458
+ this.ensure(threadId, root ? "discussion" : wire.threadKind, root ? { parentThreadId: parent.threadId, rootMessageId: root, teamId: wire.teamId } : {});
459
+ const next = { generation: this.base.current.activeGeneration, messageId: wire.messageId,
460
+ sourceThreadId: wire.threadId, sourceSeq: wire.seq, threadId, orderKey: existing?.orderKey ?? [wire.serverCreatedAt, wire.threadId, wire.seq, wire.messageId],
461
+ from: wire.from, recipients: wire.recipients, content: wire.body, attachmentRefs: [], reactions: existing?.reactions ?? [],
462
+ readPolicy: messageRequiresPlayback(wire.body) ? "explicit" : "visible", mention: messageMentionsProfile(wire.body, this.base.identity.profileId),
463
+ readBy: [...new Set([...(existing?.readBy ?? []), ...(parent.internal?.pendingReceipts?.[wire.messageId] ?? [])])].sort(),
464
+ receiptStatus: existing?.receiptStatus ?? (this.receiptsReady && wire.from === this.base.identity.profileId ? "ready" : "unknown"), sendStatus: wire.from === this.base.identity.profileId ? "sent" : undefined,
465
+ explicitReadingFacts: existing?.explicitReadingFacts ?? [], controlVersions: existing?.controlVersions ?? {}, revision: this.revision };
466
+ next.presentation = projectMessageContent({ ...wire, id: wire.messageId, timestamp: wire.serverCreatedAt });
467
+ this.setMessage(next);
468
+ this.insert(next);
469
+ const command = this.outbox.get(wire.messageId) ?? this.base.outbox.get(wire.messageId);
470
+ if (command?.kind === "message")
471
+ this.deleteOutbox.add(command.commandId);
472
+ if (root) {
473
+ const rootMessage = this.message(root);
474
+ if (rootMessage && rootMessage.discussionThreadId !== threadId)
475
+ this.setMessage({ ...rootMessage, readPolicy: "discussion", discussionThreadId: threadId });
476
+ }
477
+ const existingChild = this.thread(profileDiscussionId(parent.threadId, wire.messageId));
478
+ if (existingChild)
479
+ this.setMessage({ ...this.message(wire.messageId), readPolicy: "discussion", discussionThreadId: existingChild.threadId });
480
+ const pending = parent.internal?.pendingControls?.[wire.messageId];
481
+ if (pending)
482
+ for (const entry of pending) {
483
+ const saved = entry;
484
+ this.control(parent.threadId, saved.wire, saved.reaction, saved.recall);
485
+ }
486
+ }
487
+ control(threadId, wire, reaction, recall) {
488
+ const targetId = recall ?? reaction?.messageId;
489
+ if (typeof targetId !== "string")
490
+ throw Error("INVALID_MESSAGE_CONTROL");
491
+ const target = this.message(targetId);
492
+ if (!target) {
493
+ const thread = this.thread(threadId), entries = thread.internal?.pendingControls?.[targetId] ?? [];
494
+ this.putThread({ ...thread, internal: { ...thread.internal, pendingControls: { ...thread.internal?.pendingControls,
495
+ [targetId]: [...entries, { wire, reaction, recall }] } } });
496
+ return;
497
+ }
498
+ if (recall) {
499
+ if (wire.from === target.from && !target.recalled)
500
+ this.setMessage({ ...target, recalled: true });
501
+ return;
502
+ }
503
+ if (reaction.version !== 1 || typeof reaction.emojiId !== "string" || !Number.isSafeInteger(reaction.revision) || reaction.revision < 1 || typeof reaction.active !== "boolean")
504
+ throw Error("INVALID_MESSAGE_REACTION");
505
+ const key = JSON.stringify(["reaction", wire.from, reaction.emojiId]), previous = target.controlVersions[key];
506
+ const stamp = [reaction.revision, wire.serverCreatedAt, wire.messageId];
507
+ if (typeof previous === "string") {
508
+ const old = JSON.parse(previous);
509
+ if (old[0] > stamp[0] || old[0] === stamp[0] && (old[1] > stamp[1] || old[1] === stamp[1] && old[2] >= stamp[2]))
510
+ return;
511
+ }
512
+ const reactions = target.reactions.filter(row => row.emojiId !== reaction.emojiId);
513
+ const profiles = new Set(target.reactions.find(row => row.emojiId === reaction.emojiId)?.profileIds);
514
+ if (reaction.active)
515
+ profiles.add(wire.from);
516
+ else
517
+ profiles.delete(wire.from);
518
+ if (profiles.size)
519
+ reactions.push({ emojiId: reaction.emojiId, profileIds: [...profiles].sort() });
520
+ this.setMessage({ ...target, reactions, controlVersions: { ...target.controlVersions, [key]: JSON.stringify(stamp) } });
521
+ }
522
+ reading(event, confirmed = true) {
523
+ const data = event.fact;
524
+ if (data.receiptOnly === true) {
525
+ const receipt = validateInboxReceipt(data, this.base.identity.profileId);
526
+ for (const id of receipt.messageIds) {
527
+ const message = this.message(id);
528
+ if (message && message.from !== this.base.identity.profileId)
529
+ throw Error("INVALID_INBOX_RECEIPT_TARGET");
530
+ if (message && !message.readBy.includes(receipt.readerProfileId))
531
+ this.setMessage({ ...message,
532
+ readBy: [...message.readBy, receipt.readerProfileId].sort(), receiptStatus: "ready" });
533
+ else if (!message) {
534
+ const thread = this.ensure(receipt.threadId), readers = thread.internal?.pendingReceipts?.[id] ?? [];
535
+ if (!readers.includes(receipt.readerProfileId))
536
+ this.putThread({ ...thread, internal: { ...thread.internal,
537
+ pendingReceipts: { ...thread.internal?.pendingReceipts, [id]: [...readers, receipt.readerProfileId] } } });
538
+ }
539
+ }
540
+ return;
541
+ }
542
+ if (data.profileId !== this.base.identity.profileId || !data.threadId || !Number.isSafeInteger(data.readThroughSeq) || data.readThroughSeq < 0 || !Array.isArray(data.explicitReadMessageIds))
543
+ throw Error("INVALID_INBOX_READING");
544
+ const id = data.threadRootId ? profileDiscussionId(data.threadId, data.threadRootId) : data.threadId;
545
+ const thread = this.ensure(id, data.threadRootId ? "discussion" : "group", data.threadRootId ? { parentThreadId: data.threadId, rootMessageId: data.threadRootId } : {});
546
+ if (thread.parentThreadId)
547
+ this.ensure(thread.parentThreadId);
548
+ const sourceId = data.threadId, previous = this.source(thread, sourceId);
549
+ const source = { sourceThreadId: sourceId,
550
+ readThroughSeq: Math.max(previous?.readThroughSeq ?? 0, confirmed ? data.readThroughSeq : 0),
551
+ explicitReadMessageIds: [...new Set([...(previous?.explicitReadMessageIds ?? []), ...(confirmed ? data.explicitReadMessageIds : [])])],
552
+ pendingReadThroughSeq: Math.max(previous?.pendingReadThroughSeq ?? 0, confirmed ? 0 : data.readThroughSeq),
553
+ pendingExplicitReadMessageIds: [...new Set([...(previous?.pendingExplicitReadMessageIds ?? []), ...(confirmed ? [] : data.explicitReadMessageIds)])],
554
+ preservedReadMessageIds: previous?.preservedReadMessageIds ?? [], confirmedRevision: confirmed ? event.inboxSeq : previous?.confirmedRevision };
555
+ if (confirmed) {
556
+ if (source.readThroughSeq >= (source.pendingReadThroughSeq ?? 0))
557
+ source.pendingReadThroughSeq = undefined;
558
+ source.pendingExplicitReadMessageIds = source.pendingExplicitReadMessageIds?.filter(id => !source.explicitReadMessageIds.includes(id));
559
+ }
560
+ const next = { ...thread, readingSources: [...thread.readingSources.filter(row => row.sourceThreadId !== sourceId), source] };
561
+ const index = this.readingIndex(id), before = index.summary(thread.readingSources);
562
+ for (const messageId of data.explicitReadMessageIds) {
563
+ const message = this.message(messageId);
564
+ if (message && message.threadId === id && message.sourceThreadId === sourceId)
565
+ index.remove(message);
566
+ }
567
+ const after = index.summary(next.readingSources);
568
+ this.putThread(next);
569
+ this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions);
570
+ }
571
+ organize(event) {
572
+ const data = event.fact;
573
+ if (!data.threadId || !data.rootMessageId || !Array.isArray(data.messageIds) || !Number.isSafeInteger(data.revision))
574
+ throw Error("INVALID_INBOX_ORGANIZATION");
575
+ const parent = this.ensure(data.threadId), old = parent.internal?.organizationRevisions?.[data.rootMessageId] ?? -1;
576
+ if (old >= data.revision)
577
+ return;
578
+ const messageRoots = { ...parent.internal?.messageRoots };
579
+ for (const messageId of data.messageIds)
580
+ if (messageId !== data.rootMessageId)
581
+ messageRoots[messageId] = data.rootMessageId;
582
+ this.putThread({ ...parent, internal: { ...parent.internal, messageRoots, organizationRevisions: { ...parent.internal?.organizationRevisions, [data.rootMessageId]: data.revision } } });
583
+ const id = profileDiscussionId(data.threadId, data.rootMessageId);
584
+ this.ensure(id, "discussion", { parentThreadId: data.threadId, rootMessageId: data.rootMessageId, teamId: parent.teamId });
585
+ const root = this.message(data.rootMessageId);
586
+ if (root)
587
+ this.setMessage({ ...root, readPolicy: "discussion", discussionThreadId: id });
588
+ for (const messageId of data.messageIds) {
589
+ if (messageId === data.rootMessageId)
590
+ continue;
591
+ const message = this.message(messageId);
592
+ if (message)
593
+ this.move(message, id);
594
+ }
595
+ }
596
+ assign(event) {
597
+ const data = event.fact;
598
+ if (!data.sourceThreadId || !data.threadId || !data.teamId)
599
+ throw Error("INVALID_INBOX_ASSIGNMENT");
600
+ const destination = this.ensure(data.threadId, "group", { teamId: data.teamId });
601
+ const source = this.ensure(data.sourceThreadId);
602
+ this.putThread({ ...destination, readingSources: [...destination.readingSources.filter(row => row.sourceThreadId !== source.threadId),
603
+ ...source.readingSources.filter(row => row.sourceThreadId === source.threadId)] });
604
+ for (const window of this.directory(source.threadId).blocks)
605
+ for (const ref of window.refs)
606
+ this.move(this.message(ref.messageId), destination.threadId);
607
+ this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...source.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
608
+ }
609
+ relationship(event) {
610
+ const data = event.fact;
611
+ if (!data.pairId || ![data.actorId, data.targetId].includes(this.base.identity.profileId))
612
+ throw Error("INVALID_INBOX_RELATIONSHIP");
613
+ if (data.threadId)
614
+ this.ensure(data.threadId, "dm", { teamId: data.teamId });
615
+ }
616
+ finish() {
617
+ return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady },
618
+ threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
619
+ outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
620
+ }
621
+ }
622
+ function eventForLocalReading(identity, threadId, root, values) {
623
+ return { inboxSeq: "0", sourceId: "local-reading", acceptedAt: 0, kind: "readingUpdated",
624
+ fact: { appId: identity.appId, profileId: identity.profileId, threadId, ...(root ? { threadRootId: root } : {}), ...values } };
625
+ }
@@ -0,0 +1,17 @@
1
+ import type { ProfileMessage, ProfileMessageRef, ProfileReadingSource } from "./profileStoreTypes.js";
2
+ type Summary = {
3
+ unread: number;
4
+ mentions: number;
5
+ first?: ProfileMessageRef;
6
+ };
7
+ /** Persistent per-source range trees. Cursor advances aggregate whole ranges;
8
+ * they neither scan history nor rewrite a read flag on each Message. */
9
+ export declare class ProfileReadingIndex {
10
+ private sources;
11
+ fork(): ProfileReadingIndex;
12
+ remove(message: ProfileMessage): void;
13
+ upsert(message: ProfileMessage, profileId: string, source?: ProfileReadingSource): void;
14
+ summary(positions: readonly ProfileReadingSource[]): Summary;
15
+ visibleBetween(sourceId: string, low: number, high: number): ProfileMessageRef[];
16
+ }
17
+ export {};