@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.10

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