@pmate/chat-sdk 0.13.0-profile.2 → 0.13.0-profile.4

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.
@@ -42,6 +42,8 @@ export declare class ProfileChat implements Chat {
42
42
  private key;
43
43
  private thread;
44
44
  private parent;
45
+ private accessError;
46
+ private assertAccessible;
45
47
  private group;
46
48
  private empty;
47
49
  private snapshot;
@@ -134,6 +136,118 @@ export declare class ProfileChat implements Chat {
134
136
  revokeThread(id: string): Promise<void>;
135
137
  revokeAccess(): Promise<void>;
136
138
  firstUnread(id: string): string | undefined;
139
+ readPage(id: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly Readonly<{
140
+ id: string;
141
+ threadId: string;
142
+ threadRootId?: string;
143
+ timestamp: number;
144
+ from?: string;
145
+ mine: boolean;
146
+ status: "sending" | "sent" | "failed" | "read";
147
+ recalled: boolean;
148
+ unread?: boolean;
149
+ attentionEligible?: boolean;
150
+ reading?: Readonly<{
151
+ seq?: number;
152
+ read: boolean;
153
+ readPolicy: "visible" | "explicit";
154
+ }>;
155
+ reactions: readonly Readonly<{
156
+ emojiId: string;
157
+ userIds: string[];
158
+ mine: boolean;
159
+ }>[];
160
+ kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
161
+ text: string;
162
+ senderName?: string;
163
+ senderAvatar?: string;
164
+ timeLabel?: string;
165
+ file?: import("../fileMetadata.js").ChatFile;
166
+ image?: Readonly<{
167
+ url: string;
168
+ name?: string;
169
+ }>;
170
+ voice?: Readonly<{
171
+ url: string;
172
+ durationMs: number;
173
+ transcript?: string;
174
+ }>;
175
+ quote?: Readonly<{
176
+ messageId?: string;
177
+ senderName: string;
178
+ content: string;
179
+ recalled?: boolean;
180
+ }>;
181
+ attachment?: Readonly<{
182
+ name?: string;
183
+ size?: string;
184
+ }>;
185
+ richContent?: unknown;
186
+ mentions?: readonly import("../index.js").ChatMention[];
187
+ recipientCount?: number;
188
+ system?: Readonly<{
189
+ type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
190
+ title?: string;
191
+ }>;
192
+ }>[];
193
+ getWindowIds(id: string): readonly string[];
194
+ findMessageWindow(id: string, messageId: string): string | undefined;
195
+ readWindow(id: string, windowId: string): readonly Readonly<{
196
+ id: string;
197
+ threadId: string;
198
+ threadRootId?: string;
199
+ timestamp: number;
200
+ from?: string;
201
+ mine: boolean;
202
+ status: "sending" | "sent" | "failed" | "read";
203
+ recalled: boolean;
204
+ unread?: boolean;
205
+ attentionEligible?: boolean;
206
+ reading?: Readonly<{
207
+ seq?: number;
208
+ read: boolean;
209
+ readPolicy: "visible" | "explicit";
210
+ }>;
211
+ reactions: readonly Readonly<{
212
+ emojiId: string;
213
+ userIds: string[];
214
+ mine: boolean;
215
+ }>[];
216
+ kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
217
+ text: string;
218
+ senderName?: string;
219
+ senderAvatar?: string;
220
+ timeLabel?: string;
221
+ file?: import("../fileMetadata.js").ChatFile;
222
+ image?: Readonly<{
223
+ url: string;
224
+ name?: string;
225
+ }>;
226
+ voice?: Readonly<{
227
+ url: string;
228
+ durationMs: number;
229
+ transcript?: string;
230
+ }>;
231
+ quote?: Readonly<{
232
+ messageId?: string;
233
+ senderName: string;
234
+ content: string;
235
+ recalled?: boolean;
236
+ }>;
237
+ attachment?: Readonly<{
238
+ name?: string;
239
+ size?: string;
240
+ }>;
241
+ richContent?: unknown;
242
+ mentions?: readonly import("../index.js").ChatMention[];
243
+ recipientCount?: number;
244
+ system?: Readonly<{
245
+ type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
246
+ title?: string;
247
+ }>;
248
+ }>[];
249
+ subscribeWindowList(id: string, listener: () => void): () => void;
250
+ subscribeWindow(id: string, windowId: string, listener: () => void): () => void;
137
251
  sharedTransport(): {
138
252
  sendPrepared: (wire: ChatRuntimeMessage) => Promise<ChatRuntimeMessage>;
139
253
  };
@@ -6,6 +6,7 @@ import { outgoingContent } from "./outgoingContent.js";
6
6
  import { dmThreadId, groupThreadId } from "./thread.js";
7
7
  import { createUniqueGroup } from "./groupIdentity.js";
8
8
  import { messageThreadRoot } from "./messageThread.js";
9
+ import { scopedGroupDenial } from "./groupDenial.js";
9
10
  const sessions = new WeakMap();
10
11
  export function getProfileChatRuntime(chat) {
11
12
  const session = sessions.get(chat);
@@ -59,7 +60,21 @@ export class ProfileChat {
59
60
  throw new ChatError("closed", "Chat session closed"); }
60
61
  key(id) { return this.discussion ? profileDiscussionId(this.discussion.parentId, this.discussion.rootId) : id; }
61
62
  thread(id) { return this.host.memory.getThread(this.key(id)); }
62
- parent(id) { return this.host.memory.getThread(this.discussion?.parentId ?? 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 (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; }
63
78
  group(thread) {
64
79
  const group = thread?.group;
65
80
  if (!group)
@@ -81,14 +96,14 @@ export class ProfileChat {
81
96
  }
82
97
  prepare(id) {
83
98
  const memory = this.host.memory, thread = this.thread(id), parent = this.parent(id);
84
- if (memory.getStatus().phase !== "ready" || !thread && !(this.discussion && parent?.status === "ready"))
85
- return this.snapshot(id);
86
- if (thread?.status === "unavailable" || parent?.status === "unavailable") {
87
- const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
99
+ const error = this.accessError(id);
100
+ if (error) {
88
101
  const view = { ...this.empty(id), status: "error", ready: false, error };
89
102
  this.views.set(id, view);
90
103
  return view;
91
104
  }
105
+ if (memory.getStatus().phase !== "ready" || !thread && !(this.discussion && parent?.status === "ready"))
106
+ return this.snapshot(id);
92
107
  const count = Math.min(this.limits.get(id) ?? 128, thread?.messageCount ?? 0);
93
108
  // Compatibility API accumulates requested pages; readPage remains the
94
109
  // bounded API for page components and never materializes the whole thread.
@@ -216,6 +231,7 @@ export class ProfileChat {
216
231
  return new ProfileChat(this.host, this.teamId, { parentId: threadId, rootId });
217
232
  }
218
233
  async getMessageThreads(id, roots, options = {}) {
234
+ this.assertAccessible(id);
219
235
  options.signal?.throwIfAborted();
220
236
  return { revision: this.host.memory.getStatus().revision ?? 0, items: roots.map(root => {
221
237
  const thread = this.host.memory.getThread(profileDiscussionId(id, root));
@@ -224,7 +240,9 @@ export class ProfileChat {
224
240
  }) };
225
241
  }
226
242
  async sendPrepared(threadId, wire, options = {}, voiceBlob) {
227
- this.assertOpen();
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");
228
246
  const root = messageThreadRoot(wire.body);
229
247
  const destination = this.discussion ? this.key(threadId) : root ? profileDiscussionId(threadId, root) : threadId;
230
248
  await this.host.submit({ type: "send", threadId: destination, parentThreadId: this.discussion?.parentId ?? (root ? threadId : undefined), message: wire, command: {
@@ -236,6 +254,7 @@ export class ProfileChat {
236
254
  return wire;
237
255
  }
238
256
  async sendMessage(id, content, options = {}) {
257
+ this.assertAccessible(id);
239
258
  const parent = this.parent(id);
240
259
  if (!parent?.internal?.targetId)
241
260
  throw new ChatError("unavailable", "Conversation is not prepared");
@@ -251,22 +270,28 @@ export class ProfileChat {
251
270
  const message = this.host.memory.getMessage(messageId);
252
271
  if (!message)
253
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);
254
276
  await this.host.submit({ type: "commandResult", commandId: messageId, state: "pending" }, true);
255
277
  return { id: messageId, timestamp: message.orderKey[0] };
256
278
  }
257
279
  observeMessages(id, ids, event) {
280
+ this.assertAccessible(id);
258
281
  return this.host.submit({ type: "observe", threadId: this.key(id), messageIds: ids, policy: event, commandId: crypto.randomUUID(), createdAt: Date.now() }, event === "played");
259
282
  }
260
283
  async markRead(id) {
284
+ this.assertAccessible(id);
261
285
  if (!this.thread(id))
262
286
  return;
263
287
  await this.host.submit({ type: "observe", threadId: this.key(id), messageIds: [], allVisible: true,
264
288
  policy: "visible", commandId: crypto.randomUUID(), createdAt: Date.now() });
265
289
  }
266
290
  async getReaders(id, messageId, options = {}) {
291
+ this.assertAccessible(id);
267
292
  options.signal?.throwIfAborted();
268
293
  const message = this.host.memory.getMessage(messageId);
269
- 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))
270
295
  throw new ChatError("invalid-input", "Message not found");
271
296
  if (message.receiptStatus !== "ready")
272
297
  throw new ChatError("unavailable", "Reading receipts are not prepared");
@@ -276,9 +301,10 @@ export class ProfileChat {
276
301
  }
277
302
  async watchReaders(_id, _ids, _receiver) { }
278
303
  async getVoiceAttachment(id, messageId, options = {}) {
304
+ this.assertAccessible(id);
279
305
  options.signal?.throwIfAborted();
280
306
  const message = this.host.memory.getMessage(messageId);
281
- 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))
282
308
  throw new ChatError("invalid-input", "Message not found");
283
309
  const url = this.host.memory.getPresentedMessage(messageId)?.voice?.url;
284
310
  if (url)
@@ -289,7 +315,7 @@ export class ProfileChat {
289
315
  const objectUrl = URL.createObjectURL(blob);
290
316
  return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) };
291
317
  }
292
- 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)
293
319
  throw new ChatError("unavailable", "Group is not prepared"); return group; }
294
320
  async refreshGroup(id, options = {}) { await this.host.synchronize(); return this.getGroup(id, options); }
295
321
  async waitGroup(id, previous) {
@@ -330,7 +356,31 @@ export class ProfileChat {
330
356
  async revokeAccess() { for (const thread of this.host.memory.getThreadList())
331
357
  if (thread.teamId === this.teamId)
332
358
  await this.revokeThread(thread.threadId); }
333
- firstUnread(id) { return this.thread(id)?.firstUnreadMessageId; }
359
+ firstUnread(id) { this.assertAccessible(id); return this.thread(id)?.firstUnreadMessageId; }
360
+ readPage(id, anchor, limit, direction = "older") {
361
+ this.assertAccessible(id);
362
+ return this.host.memory.readPresentedPage(this.key(id), anchor, limit, direction);
363
+ }
364
+ getWindowIds(id) {
365
+ this.assertAccessible(id);
366
+ return this.host.memory.getWindowIds(this.key(id));
367
+ }
368
+ findMessageWindow(id, messageId) {
369
+ this.assertAccessible(id);
370
+ return this.host.memory.findMessageWindow(this.key(id), messageId);
371
+ }
372
+ readWindow(id, windowId) {
373
+ this.assertAccessible(id);
374
+ return this.host.memory.readPresentedWindow(this.key(id), windowId);
375
+ }
376
+ subscribeWindowList(id, listener) {
377
+ this.assertAccessible(id);
378
+ return this.host.memory.subscribeWindowList(this.key(id), listener);
379
+ }
380
+ subscribeWindow(id, windowId, listener) {
381
+ this.assertAccessible(id);
382
+ return this.host.memory.subscribeWindow(this.key(id), windowId, listener);
383
+ }
334
384
  sharedTransport() {
335
385
  return { sendPrepared: (wire) => {
336
386
  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 completion = new Promise(resolve => this.entries.push({ event, bytes, accepted: Date.now(), resolve, barrier }));
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[0].accepted + this.options.windowMs);
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,12 +73,15 @@ 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 => entry.resolve());
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
87
  this.retryBatch = batch;
@@ -28,6 +28,7 @@ export declare class ProfileCoordinator {
28
28
  private closed;
29
29
  private needsOwner;
30
30
  private starting?;
31
+ private startupRetry?;
31
32
  get identity(): import("./inboxStore.js").InboxScope;
32
33
  get memory(): import("./profileMemoryStore.js").ProfileMemoryStore;
33
34
  submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
@@ -13,6 +13,7 @@ export class ProfileCoordinator {
13
13
  closed = false;
14
14
  needsOwner = false;
15
15
  starting;
16
+ startupRetry;
16
17
  get identity() { return this.options.configuration.identity; }
17
18
  get memory() { return this.replica.memory; }
18
19
  submit(operation, immediate = false) { return this.replica.submit(operation, immediate); }
@@ -37,14 +38,24 @@ export class ProfileCoordinator {
37
38
  }
38
39
  catch { } }
39
40
  workerMessage = (event) => {
41
+ if (event.data?.profileControl === "credentials" && typeof event.data.token === "string" && event.data.token && event.data.token.length <= 65536) {
42
+ const configuration = this.options.configuration;
43
+ if (configuration.network)
44
+ configuration.network = { ...configuration.network, token: event.data.token };
45
+ }
40
46
  if (event.data?.profileControl === "progress") {
41
47
  try {
42
48
  this.options.onProgress?.(event.data.progress);
43
49
  }
44
50
  catch { }
45
51
  }
46
- if (event.data?.profileControl === "error")
52
+ if (event.data?.profileControl === "error") {
47
53
  this.report(Error(event.data.error));
54
+ if (event.data.error === "PROFILE_WRITER_FENCED") {
55
+ this.needsOwner = true;
56
+ void this.acquire().then(() => this.replica.repair()).catch(error => this.report(error));
57
+ }
58
+ }
48
59
  };
49
60
  start() {
50
61
  if (this.starting)
@@ -54,8 +65,27 @@ export class ProfileCoordinator {
54
65
  return task;
55
66
  }
56
67
  async initialize() {
57
- await this.acquire();
58
- await this.replica.start(false);
68
+ for (;;) {
69
+ if (this.closed)
70
+ throw Error("PROFILE_COORDINATOR_CLOSED");
71
+ try {
72
+ await this.acquire();
73
+ await this.replica.start(false);
74
+ break;
75
+ }
76
+ catch (error) {
77
+ if (this.closed)
78
+ throw Error("PROFILE_COORDINATOR_CLOSED");
79
+ if (!["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE", "PROFILE_WORKER_TIMEOUT"].includes(error?.message))
80
+ throw error;
81
+ this.report(error);
82
+ this.needsOwner = true;
83
+ await new Promise(resolve => {
84
+ const timer = setTimeout(() => { this.startupRetry = undefined; resolve(); }, this.options.retryMs ?? 10000);
85
+ this.startupRetry = { timer, resolve };
86
+ });
87
+ }
88
+ }
59
89
  if (!this.timer)
60
90
  this.timer = setInterval(() => {
61
91
  void this.replica.check().catch(error => {
@@ -113,9 +143,7 @@ export class ProfileCoordinator {
113
143
  if (!configuration.network)
114
144
  return;
115
145
  configuration.network = { ...configuration.network, token };
116
- if (this.host)
117
- await this.host.update(configuration);
118
- else if (this.starting) {
146
+ if (this.starting) {
119
147
  await this.starting;
120
148
  await this.replica.updateCredentials(token);
121
149
  }
@@ -123,6 +151,11 @@ export class ProfileCoordinator {
123
151
  async close() {
124
152
  this.closed = true;
125
153
  clearInterval(this.timer);
154
+ if (this.startupRetry) {
155
+ clearTimeout(this.startupRetry.timer);
156
+ this.startupRetry.resolve();
157
+ this.startupRetry = undefined;
158
+ }
126
159
  this.replica.close();
127
160
  this.channel.removeEventListener("message", this.workerMessage);
128
161
  this.channel.close();
@@ -32,6 +32,9 @@ export declare class ProfileDatabase extends Dexie {
32
32
  windows?: ProfileWindow[];
33
33
  messages?: ProfileMessage[];
34
34
  }): Promise<void>;
35
+ /** Bounded maintenance, fenced in the same transaction as deletion. Building
36
+ * and validated generations remain resumable; outbox is never involved. */
37
+ cleanupGenerations(ownerId: string, fence: number, limit?: number): Promise<number>;
35
38
  restoreGeneration(generation: string): Promise<{
36
39
  build: ProfileGenerationState | undefined;
37
40
  threads: ProfileThread[];
@@ -138,6 +138,41 @@ export class ProfileDatabase extends Dexie {
138
138
  await this.inboxState.put(build);
139
139
  });
140
140
  }
141
+ /** Bounded maintenance, fenced in the same transaction as deletion. Building
142
+ * and validated generations remain resumable; outbox is never involved. */
143
+ async cleanupGenerations(ownerId, fence, limit = 200) {
144
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)
145
+ throw Error("INVALID_PROFILE_CLEANUP_LIMIT");
146
+ return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
147
+ await this.assertWriter(ownerId, fence);
148
+ const current = await this.inboxState.get("current");
149
+ if (!current)
150
+ return 0;
151
+ const builds = (await this.inboxState.toArray()).filter((row) => row.key.startsWith("build:"));
152
+ const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.status === "building" || row.status === "validated").map(row => row.generation)]);
153
+ let removed = 0;
154
+ for (const table of [this.messages, this.windows, this.threads]) {
155
+ if (removed === limit)
156
+ break;
157
+ const keys = await table.where("generation").noneOf([...protectedGenerations]).limit(limit - removed).primaryKeys();
158
+ // Dexie accepts each table's native compound keys. Keep the union of
159
+ // table key types at this maintenance boundary only.
160
+ if (keys.length)
161
+ await table.bulkDelete(keys);
162
+ removed += keys.length;
163
+ }
164
+ if (removed < limit)
165
+ for (const build of builds) {
166
+ if (removed === limit)
167
+ break;
168
+ if (!protectedGenerations.has(build.generation)) {
169
+ await this.inboxState.delete(build.key);
170
+ removed++;
171
+ }
172
+ }
173
+ return removed;
174
+ });
175
+ }
141
176
  async restoreGeneration(generation) {
142
177
  return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState], async () => ({
143
178
  build: await this.inboxState.get(`build:${generation}`),
@@ -27,6 +27,8 @@ export class ProfileInboxFeed {
27
27
  catch { }
28
28
  }
29
29
  async request(action, params = {}) {
30
+ if (!this.options.owner.active)
31
+ throw Error("PROFILE_OWNER_UNAVAILABLE");
30
32
  const identity = this.options.owner.identity;
31
33
  const query = new URLSearchParams({ appId: identity.appId, profileId: identity.profileId, ...params });
32
34
  const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, {
@@ -46,6 +48,8 @@ export class ProfileInboxFeed {
46
48
  synchronize() {
47
49
  if (this.closed)
48
50
  return Promise.reject(Error("INBOX_CLIENT_CLOSED"));
51
+ if (!this.options.owner.active)
52
+ return Promise.reject(Error("PROFILE_OWNER_UNAVAILABLE"));
49
53
  if (this.running)
50
54
  return this.running;
51
55
  const task = this.catchUp().catch(error => { this.progress("error"); throw error; });
@@ -173,6 +177,10 @@ export class ProfileInboxFeed {
173
177
  async tick() {
174
178
  if (this.closed)
175
179
  return;
180
+ if (!this.options.owner.active) {
181
+ this.streamController?.abort();
182
+ return;
183
+ }
176
184
  await this.synchronize();
177
185
  if (this.options.live === false || this.liveTask)
178
186
  return;
@@ -24,6 +24,15 @@ export type ProfileDelta = {
24
24
  export declare class ProfileMemoryStore {
25
25
  private onError;
26
26
  private profileId;
27
+ private windowRows;
28
+ private messageWindows;
29
+ private windowPages;
30
+ private windowAccess;
31
+ private windowIds;
32
+ private windowListeners;
33
+ private windowListListeners;
34
+ private dirtyWindows;
35
+ private readonly emptyWindowIds;
27
36
  private current?;
28
37
  private entities;
29
38
  private threads;
@@ -47,6 +56,7 @@ export declare class ProfileMemoryStore {
47
56
  };
48
57
  getThread(threadId: string): ProfileThread | undefined;
49
58
  getMessage(messageId: string): ProfileMessage | undefined;
59
+ isThreadAvailable(threadId: string): boolean;
50
60
  getPresentedMessage(messageId: string): Readonly<{
51
61
  id: string;
52
62
  threadId: string;
@@ -105,6 +115,14 @@ export declare class ProfileMemoryStore {
105
115
  subscribeThreadList: (listener: () => void) => () => void;
106
116
  subscribeMessages(listener: (messages: readonly ProfileMessage[]) => void): () => void;
107
117
  subscribeThread(threadId: string, listener: () => void): () => void;
118
+ private windowKey;
119
+ private installWindow;
120
+ getWindowIds(threadId: string): readonly string[];
121
+ findMessageWindow(threadId: string, messageId: string): string | undefined;
122
+ readPresentedWindow(threadId: string, windowId: string): readonly ChatMessage[];
123
+ subscribeWindow(threadId: string, windowId: string, listener: () => void): () => void;
124
+ subscribeWindowList(threadId: string, listener: () => void): () => void;
125
+ private subscribeKey;
108
126
  restore(snapshot: ProfileSnapshot): void;
109
127
  apply(delta: ProfileDelta): void;
110
128
  private indexMessage;
@@ -8,6 +8,15 @@ export const PROFILE_PROJECTION_VERSION = 1;
8
8
  export class ProfileMemoryStore {
9
9
  onError;
10
10
  profileId;
11
+ windowRows = new Map();
12
+ messageWindows = new Map();
13
+ windowPages = new Map();
14
+ windowAccess = new Map();
15
+ windowIds = new Map();
16
+ windowListeners = new Map();
17
+ windowListListeners = new Map();
18
+ dirtyWindows = new Set();
19
+ emptyWindowIds = [];
11
20
  current;
12
21
  entities = new Map();
13
22
  threads = new Map();
@@ -38,7 +47,14 @@ export class ProfileMemoryStore {
38
47
  getStatus() { return { phase: this.phase, generation: this.current?.activeGeneration, revision: this.current?.commitRevision }; }
39
48
  getThread(threadId) { return this.threads.get(threadId); }
40
49
  getMessage(messageId) { return this.entities.get(messageId); }
41
- getPresentedMessage(messageId) { return this.presented.get(messageId); }
50
+ isThreadAvailable(threadId) {
51
+ const thread = this.threads.get(threadId);
52
+ return thread?.status === "ready" && (!thread.parentThreadId || this.threads.get(thread.parentThreadId)?.status === "ready");
53
+ }
54
+ getPresentedMessage(messageId) {
55
+ const message = this.entities.get(messageId);
56
+ return message && this.isThreadAvailable(message.threadId) ? this.presented.get(messageId) : undefined;
57
+ }
42
58
  getThreadList = () => this.list;
43
59
  subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
44
60
  subscribeMessages(listener) { this.messageListeners.add(listener); return () => { this.messageListeners.delete(listener); }; }
@@ -52,6 +68,65 @@ export class ProfileMemoryStore {
52
68
  return () => { listeners.delete(listener); if (!listeners.size)
53
69
  this.listeners.delete(threadId); };
54
70
  }
71
+ windowKey(threadId, windowId) { return JSON.stringify([threadId, windowId]); }
72
+ installWindow(window) {
73
+ const key = this.windowKey(window.threadId, window.windowId);
74
+ for (const ref of this.windowRows.get(key)?.refs ?? [])
75
+ if (this.messageWindows.get(ref.messageId) === key)
76
+ this.messageWindows.delete(ref.messageId);
77
+ this.windowRows.set(key, window);
78
+ for (const ref of window.refs)
79
+ this.messageWindows.set(ref.messageId, key);
80
+ this.windowPages.delete(key);
81
+ this.dirtyWindows.add(key);
82
+ }
83
+ getWindowIds(threadId) {
84
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
85
+ throw Error("PROFILE_THREAD_NOT_READY");
86
+ return this.windowIds.get(threadId) ?? this.emptyWindowIds;
87
+ }
88
+ findMessageWindow(threadId, messageId) {
89
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
90
+ throw Error("PROFILE_THREAD_NOT_READY");
91
+ const key = this.messageWindows.get(messageId);
92
+ const window = key ? this.windowRows.get(key) : undefined;
93
+ return window?.threadId === threadId ? window.windowId : undefined;
94
+ }
95
+ readPresentedWindow(threadId, windowId) {
96
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
97
+ throw Error("PROFILE_THREAD_NOT_READY");
98
+ const key = this.windowKey(threadId, windowId);
99
+ const cached = this.windowPages.get(key);
100
+ if (cached)
101
+ return cached;
102
+ const window = this.windowRows.get(key);
103
+ if (!window)
104
+ throw Error("PROFILE_WINDOW_UNAVAILABLE");
105
+ const page = window.refs.map(ref => {
106
+ const message = this.presented.get(ref.messageId);
107
+ if (!message)
108
+ throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
109
+ return message;
110
+ });
111
+ this.windowPages.set(key, page);
112
+ return page;
113
+ }
114
+ subscribeWindow(threadId, windowId, listener) {
115
+ return this.subscribeKey(this.windowListeners, this.windowKey(threadId, windowId), listener);
116
+ }
117
+ subscribeWindowList(threadId, listener) {
118
+ return this.subscribeKey(this.windowListListeners, threadId, listener);
119
+ }
120
+ subscribeKey(map, key, listener) {
121
+ let listeners = map.get(key);
122
+ if (!listeners) {
123
+ listeners = new Set();
124
+ map.set(key, listeners);
125
+ }
126
+ listeners.add(listener);
127
+ return () => { listeners.delete(listener); if (!listeners.size)
128
+ map.delete(key); };
129
+ }
55
130
  restore(snapshot) {
56
131
  const generation = snapshot.current.activeGeneration;
57
132
  if (snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
@@ -78,6 +153,14 @@ export class ProfileMemoryStore {
78
153
  }
79
154
  // Install only after complete validation: a bad handoff retains the old view.
80
155
  const affected = new Set([...this.threads.keys(), ...threads.keys()]);
156
+ for (const key of this.windowRows.keys())
157
+ this.dirtyWindows.add(key);
158
+ this.windowRows.clear();
159
+ this.messageWindows.clear();
160
+ this.windowPages.clear();
161
+ this.windowIds.clear();
162
+ for (const window of snapshot.windows)
163
+ this.installWindow(window);
81
164
  this.entities = entities;
82
165
  this.threads = threads;
83
166
  this.directories = directories;
@@ -144,6 +227,7 @@ export class ProfileMemoryStore {
144
227
  for (const thread of delta.threads)
145
228
  this.threads.set(thread.threadId, thread);
146
229
  for (const window of delta.windows) {
230
+ this.installWindow(window);
147
231
  let directory = this.directories.get(window.threadId);
148
232
  if (!directory) {
149
233
  directory = new ProfileWindowDirectory(delta.generation, window.threadId);
@@ -159,6 +243,10 @@ export class ProfileMemoryStore {
159
243
  }
160
244
  for (const thread of delta.threads) {
161
245
  const previous = previousThreads.get(thread.threadId);
246
+ if (previous?.status !== thread.status)
247
+ for (const child of this.threads.values())
248
+ if (child.parentThreadId === thread.threadId)
249
+ affected.add(child.threadId);
162
250
  const index = this.readingIndices.get(thread.threadId);
163
251
  for (const source of thread.readingSources) {
164
252
  const before = previous?.readingSources.find(row => row.sourceThreadId === source.sourceThreadId);
@@ -200,8 +288,8 @@ export class ProfileMemoryStore {
200
288
  const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
201
289
  const mine = message.from === this.profileId;
202
290
  const policy = message.readPolicy ?? "visible";
203
- const read = mine || message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
204
- message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
291
+ const read = message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
292
+ mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
205
293
  source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
206
294
  policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
207
295
  const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
@@ -215,8 +303,39 @@ export class ProfileMemoryStore {
215
303
  readPolicy: policy === "visible" ? "visible" : "explicit" },
216
304
  reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
217
305
  this.presented.set(message.messageId, value);
306
+ const key = this.messageWindows.get(message.messageId);
307
+ if (key) {
308
+ this.windowPages.delete(key);
309
+ this.dirtyWindows.add(key);
310
+ }
218
311
  }
219
312
  publish(affected, directoryChanged) {
313
+ const changedLists = new Set();
314
+ for (const threadId of affected) {
315
+ const blocks = this.directories.get(threadId)?.blocks ?? [];
316
+ const previous = this.windowIds.get(threadId);
317
+ // Window sequence and IDs never shift on body/reading updates. Only a
318
+ // newly appended block or a full restoration changes this directory.
319
+ if (!previous || previous.length !== blocks.length) {
320
+ this.windowIds.set(threadId, blocks.map(window => window.windowId));
321
+ changedLists.add(threadId);
322
+ }
323
+ const available = this.isThreadAvailable(threadId);
324
+ if (this.windowAccess.get(threadId) !== available) {
325
+ this.windowAccess.set(threadId, available);
326
+ changedLists.add(threadId);
327
+ for (const block of blocks)
328
+ this.dirtyWindows.add(this.windowKey(threadId, block.windowId));
329
+ }
330
+ }
331
+ const dirtyWindows = this.dirtyWindows;
332
+ this.dirtyWindows = new Set();
333
+ for (const key of dirtyWindows)
334
+ for (const listener of this.windowListeners.get(key) ?? [])
335
+ this.notify(listener);
336
+ for (const thread of changedLists)
337
+ for (const listener of this.windowListListeners.get(thread) ?? [])
338
+ this.notify(listener);
220
339
  for (const thread of affected)
221
340
  this.epochs.set(thread, (this.epochs.get(thread) ?? 0) + 1);
222
341
  // Cached pages live only until that thread changes; no unbounded scroll cache.
@@ -235,7 +354,7 @@ export class ProfileMemoryStore {
235
354
  this.notify(listener);
236
355
  }
237
356
  readPage(threadId, anchor, limit, direction = "older") {
238
- if (this.phase !== "ready" || this.threads.get(threadId)?.status !== "ready")
357
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
239
358
  throw Error("PROFILE_THREAD_NOT_READY");
240
359
  const key = JSON.stringify([threadId, anchor ?? null, limit, direction]), epoch = this.epochs.get(threadId) ?? 0;
241
360
  const cached = this.pageCache.get(key);
@@ -1,4 +1,5 @@
1
1
  import { voiceUploader } from "./voiceUpload.js";
2
+ import { profileDiscussionId } from "./profileProjection.js";
2
3
  /** Reads committed commands from owner memory. All status/ACK transitions return
3
4
  * to the same durable queue; network waits never block local event processing. */
4
5
  export class ProfileOutboxDispatcher {
@@ -51,7 +52,12 @@ export class ProfileOutboxDispatcher {
51
52
  while (!this.closed && owner.active) {
52
53
  if (owner.memory.getStatus().phase !== "ready")
53
54
  return;
54
- const command = owner.commands().sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId))[0];
55
+ const command = owner.commands().filter(command => {
56
+ const thread = owner.memory.getThread(command.threadId);
57
+ const canonical = thread?.internal?.assignments?.[thread.threadId] ?? command.threadId;
58
+ const root = command.kind !== "message" ? command.payload.threadRootId : undefined;
59
+ return owner.memory.isThreadAvailable(root ? profileDiscussionId(canonical, root) : canonical);
60
+ }).sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId))[0];
55
61
  if (!command)
56
62
  return;
57
63
  await this.transition(command, "sending");
@@ -11,6 +11,7 @@ export type ProfileOwnerOptions = {
11
11
  onCommitted?: (delta: ProfileDelta) => void;
12
12
  onError?: (error: unknown) => void;
13
13
  windowMs?: number;
14
+ readingWindowMs?: number;
14
15
  retryMs?: number;
15
16
  };
16
17
  /** The durable owner publishes only after commit. Network requests belong to
@@ -23,6 +24,10 @@ export declare class ProfileOwner {
23
24
  private builder;
24
25
  private lease;
25
26
  private timer?;
27
+ private cleanupTimer?;
28
+ private cleanupMore;
29
+ private cleanupTask?;
30
+ private cleanupStopping;
26
31
  private lost;
27
32
  private closed;
28
33
  private committedListeners;
@@ -52,6 +57,7 @@ export declare class ProfileOwner {
52
57
  generationProgress(generation: string): Promise<ProfileGenerationState>;
53
58
  pendingGenerations(): Promise<ProfileGenerationState[]>;
54
59
  activateGeneration(generation: string): Promise<void>;
60
+ private scheduleCleanup;
55
61
  private materializeReadingIntents;
56
62
  private report;
57
63
  private renew;
@@ -13,6 +13,10 @@ export class ProfileOwner {
13
13
  builder;
14
14
  lease;
15
15
  timer;
16
+ cleanupTimer;
17
+ cleanupMore = false;
18
+ cleanupTask;
19
+ cleanupStopping = false;
16
20
  lost = false;
17
21
  closed = false;
18
22
  committedListeners = new Set();
@@ -40,9 +44,11 @@ export class ProfileOwner {
40
44
  owner.builder = new ProfileGenerationBuilder(options.database, () => owner.lease);
41
45
  owner.memory.restore(snapshot);
42
46
  owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
47
+ windowMsForEvent: event => "type" in event && event.type === "observe" && event.policy === "visible" ? options.readingWindowMs ?? 500 : options.windowMs ?? 200,
43
48
  retryMs: options.retryMs, onError: error => owner.report(error) });
44
49
  owner.timer = setInterval(() => { void owner.renew(); }, 10000);
45
50
  await owner.materializeReadingIntents();
51
+ owner.scheduleCleanup();
46
52
  return owner;
47
53
  }
48
54
  catch (error) {
@@ -111,6 +117,20 @@ export class ProfileOwner {
111
117
  throw Error("PROFILE_OWNER_UNAVAILABLE");
112
118
  await this.queue.enqueue({ ownerType: "activate", generation }, 128, true, true);
113
119
  await this.materializeReadingIntents();
120
+ this.scheduleCleanup();
121
+ }
122
+ scheduleCleanup() {
123
+ if (this.cleanupStopping || this.cleanupTimer || !this.active)
124
+ return;
125
+ this.cleanupTimer = setTimeout(() => {
126
+ this.cleanupTimer = undefined;
127
+ if (!this.active)
128
+ return;
129
+ this.cleanupTask = this.queue.enqueue({ ownerType: "cleanup" }, 0, true, true).then(() => {
130
+ if (this.cleanupMore)
131
+ this.scheduleCleanup();
132
+ }).catch(error => this.report(error));
133
+ }, 0);
114
134
  }
115
135
  async materializeReadingIntents() {
116
136
  let pending = [];
@@ -178,7 +198,9 @@ export class ProfileOwner {
178
198
  if (first && "ownerType" in first) {
179
199
  if (events.length !== 1)
180
200
  throw Error("PROFILE_BARRIER_NOT_ISOLATED");
181
- if (first.ownerType === "begin")
201
+ if (first.ownerType === "cleanup")
202
+ this.cleanupMore = await this.options.database.cleanupGenerations(this.lease.ownerId, this.lease.fence) === 200;
203
+ else if (first.ownerType === "begin")
182
204
  await this.builder.begin(first.generation, first.bootstrap, this.current.commitRevision);
183
205
  else if (first.ownerType === "append")
184
206
  await this.builder.append(first.generation, first.events);
@@ -198,7 +220,7 @@ export class ProfileOwner {
198
220
  generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
199
221
  committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations });
200
222
  if (committed.commitRevision === fromRevision)
201
- return;
223
+ return prepared.rejected;
202
224
  prepared.current = committed;
203
225
  const delta = { current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
204
226
  protocolVersion: PROFILE_PROTOCOL_VERSION, generation: committed.activeGeneration,
@@ -213,11 +235,16 @@ export class ProfileOwner {
213
235
  this.memory.restore(this.projection.snapshot());
214
236
  }
215
237
  this.notify(delta);
238
+ return prepared.rejected;
216
239
  }
217
240
  async close() {
218
241
  if (this.closed)
219
242
  return;
220
243
  // The producer must stop intake and await accepted enqueue promises first.
244
+ this.cleanupStopping = true;
245
+ if (this.cleanupTimer)
246
+ clearTimeout(this.cleanupTimer);
247
+ await this.cleanupTask;
221
248
  this.queue.close();
222
249
  this.closed = true;
223
250
  clearInterval(this.timer);
@@ -74,6 +74,7 @@ export type PreparedProfileProjection = {
74
74
  readingIndices: Map<string, ProfileReadingIndex>;
75
75
  outbox: ProfileOutboxCommand[];
76
76
  deleteOutbox: string[];
77
+ rejected?: readonly (Error | undefined)[];
77
78
  };
78
79
  /** Committed authority for the replay reducer. Drafts contain only changed rows;
79
80
  * failure discards the draft, leaving both entities and indexes untouched. */
@@ -90,7 +91,16 @@ export declare class ProfileProjection {
90
91
  constructor(identity: ProfileIdentity, snapshot: ProfileSnapshot & {
91
92
  outbox?: ProfileOutboxCommand[];
92
93
  }, windowStart: number);
93
- prepare(events: readonly ProfileOperation[]): PreparedProfileProjection;
94
+ prepare(events: readonly ProfileOperation[]): {
95
+ rejected: (Error | undefined)[];
96
+ current: ProfileCurrentState;
97
+ threads: ProfileThread[];
98
+ windows: ProfileWindow[];
99
+ messages: ProfileMessage[];
100
+ readingIndices: Map<string, ProfileReadingIndex>;
101
+ outbox: ProfileOutboxCommand[];
102
+ deleteOutbox: string[];
103
+ };
94
104
  prepareBasis(bootstrap: InboxBootstrap): PreparedProfileProjection;
95
105
  accept(prepared: PreparedProfileProjection): void;
96
106
  snapshot(): ProfileSnapshot;
@@ -51,13 +51,20 @@ export class ProfileProjection {
51
51
  }
52
52
  prepare(events) {
53
53
  const draft = new ProfileProjectionDraft(this);
54
- for (const event of events) {
55
- if ("type" in event)
54
+ const rejected = [];
55
+ for (const [index, event] of events.entries()) {
56
+ if ("type" in event) {
57
+ const error = draft.localAccessError(event);
58
+ if (error) {
59
+ rejected[index] = error;
60
+ continue;
61
+ }
56
62
  draft.local(event);
63
+ }
57
64
  else
58
65
  draft.event(event);
59
66
  }
60
- return draft.finish();
67
+ return { ...draft.finish(), rejected };
61
68
  }
62
69
  prepareBasis(bootstrap) {
63
70
  if (bootstrap.appId !== this.identity.appId || bootstrap.profileId !== this.identity.profileId || bootstrap.epoch !== this.current.epoch)
@@ -118,12 +125,40 @@ class ProfileProjectionDraft {
118
125
  revision;
119
126
  receiptsReady;
120
127
  localMigrations;
128
+ readingCommands = new Map();
121
129
  constructor(base) {
122
130
  this.base = base;
123
131
  this.seq = inboxSequence(base.current.committedSeq);
124
132
  this.revision = base.current.commitRevision + 1;
125
133
  this.receiptsReady = base.current.receiptsReady;
126
134
  }
135
+ localAccessError(operation) {
136
+ if (operation.type !== "send" && operation.type !== "observe")
137
+ return;
138
+ const thread = this.thread(operation.threadId);
139
+ const parentId = thread?.parentThreadId ?? (operation.type === "send" ? operation.parentThreadId : undefined);
140
+ const parent = parentId ? this.thread(parentId) : undefined;
141
+ if (thread?.status !== "ready" && !(operation.type === "send" && !thread && parent?.status === "ready") || parentId && parent?.status !== "ready")
142
+ return Error("PROFILE_THREAD_NOT_READY");
143
+ if (operation.type === "send") {
144
+ const wire = operation.message, command = operation.command;
145
+ if (!wire || !command || !wire.hash || wire.from !== this.base.identity.profileId || command.messageId !== wire.hash || command.commandId !== wire.hash || command.threadId !== operation.threadId)
146
+ return Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
147
+ const root = messageThreadRoot(wire.body);
148
+ if (!thread && (!parentId || !root || profileDiscussionId(parentId, root) !== operation.threadId))
149
+ return Error("INVALID_DISCUSSION_DESTINATION");
150
+ const destination = parent ?? thread;
151
+ if (destination?.internal?.targetId && destination.internal.targetId !== wire.to)
152
+ return Error("OUTGOING_MESSAGE_DESTINATION_MISMATCH");
153
+ const body = wire.body;
154
+ const scope = body?.content ?? body?.payload;
155
+ if (scope?.appId !== undefined && scope.appId !== this.base.identity.appId || scope?.teamId !== undefined && scope.teamId !== destination?.teamId)
156
+ return Error("OUTGOING_MESSAGE_SCOPE_MISMATCH");
157
+ const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
158
+ if (reaction && (reaction.version !== 1 || typeof reaction.messageId !== "string" || !reaction.messageId || typeof reaction.emojiId !== "string" || !reaction.emojiId || typeof reaction.active !== "boolean" || operation.preserveWire && (!Number.isSafeInteger(reaction.revision) || reaction.revision < 1)))
159
+ return Error("INVALID_MESSAGE_REACTION");
160
+ }
161
+ }
127
162
  message(id) { return this.messages.get(id) ?? this.base.messages.get(id); }
128
163
  thread(id) { return this.threads.get(id) ?? this.base.threads.get(id); }
129
164
  ensure(id, kind = "group", extra = {}) {
@@ -172,10 +207,12 @@ class ProfileProjectionDraft {
172
207
  return first?.messageId;
173
208
  }
174
209
  read(message, thread = this.thread(message.threadId)) {
175
- if (message.from === this.base.identity.profileId || message.recalled)
210
+ if (message.recalled)
176
211
  return true;
177
212
  if (message.readPolicy === "discussion")
178
213
  return this.thread(message.discussionThreadId)?.readingStatus === "read";
214
+ if (message.from === this.base.identity.profileId)
215
+ return true;
179
216
  if (!message.sourceSeq)
180
217
  return false;
181
218
  if (message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId))
@@ -439,10 +476,19 @@ class ProfileProjectionDraft {
439
476
  grouped.set(message.sourceThreadId, group);
440
477
  }
441
478
  for (const [sourceId, values] of grouped) {
442
- const commandId = `${operation.commandId}:${encodeURIComponent(sourceId)}`;
479
+ const key = JSON.stringify([sourceId, thread.rootMessageId ?? null]);
480
+ const earlierId = operation.policy === "visible" ? this.readingCommands.get(key) : undefined;
481
+ const earlier = earlierId && !this.deleteOutbox.has(earlierId) ? this.outbox.get(earlierId) : undefined;
482
+ const commandId = earlier?.commandId ?? `${operation.commandId}:${encodeURIComponent(sourceId)}`;
483
+ const previous = earlier?.payload;
484
+ const merged = previous ? { ...values, readThroughSeq: Math.max(previous.readThroughSeq, values.readThroughSeq),
485
+ readThroughMessageId: previous.readThroughSeq >= values.readThroughSeq ? previous.readThroughMessageId : values.readThroughMessageId,
486
+ explicitReadMessageIds: [...new Set([...previous.explicitReadMessageIds, ...values.explicitReadMessageIds])] } : values;
487
+ if (operation.policy === "visible")
488
+ this.readingCommands.set(key, commandId);
443
489
  this.outbox.set(commandId, { commandId, kind: operation.policy === "played" ? "played" : "reading", threadId: thread.threadId,
444
- createdAt: operation.createdAt, payload: { appId: this.base.identity.appId, profileId: this.base.identity.profileId,
445
- teamId: thread.teamId, threadId: sourceId, ...(thread.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), ...values }, state: "pending", attempts: 0 });
490
+ createdAt: earlier?.createdAt ?? operation.createdAt, payload: { appId: this.base.identity.appId, profileId: this.base.identity.profileId,
491
+ teamId: thread.teamId, threadId: sourceId, ...(thread.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), ...merged }, state: "pending", attempts: 0 });
446
492
  this.reading(eventForLocalReading(this.base.identity, sourceId, thread.rootMessageId, values), false);
447
493
  }
448
494
  }
@@ -465,7 +511,8 @@ class ProfileProjectionDraft {
465
511
  const controls = { ...parent.internal?.groupControls, [wire.messageId]: wire };
466
512
  const group = projectInboxGroup(this.base.identity.appId, wire.to, wire.teamId, Object.values(controls));
467
513
  this.putThread({ ...parent, internal: { ...parent.internal, groupControls: controls },
468
- ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined, status: group.status === "dissolved" ? "unavailable" : "ready" } : {}) });
514
+ ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined,
515
+ status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}) });
469
516
  return;
470
517
  }
471
518
  const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
@@ -44,13 +44,11 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
44
44
  const controller = new AbortController();
45
45
  const listener = (event) => {
46
46
  const request = event.data;
47
- if (!request || request.scope !== scope || !request.requestId || !request.action)
47
+ if (!request || request.scope !== scope || !request.requestId || !request.action || !owner.active)
48
48
  return;
49
49
  void (async () => {
50
50
  if (request.profileProtocol !== PROFILE_PROTOCOL_VERSION)
51
51
  throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
52
- if (!owner.active)
53
- throw Error("PROFILE_OWNER_UNAVAILABLE");
54
52
  let result;
55
53
  if (request.action === "catchUp") {
56
54
  const deltas = journal.since(request.generation, request.revision, owner.current);
@@ -87,10 +85,10 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
87
85
  }
88
86
  else
89
87
  throw Error("INVALID_PROFILE_REQUEST");
90
- if (active)
88
+ if (active && owner.active)
91
89
  send({ clientId: request.clientId, requestId: request.requestId, result });
92
90
  })().catch(error => {
93
- if (!active)
91
+ if (!active || !owner.active)
94
92
  return;
95
93
  try {
96
94
  send({ clientId: request.clientId, requestId: request.requestId, error: error instanceof Error ? error.message : "PROFILE_REQUEST_FAILED" });
@@ -65,7 +65,12 @@ export function installProfileWorker(port, options = {}) {
65
65
  const report = (error) => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_NETWORK_FAILED" });
66
66
  const endpoint = network.hubHttpUrl.replace(/\/$/, "").replace(/^ws/, "http");
67
67
  const token = () => network.token;
68
- owner.setCredentialUpdater(value => { network = { ...network, token: value }; });
68
+ owner.setCredentialUpdater(value => {
69
+ network = { ...network, token: value };
70
+ const message = { profileControl: "credentials", token: value };
71
+ port.postMessage(message);
72
+ channel?.postMessage(message);
73
+ });
69
74
  connection = new ChatClient({ appId: config.identity.appId, profileId: config.identity.profileId,
70
75
  hubUrl: endpoint.replace(/^http/, "ws"), fetchImpl: options.fetch, getToken: async () => token(),
71
76
  session: { token: token(), identity: { accountId: config.identity.accountId, app: config.identity.appId, profileId: config.identity.profileId } } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.13.0-profile.2",
3
+ "version": "0.13.0-profile.4",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",