@pmate/chat-sdk 0.13.0-profile.3 → 0.13.0-profile.5

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;
@@ -133,7 +135,121 @@ export declare class ProfileChat implements Chat {
133
135
  synchronizeReading(): Promise<void>;
134
136
  revokeThread(id: string): Promise<void>;
135
137
  revokeAccess(): Promise<void>;
138
+ /** Call only after a fresh authoritative Team membership check succeeds. */
139
+ grantAccess(expectedAccessRevision: number): Promise<void>;
136
140
  firstUnread(id: string): string | undefined;
141
+ readPage(id: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly Readonly<{
142
+ id: string;
143
+ threadId: string;
144
+ threadRootId?: string;
145
+ timestamp: number;
146
+ from?: string;
147
+ mine: boolean;
148
+ status: "sending" | "sent" | "failed" | "read";
149
+ recalled: boolean;
150
+ unread?: boolean;
151
+ attentionEligible?: boolean;
152
+ reading?: Readonly<{
153
+ seq?: number;
154
+ read: boolean;
155
+ readPolicy: "visible" | "explicit";
156
+ }>;
157
+ reactions: readonly Readonly<{
158
+ emojiId: string;
159
+ userIds: string[];
160
+ mine: boolean;
161
+ }>[];
162
+ kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
163
+ text: string;
164
+ senderName?: string;
165
+ senderAvatar?: string;
166
+ timeLabel?: string;
167
+ file?: import("../fileMetadata.js").ChatFile;
168
+ image?: Readonly<{
169
+ url: string;
170
+ name?: string;
171
+ }>;
172
+ voice?: Readonly<{
173
+ url: string;
174
+ durationMs: number;
175
+ transcript?: string;
176
+ }>;
177
+ quote?: Readonly<{
178
+ messageId?: string;
179
+ senderName: string;
180
+ content: string;
181
+ recalled?: boolean;
182
+ }>;
183
+ attachment?: Readonly<{
184
+ name?: string;
185
+ size?: string;
186
+ }>;
187
+ richContent?: unknown;
188
+ mentions?: readonly import("../index.js").ChatMention[];
189
+ recipientCount?: number;
190
+ system?: Readonly<{
191
+ type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
192
+ title?: string;
193
+ }>;
194
+ }>[];
195
+ getWindowIds(id: string): readonly string[];
196
+ findMessageWindow(id: string, messageId: string): string | undefined;
197
+ readWindow(id: string, windowId: string): readonly Readonly<{
198
+ id: string;
199
+ threadId: string;
200
+ threadRootId?: string;
201
+ timestamp: number;
202
+ from?: string;
203
+ mine: boolean;
204
+ status: "sending" | "sent" | "failed" | "read";
205
+ recalled: boolean;
206
+ unread?: boolean;
207
+ attentionEligible?: boolean;
208
+ reading?: Readonly<{
209
+ seq?: number;
210
+ read: boolean;
211
+ readPolicy: "visible" | "explicit";
212
+ }>;
213
+ reactions: readonly Readonly<{
214
+ emojiId: string;
215
+ userIds: string[];
216
+ mine: boolean;
217
+ }>[];
218
+ kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
219
+ text: string;
220
+ senderName?: string;
221
+ senderAvatar?: string;
222
+ timeLabel?: string;
223
+ file?: import("../fileMetadata.js").ChatFile;
224
+ image?: Readonly<{
225
+ url: string;
226
+ name?: string;
227
+ }>;
228
+ voice?: Readonly<{
229
+ url: string;
230
+ durationMs: number;
231
+ transcript?: string;
232
+ }>;
233
+ quote?: Readonly<{
234
+ messageId?: string;
235
+ senderName: string;
236
+ content: string;
237
+ recalled?: boolean;
238
+ }>;
239
+ attachment?: Readonly<{
240
+ name?: string;
241
+ size?: string;
242
+ }>;
243
+ richContent?: unknown;
244
+ mentions?: readonly import("../index.js").ChatMention[];
245
+ recipientCount?: number;
246
+ system?: Readonly<{
247
+ type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
248
+ title?: string;
249
+ }>;
250
+ }>[];
251
+ subscribeWindowList(id: string, listener: () => void): () => void;
252
+ subscribeWindow(id: string, windowId: string, listener: () => void): () => void;
137
253
  sharedTransport(): {
138
254
  sendPrepared: (wire: ChatRuntimeMessage) => Promise<ChatRuntimeMessage>;
139
255
  };
@@ -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 (!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; }
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) {
@@ -327,10 +353,34 @@ export class ProfileChat {
327
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); }
328
354
  synchronizeReading() { return this.host.synchronize(); }
329
355
  revokeThread(id) { return this.host.submit({ type: "revoke", threadId: this.key(id) }, true); }
330
- async revokeAccess() { for (const thread of this.host.memory.getThreadList())
331
- if (thread.teamId === this.teamId)
332
- await this.revokeThread(thread.threadId); }
333
- firstUnread(id) { return this.thread(id)?.firstUnreadMessageId; }
356
+ revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
357
+ /** Call only after a fresh authoritative Team membership check succeeds. */
358
+ grantAccess(expectedAccessRevision) { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: true, expectedAccessRevision }, true); }
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;
@@ -38,14 +38,24 @@ export class ProfileCoordinator {
38
38
  }
39
39
  catch { } }
40
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
+ }
41
46
  if (event.data?.profileControl === "progress") {
42
47
  try {
43
48
  this.options.onProgress?.(event.data.progress);
44
49
  }
45
50
  catch { }
46
51
  }
47
- if (event.data?.profileControl === "error")
52
+ if (event.data?.profileControl === "error") {
48
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
+ }
49
59
  };
50
60
  start() {
51
61
  if (this.starting)
@@ -133,9 +143,7 @@ export class ProfileCoordinator {
133
143
  if (!configuration.network)
134
144
  return;
135
145
  configuration.network = { ...configuration.network, token };
136
- if (this.host)
137
- await this.host.update(configuration);
138
- else if (this.starting) {
146
+ if (this.starting) {
139
147
  await this.starting;
140
148
  await this.replica.updateCredentials(token);
141
149
  }
@@ -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[];
@@ -81,7 +81,7 @@ export class ProfileDatabase extends Dexie {
81
81
  throw Error("PROFILE_CURSOR_REGRESSION");
82
82
  const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
83
83
  const localMigrations = batch.localMigrations ? [...new Set([...(current.localMigrations ?? []), ...batch.localMigrations])] : current.localMigrations;
84
- if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations))
84
+ if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision)
85
85
  return current;
86
86
  if (batch.messages?.length)
87
87
  await this.messages.bulkPut(batch.messages);
@@ -99,7 +99,7 @@ export class ProfileDatabase extends Dexie {
99
99
  await this.outbox.bulkDelete(batch.deleteOutbox);
100
100
  if (!Number.isSafeInteger(current.commitRevision + 1))
101
101
  throw Error("PROFILE_REVISION_EXHAUSTED");
102
- const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
102
+ const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
103
103
  await this.inboxState.put(next);
104
104
  return next;
105
105
  });
@@ -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,9 @@ export declare class ProfileMemoryStore {
47
56
  };
48
57
  getThread(threadId: string): ProfileThread | undefined;
49
58
  getMessage(messageId: string): ProfileMessage | undefined;
59
+ getAccessRevision(): number;
60
+ isTeamAvailable(teamId: string | undefined): boolean;
61
+ isThreadAvailable(threadId: string): boolean;
50
62
  getPresentedMessage(messageId: string): Readonly<{
51
63
  id: string;
52
64
  threadId: string;
@@ -105,6 +117,14 @@ export declare class ProfileMemoryStore {
105
117
  subscribeThreadList: (listener: () => void) => () => void;
106
118
  subscribeMessages(listener: (messages: readonly ProfileMessage[]) => void): () => void;
107
119
  subscribeThread(threadId: string, listener: () => void): () => void;
120
+ private windowKey;
121
+ private installWindow;
122
+ getWindowIds(threadId: string): readonly string[];
123
+ findMessageWindow(threadId: string, messageId: string): string | undefined;
124
+ readPresentedWindow(threadId: string, windowId: string): readonly ChatMessage[];
125
+ subscribeWindow(threadId: string, windowId: string, listener: () => void): () => void;
126
+ subscribeWindowList(threadId: string, listener: () => void): () => void;
127
+ private subscribeKey;
108
128
  restore(snapshot: ProfileSnapshot): void;
109
129
  apply(delta: ProfileDelta): void;
110
130
  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,16 @@ 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
+ getAccessRevision() { return this.current?.teamAccessRevision ?? 0; }
51
+ isTeamAvailable(teamId) { return !teamId || !this.current?.revokedTeamIds?.includes(teamId); }
52
+ isThreadAvailable(threadId) {
53
+ const thread = this.threads.get(threadId);
54
+ return thread?.status === "ready" && this.isTeamAvailable(thread.teamId) && (!thread.parentThreadId || this.threads.get(thread.parentThreadId)?.status === "ready" && this.isTeamAvailable(this.threads.get(thread.parentThreadId)?.teamId));
55
+ }
56
+ getPresentedMessage(messageId) {
57
+ const message = this.entities.get(messageId);
58
+ return message && this.isThreadAvailable(message.threadId) ? this.presented.get(messageId) : undefined;
59
+ }
42
60
  getThreadList = () => this.list;
43
61
  subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
44
62
  subscribeMessages(listener) { this.messageListeners.add(listener); return () => { this.messageListeners.delete(listener); }; }
@@ -52,6 +70,65 @@ export class ProfileMemoryStore {
52
70
  return () => { listeners.delete(listener); if (!listeners.size)
53
71
  this.listeners.delete(threadId); };
54
72
  }
73
+ windowKey(threadId, windowId) { return JSON.stringify([threadId, windowId]); }
74
+ installWindow(window) {
75
+ const key = this.windowKey(window.threadId, window.windowId);
76
+ for (const ref of this.windowRows.get(key)?.refs ?? [])
77
+ if (this.messageWindows.get(ref.messageId) === key)
78
+ this.messageWindows.delete(ref.messageId);
79
+ this.windowRows.set(key, window);
80
+ for (const ref of window.refs)
81
+ this.messageWindows.set(ref.messageId, key);
82
+ this.windowPages.delete(key);
83
+ this.dirtyWindows.add(key);
84
+ }
85
+ getWindowIds(threadId) {
86
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
87
+ throw Error("PROFILE_THREAD_NOT_READY");
88
+ return this.windowIds.get(threadId) ?? this.emptyWindowIds;
89
+ }
90
+ findMessageWindow(threadId, messageId) {
91
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
92
+ throw Error("PROFILE_THREAD_NOT_READY");
93
+ const key = this.messageWindows.get(messageId);
94
+ const window = key ? this.windowRows.get(key) : undefined;
95
+ return window?.threadId === threadId ? window.windowId : undefined;
96
+ }
97
+ readPresentedWindow(threadId, windowId) {
98
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
99
+ throw Error("PROFILE_THREAD_NOT_READY");
100
+ const key = this.windowKey(threadId, windowId);
101
+ const cached = this.windowPages.get(key);
102
+ if (cached)
103
+ return cached;
104
+ const window = this.windowRows.get(key);
105
+ if (!window)
106
+ throw Error("PROFILE_WINDOW_UNAVAILABLE");
107
+ const page = window.refs.map(ref => {
108
+ const message = this.presented.get(ref.messageId);
109
+ if (!message)
110
+ throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
111
+ return message;
112
+ });
113
+ this.windowPages.set(key, page);
114
+ return page;
115
+ }
116
+ subscribeWindow(threadId, windowId, listener) {
117
+ return this.subscribeKey(this.windowListeners, this.windowKey(threadId, windowId), listener);
118
+ }
119
+ subscribeWindowList(threadId, listener) {
120
+ return this.subscribeKey(this.windowListListeners, threadId, listener);
121
+ }
122
+ subscribeKey(map, key, listener) {
123
+ let listeners = map.get(key);
124
+ if (!listeners) {
125
+ listeners = new Set();
126
+ map.set(key, listeners);
127
+ }
128
+ listeners.add(listener);
129
+ return () => { listeners.delete(listener); if (!listeners.size)
130
+ map.delete(key); };
131
+ }
55
132
  restore(snapshot) {
56
133
  const generation = snapshot.current.activeGeneration;
57
134
  if (snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
@@ -78,6 +155,14 @@ export class ProfileMemoryStore {
78
155
  }
79
156
  // Install only after complete validation: a bad handoff retains the old view.
80
157
  const affected = new Set([...this.threads.keys(), ...threads.keys()]);
158
+ for (const key of this.windowRows.keys())
159
+ this.dirtyWindows.add(key);
160
+ this.windowRows.clear();
161
+ this.messageWindows.clear();
162
+ this.windowPages.clear();
163
+ this.windowIds.clear();
164
+ for (const window of snapshot.windows)
165
+ this.installWindow(window);
81
166
  this.entities = entities;
82
167
  this.threads = threads;
83
168
  this.directories = directories;
@@ -144,6 +229,7 @@ export class ProfileMemoryStore {
144
229
  for (const thread of delta.threads)
145
230
  this.threads.set(thread.threadId, thread);
146
231
  for (const window of delta.windows) {
232
+ this.installWindow(window);
147
233
  let directory = this.directories.get(window.threadId);
148
234
  if (!directory) {
149
235
  directory = new ProfileWindowDirectory(delta.generation, window.threadId);
@@ -152,6 +238,11 @@ export class ProfileMemoryStore {
152
238
  directory.accept({ windows: [window], windowCount: 0 });
153
239
  affected.add(window.threadId);
154
240
  }
241
+ const accessChanged = new Set([...(this.current.revokedTeamIds ?? []), ...(delta.current.revokedTeamIds ?? [])].filter(id => this.current.revokedTeamIds?.includes(id) !== delta.current.revokedTeamIds?.includes(id)));
242
+ if (accessChanged.size)
243
+ for (const thread of this.threads.values())
244
+ if (thread.teamId && accessChanged.has(thread.teamId))
245
+ affected.add(thread.threadId);
155
246
  this.current = delta.current;
156
247
  for (const message of delta.messages) {
157
248
  this.indexMessage(message);
@@ -159,6 +250,10 @@ export class ProfileMemoryStore {
159
250
  }
160
251
  for (const thread of delta.threads) {
161
252
  const previous = previousThreads.get(thread.threadId);
253
+ if (previous?.status !== thread.status)
254
+ for (const child of this.threads.values())
255
+ if (child.parentThreadId === thread.threadId)
256
+ affected.add(child.threadId);
162
257
  const index = this.readingIndices.get(thread.threadId);
163
258
  for (const source of thread.readingSources) {
164
259
  const before = previous?.readingSources.find(row => row.sourceThreadId === source.sourceThreadId);
@@ -185,7 +280,7 @@ export class ProfileMemoryStore {
185
280
  }
186
281
  }
187
282
  }
188
- this.publish(affected, delta.threads.length > 0);
283
+ this.publish(affected, delta.threads.length > 0 || accessChanged.size > 0);
189
284
  if (added.length)
190
285
  for (const listener of this.messageListeners)
191
286
  this.notify(() => listener(added));
@@ -200,8 +295,8 @@ export class ProfileMemoryStore {
200
295
  const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
201
296
  const mine = message.from === this.profileId;
202
297
  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 ||
298
+ const read = message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
299
+ mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
205
300
  source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
206
301
  policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
207
302
  const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
@@ -215,8 +310,39 @@ export class ProfileMemoryStore {
215
310
  readPolicy: policy === "visible" ? "visible" : "explicit" },
216
311
  reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
217
312
  this.presented.set(message.messageId, value);
313
+ const key = this.messageWindows.get(message.messageId);
314
+ if (key) {
315
+ this.windowPages.delete(key);
316
+ this.dirtyWindows.add(key);
317
+ }
218
318
  }
219
319
  publish(affected, directoryChanged) {
320
+ const changedLists = new Set();
321
+ for (const threadId of affected) {
322
+ const blocks = this.directories.get(threadId)?.blocks ?? [];
323
+ const previous = this.windowIds.get(threadId);
324
+ // Window sequence and IDs never shift on body/reading updates. Only a
325
+ // newly appended block or a full restoration changes this directory.
326
+ if (!previous || previous.length !== blocks.length) {
327
+ this.windowIds.set(threadId, blocks.map(window => window.windowId));
328
+ changedLists.add(threadId);
329
+ }
330
+ const available = this.isThreadAvailable(threadId);
331
+ if (this.windowAccess.get(threadId) !== available) {
332
+ this.windowAccess.set(threadId, available);
333
+ changedLists.add(threadId);
334
+ for (const block of blocks)
335
+ this.dirtyWindows.add(this.windowKey(threadId, block.windowId));
336
+ }
337
+ }
338
+ const dirtyWindows = this.dirtyWindows;
339
+ this.dirtyWindows = new Set();
340
+ for (const key of dirtyWindows)
341
+ for (const listener of this.windowListeners.get(key) ?? [])
342
+ this.notify(listener);
343
+ for (const thread of changedLists)
344
+ for (const listener of this.windowListListeners.get(thread) ?? [])
345
+ this.notify(listener);
220
346
  for (const thread of affected)
221
347
  this.epochs.set(thread, (this.epochs.get(thread) ?? 0) + 1);
222
348
  // Cached pages live only until that thread changes; no unbounded scroll cache.
@@ -224,7 +350,7 @@ export class ProfileMemoryStore {
224
350
  if (affected.has(JSON.parse(key)[0]))
225
351
  this.pageCache.delete(key);
226
352
  if (directoryChanged) {
227
- this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion")
353
+ this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion" && this.isTeamAvailable(thread.teamId))
228
354
  .sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.threadId.localeCompare(b.threadId));
229
355
  }
230
356
  for (const thread of affected)
@@ -235,7 +361,7 @@ export class ProfileMemoryStore {
235
361
  this.notify(listener);
236
362
  }
237
363
  readPage(threadId, anchor, limit, direction = "older") {
238
- if (this.phase !== "ready" || this.threads.get(threadId)?.status !== "ready")
364
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
239
365
  throw Error("PROFILE_THREAD_NOT_READY");
240
366
  const key = JSON.stringify([threadId, anchor ?? null, limit, direction]), epoch = this.epochs.get(threadId) ?? 0;
241
367
  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);
@@ -196,9 +218,9 @@ export class ProfileOwner {
196
218
  const prepared = this.projection.prepare(events);
197
219
  const committed = await this.options.database.commit({ ...prepared, ownerId: this.lease.ownerId, fence: this.lease.fence,
198
220
  generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
199
- committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations });
221
+ committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
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);
@@ -33,6 +33,15 @@ export type ProfileLocalOperation = {
33
33
  } | {
34
34
  type: "revoke";
35
35
  threadId: string;
36
+ } | {
37
+ type: "teamAccess";
38
+ teamId: string;
39
+ allowed: false;
40
+ } | {
41
+ type: "teamAccess";
42
+ teamId: string;
43
+ allowed: true;
44
+ expectedAccessRevision: number;
36
45
  } | {
37
46
  type: "send";
38
47
  threadId: string;
@@ -74,6 +83,7 @@ export type PreparedProfileProjection = {
74
83
  readingIndices: Map<string, ProfileReadingIndex>;
75
84
  outbox: ProfileOutboxCommand[];
76
85
  deleteOutbox: string[];
86
+ rejected?: readonly (Error | undefined)[];
77
87
  };
78
88
  /** Committed authority for the replay reducer. Drafts contain only changed rows;
79
89
  * failure discards the draft, leaving both entities and indexes untouched. */
@@ -90,7 +100,16 @@ export declare class ProfileProjection {
90
100
  constructor(identity: ProfileIdentity, snapshot: ProfileSnapshot & {
91
101
  outbox?: ProfileOutboxCommand[];
92
102
  }, windowStart: number);
93
- prepare(events: readonly ProfileOperation[]): PreparedProfileProjection;
103
+ prepare(events: readonly ProfileOperation[]): {
104
+ rejected: (Error | undefined)[];
105
+ current: ProfileCurrentState;
106
+ threads: ProfileThread[];
107
+ windows: ProfileWindow[];
108
+ messages: ProfileMessage[];
109
+ readingIndices: Map<string, ProfileReadingIndex>;
110
+ outbox: ProfileOutboxCommand[];
111
+ deleteOutbox: string[];
112
+ };
94
113
  prepareBasis(bootstrap: InboxBootstrap): PreparedProfileProjection;
95
114
  accept(prepared: PreparedProfileProjection): void;
96
115
  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,46 @@ class ProfileProjectionDraft {
118
125
  revision;
119
126
  receiptsReady;
120
127
  localMigrations;
128
+ revokedTeamIds;
129
+ teamAccessRevision;
130
+ readingCommands = new Map();
121
131
  constructor(base) {
122
132
  this.base = base;
123
133
  this.seq = inboxSequence(base.current.committedSeq);
124
134
  this.revision = base.current.commitRevision + 1;
125
135
  this.receiptsReady = base.current.receiptsReady;
126
136
  }
137
+ localAccessError(operation) {
138
+ if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
139
+ return Error("PROFILE_ACCESS_CHECK_STALE");
140
+ if (operation.type !== "send" && operation.type !== "observe")
141
+ return;
142
+ const thread = this.thread(operation.threadId);
143
+ const parentId = thread?.parentThreadId ?? (operation.type === "send" ? operation.parentThreadId : undefined);
144
+ const parent = parentId ? this.thread(parentId) : undefined;
145
+ if ((this.revokedTeamIds ?? this.base.current.revokedTeamIds ?? []).includes((parent ?? thread)?.teamId ?? ""))
146
+ return Error("PROFILE_TEAM_ACCESS_REVOKED");
147
+ if (thread?.status !== "ready" && !(operation.type === "send" && !thread && parent?.status === "ready") || parentId && parent?.status !== "ready")
148
+ return Error("PROFILE_THREAD_NOT_READY");
149
+ if (operation.type === "send") {
150
+ const wire = operation.message, command = operation.command;
151
+ if (!wire || !command || !wire.hash || wire.from !== this.base.identity.profileId || command.messageId !== wire.hash || command.commandId !== wire.hash || command.threadId !== operation.threadId)
152
+ return Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
153
+ const root = messageThreadRoot(wire.body);
154
+ if (!thread && (!parentId || !root || profileDiscussionId(parentId, root) !== operation.threadId))
155
+ return Error("INVALID_DISCUSSION_DESTINATION");
156
+ const destination = parent ?? thread;
157
+ if (destination?.internal?.targetId && destination.internal.targetId !== wire.to)
158
+ return Error("OUTGOING_MESSAGE_DESTINATION_MISMATCH");
159
+ const body = wire.body;
160
+ const scope = body?.content ?? body?.payload;
161
+ if (scope?.appId !== undefined && scope.appId !== this.base.identity.appId || scope?.teamId !== undefined && scope.teamId !== destination?.teamId)
162
+ return Error("OUTGOING_MESSAGE_SCOPE_MISMATCH");
163
+ const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
164
+ 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)))
165
+ return Error("INVALID_MESSAGE_REACTION");
166
+ }
167
+ }
127
168
  message(id) { return this.messages.get(id) ?? this.base.messages.get(id); }
128
169
  thread(id) { return this.threads.get(id) ?? this.base.threads.get(id); }
129
170
  ensure(id, kind = "group", extra = {}) {
@@ -172,10 +213,12 @@ class ProfileProjectionDraft {
172
213
  return first?.messageId;
173
214
  }
174
215
  read(message, thread = this.thread(message.threadId)) {
175
- if (message.from === this.base.identity.profileId || message.recalled)
216
+ if (message.recalled)
176
217
  return true;
177
218
  if (message.readPolicy === "discussion")
178
219
  return this.thread(message.discussionThreadId)?.readingStatus === "read";
220
+ if (message.from === this.base.identity.profileId)
221
+ return true;
179
222
  if (!message.sourceSeq)
180
223
  return false;
181
224
  if (message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId))
@@ -286,6 +329,20 @@ class ProfileProjectionDraft {
286
329
  this.seq = seq;
287
330
  }
288
331
  local(operation) {
332
+ if (operation.type === "teamAccess") {
333
+ if (!operation.teamId)
334
+ throw Error("INVALID_PROFILE_TEAM");
335
+ const revoked = new Set(this.revokedTeamIds ?? this.base.current.revokedTeamIds ?? []);
336
+ if (operation.allowed && !revoked.has(operation.teamId))
337
+ return;
338
+ if (operation.allowed)
339
+ revoked.delete(operation.teamId);
340
+ else
341
+ revoked.add(operation.teamId);
342
+ this.revokedTeamIds = [...revoked].sort();
343
+ this.teamAccessRevision = (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0) + 1;
344
+ return;
345
+ }
289
346
  if (operation.type === "restoreReadingCommand") {
290
347
  const command = operation.command, data = command.payload;
291
348
  if (!["reading", "played"].includes(command.kind) || !command.commandId || data.appId !== this.base.identity.appId || data.profileId !== this.base.identity.profileId)
@@ -439,10 +496,19 @@ class ProfileProjectionDraft {
439
496
  grouped.set(message.sourceThreadId, group);
440
497
  }
441
498
  for (const [sourceId, values] of grouped) {
442
- const commandId = `${operation.commandId}:${encodeURIComponent(sourceId)}`;
499
+ const key = JSON.stringify([sourceId, thread.rootMessageId ?? null]);
500
+ const earlierId = operation.policy === "visible" ? this.readingCommands.get(key) : undefined;
501
+ const earlier = earlierId && !this.deleteOutbox.has(earlierId) ? this.outbox.get(earlierId) : undefined;
502
+ const commandId = earlier?.commandId ?? `${operation.commandId}:${encodeURIComponent(sourceId)}`;
503
+ const previous = earlier?.payload;
504
+ const merged = previous ? { ...values, readThroughSeq: Math.max(previous.readThroughSeq, values.readThroughSeq),
505
+ readThroughMessageId: previous.readThroughSeq >= values.readThroughSeq ? previous.readThroughMessageId : values.readThroughMessageId,
506
+ explicitReadMessageIds: [...new Set([...previous.explicitReadMessageIds, ...values.explicitReadMessageIds])] } : values;
507
+ if (operation.policy === "visible")
508
+ this.readingCommands.set(key, commandId);
443
509
  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 });
510
+ createdAt: earlier?.createdAt ?? operation.createdAt, payload: { appId: this.base.identity.appId, profileId: this.base.identity.profileId,
511
+ teamId: thread.teamId, threadId: sourceId, ...(thread.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), ...merged }, state: "pending", attempts: 0 });
446
512
  this.reading(eventForLocalReading(this.base.identity, sourceId, thread.rootMessageId, values), false);
447
513
  }
448
514
  }
@@ -465,7 +531,8 @@ class ProfileProjectionDraft {
465
531
  const controls = { ...parent.internal?.groupControls, [wire.messageId]: wire };
466
532
  const group = projectInboxGroup(this.base.identity.appId, wire.to, wire.teamId, Object.values(controls));
467
533
  this.putThread({ ...parent, internal: { ...parent.internal, groupControls: controls },
468
- ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined, status: group.status === "dissolved" ? "unavailable" : "ready" } : {}) });
534
+ ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined,
535
+ status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}) });
469
536
  return;
470
537
  }
471
538
  const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
@@ -683,7 +750,7 @@ class ProfileProjectionDraft {
683
750
  }
684
751
  finish() {
685
752
  return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
686
- localMigrations: this.localMigrations ?? this.base.current.localMigrations },
753
+ localMigrations: this.localMigrations ?? this.base.current.localMigrations, revokedTeamIds: this.revokedTeamIds ?? this.base.current.revokedTeamIds, teamAccessRevision: this.teamAccessRevision ?? this.base.current.teamAccessRevision },
687
754
  threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
688
755
  outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
689
756
  }
@@ -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" });
@@ -119,6 +119,8 @@ export type ProfileCurrentState = {
119
119
  commitRevision: number;
120
120
  receiptsReady?: boolean;
121
121
  localMigrations?: string[];
122
+ revokedTeamIds?: string[];
123
+ teamAccessRevision?: number;
122
124
  };
123
125
  export type ProfileWriterLease = {
124
126
  key: "lease";
@@ -160,6 +162,8 @@ export type ProfileWriteBatch = {
160
162
  committedSeq: string;
161
163
  receiptsReady?: boolean;
162
164
  localMigrations?: string[];
165
+ revokedTeamIds?: string[];
166
+ teamAccessRevision?: number;
163
167
  threads?: ProfileThread[];
164
168
  windows?: ProfileWindow[];
165
169
  messages?: ProfileMessage[];
@@ -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.3",
3
+ "version": "0.13.0-profile.5",
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",