@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.91

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 (125) hide show
  1. package/README.md +216 -83
  2. package/lib/advanced.d.ts +10 -0
  3. package/lib/advanced.js +10 -0
  4. package/lib/chat.d.ts +5 -0
  5. package/lib/chat.js +11 -0
  6. package/lib/chatContract.d.ts +158 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +31 -0
  9. package/lib/chatError.js +18 -0
  10. package/lib/chatTypes.d.ts +128 -0
  11. package/lib/chatTypes.js +1 -0
  12. package/lib/commands.d.ts +20 -0
  13. package/lib/commands.js +12 -0
  14. package/lib/components/ChatInputDesktop.js +5 -4
  15. package/lib/components/ChatInputMobile.js +5 -4
  16. package/lib/components/CommandMenu.d.ts +15 -0
  17. package/lib/components/CommandMenu.js +10 -0
  18. package/lib/credentials.d.ts +26 -0
  19. package/lib/credentials.js +110 -0
  20. package/lib/fileMetadata.d.ts +9 -0
  21. package/lib/fileMetadata.js +18 -0
  22. package/lib/framework.d.ts +11 -0
  23. package/lib/framework.js +12 -0
  24. package/lib/history.d.ts +4 -0
  25. package/lib/history.js +8 -0
  26. package/lib/hooks/useChatSnapshot.d.ts +4 -0
  27. package/lib/hooks/useChatSnapshot.js +9 -0
  28. package/lib/hooks/useComposerSuggestions.d.ts +50 -0
  29. package/lib/hooks/useComposerSuggestions.js +70 -0
  30. package/lib/index.d.ts +6 -0
  31. package/lib/index.js +6 -0
  32. package/lib/internal/chatEngine.d.ts +131 -0
  33. package/lib/internal/chatEngine.js +306 -0
  34. package/lib/internal/chatRegistry.d.ts +4 -0
  35. package/lib/internal/chatRegistry.js +4 -0
  36. package/lib/internal/createPublicChat.d.ts +4 -0
  37. package/lib/internal/createPublicChat.js +62 -0
  38. package/lib/messageView.d.ts +6 -0
  39. package/lib/messageView.js +103 -0
  40. package/lib/runtime/batchedReadIndex.d.ts +16 -3
  41. package/lib/runtime/batchedReadIndex.js +50 -4
  42. package/lib/runtime/cachedMessage.d.ts +12 -0
  43. package/lib/runtime/cachedMessage.js +18 -0
  44. package/lib/runtime/chatClient.d.ts +8 -1
  45. package/lib/runtime/chatClient.js +18 -6
  46. package/lib/runtime/chatError.d.ts +5 -0
  47. package/lib/runtime/chatError.js +20 -0
  48. package/lib/runtime/chatSession.d.ts +141 -13
  49. package/lib/runtime/chatSession.js +797 -48
  50. package/lib/runtime/connectivity.d.ts +4 -0
  51. package/lib/runtime/connectivity.js +8 -0
  52. package/lib/runtime/conversationDirectory.d.ts +37 -0
  53. package/lib/runtime/conversationDirectory.js +116 -0
  54. package/lib/runtime/conversationRead.d.ts +14 -0
  55. package/lib/runtime/conversationRead.js +34 -0
  56. package/lib/runtime/conversationReading.d.ts +30 -0
  57. package/lib/runtime/conversationReading.js +47 -0
  58. package/lib/runtime/createChat.d.ts +14 -7
  59. package/lib/runtime/createChat.js +67 -24
  60. package/lib/runtime/durableSender.d.ts +97 -14
  61. package/lib/runtime/durableSender.js +787 -71
  62. package/lib/runtime/groupClient.d.ts +92 -0
  63. package/lib/runtime/groupClient.js +380 -0
  64. package/lib/runtime/groupDenial.d.ts +2 -0
  65. package/lib/runtime/groupDenial.js +4 -0
  66. package/lib/runtime/groupIdentity.d.ts +4 -0
  67. package/lib/runtime/groupIdentity.js +26 -0
  68. package/lib/runtime/inboxClient.d.ts +65 -0
  69. package/lib/runtime/inboxClient.js +268 -0
  70. package/lib/runtime/inboxGroup.d.ts +4 -0
  71. package/lib/runtime/inboxGroup.js +51 -0
  72. package/lib/runtime/inboxStore.d.ts +194 -0
  73. package/lib/runtime/inboxStore.js +329 -0
  74. package/lib/runtime/inboxTransport.d.ts +6 -0
  75. package/lib/runtime/inboxTransport.js +76 -0
  76. package/lib/runtime/index.d.ts +10 -0
  77. package/lib/runtime/index.js +8 -0
  78. package/lib/runtime/indexedDbRecovery.d.ts +6 -0
  79. package/lib/runtime/indexedDbRecovery.js +42 -0
  80. package/lib/runtime/messageClient.d.ts +37 -8
  81. package/lib/runtime/messageClient.js +366 -68
  82. package/lib/runtime/messageControls.d.ts +19 -0
  83. package/lib/runtime/messageControls.js +44 -0
  84. package/lib/runtime/messageDiscussionStore.d.ts +63 -0
  85. package/lib/runtime/messageDiscussionStore.js +147 -0
  86. package/lib/runtime/messageLaunch.d.ts +44 -0
  87. package/lib/runtime/messageLaunch.js +137 -0
  88. package/lib/runtime/messageQuotes.d.ts +3 -0
  89. package/lib/runtime/messageQuotes.js +17 -0
  90. package/lib/runtime/messageReaders.d.ts +5 -1
  91. package/lib/runtime/messageReaders.js +16 -5
  92. package/lib/runtime/messageStore.d.ts +51 -2
  93. package/lib/runtime/messageStore.js +264 -14
  94. package/lib/runtime/messageThread.d.ts +9 -0
  95. package/lib/runtime/messageThread.js +17 -0
  96. package/lib/runtime/messageTimeline.d.ts +51 -0
  97. package/lib/runtime/messageTimeline.js +121 -0
  98. package/lib/runtime/outboxSchema.d.ts +5 -0
  99. package/lib/runtime/outboxSchema.js +59 -0
  100. package/lib/runtime/outgoingContent.d.ts +95 -0
  101. package/lib/runtime/outgoingContent.js +121 -0
  102. package/lib/runtime/readBatchJournal.d.ts +35 -0
  103. package/lib/runtime/readBatchJournal.js +210 -0
  104. package/lib/runtime/readCounts.d.ts +7 -1
  105. package/lib/runtime/readCounts.js +108 -21
  106. package/lib/runtime/readIndex.d.ts +74 -7
  107. package/lib/runtime/readIndex.js +488 -33
  108. package/lib/runtime/readSchema.d.ts +2 -0
  109. package/lib/runtime/readSchema.js +58 -0
  110. package/lib/runtime/readSync.d.ts +8 -0
  111. package/lib/runtime/readSync.js +125 -17
  112. package/lib/runtime/readingClient.d.ts +22 -0
  113. package/lib/runtime/readingClient.js +141 -20
  114. package/lib/runtime/readingContent.d.ts +5 -0
  115. package/lib/runtime/readingContent.js +23 -0
  116. package/lib/runtime/responseCache.d.ts +41 -5
  117. package/lib/runtime/responseCache.js +182 -44
  118. package/lib/runtime/socialReadClient.d.ts +30 -4
  119. package/lib/runtime/socialReadClient.js +34 -8
  120. package/lib/runtime/voiceUpload.d.ts +2 -0
  121. package/lib/runtime/voiceUpload.js +27 -0
  122. package/lib/snapshot.d.ts +36 -0
  123. package/lib/snapshot.js +52 -0
  124. package/lib/types/chatInput.d.ts +3 -0
  125. package/package.json +32 -2
@@ -1,12 +1,48 @@
1
+ import { groupIdCollision } from "./groupIdentity.js";
1
2
  import { Dexie } from "dexie";
3
+ import { validMessageIdentifier } from "./outgoingContent.js";
4
+ import { outboxDatabase, prepareOutboxSchema } from "./outboxSchema.js";
5
+ import { blake3 } from "@noble/hashes/blake3.js";
6
+ import { bytesToHex } from "@noble/hashes/utils.js";
2
7
  import { withChatTeam } from "./teamScope.js";
3
8
  import { messageScopeKey } from "./messageStore.js";
4
9
  /** Persists the exact wire message before sending; retries preserve its hash. */
5
10
  export class DurableChatSender {
6
11
  client;
7
12
  onError;
13
+ options;
8
14
  db;
9
15
  outbox;
16
+ controlRevisions;
17
+ attachments;
18
+ schemaReady;
19
+ attachmentBytes = 0;
20
+ attachmentLeases = new Map();
21
+ epochs;
22
+ uploads = new Set();
23
+ reconciliations = new Set();
24
+ firstDelivery = new Set();
25
+ ioQueue = [];
26
+ ioTimer;
27
+ ioRunning;
28
+ ioCount = 0;
29
+ ioBytes = 0;
30
+ acceptanceQueue = [];
31
+ acceptanceTimer;
32
+ acceptanceRunning;
33
+ acceptanceCount = 0;
34
+ acceptanceBytes = 0;
35
+ uploadTail = Promise.resolve();
36
+ uploadWaiting = 0;
37
+ confirmationQueue = [];
38
+ confirmationTimer;
39
+ confirmationRunning;
40
+ confirmationSize = 0;
41
+ version = 0;
42
+ withdrawn = false;
43
+ revoking;
44
+ channel;
45
+ accepted = new Set();
10
46
  scope;
11
47
  identity;
12
48
  values = new Map();
@@ -14,30 +50,233 @@ export class DurableChatSender {
14
50
  listeners = new Set();
15
51
  running = new Map();
16
52
  closed = false;
53
+ closing = false;
54
+ empty = [];
17
55
  offConnection;
18
56
  ready;
19
57
  constructor(client, scope, onError, options = {}) {
20
58
  this.client = client;
21
59
  this.onError = onError;
60
+ this.options = options;
22
61
  this.scope = messageScopeKey(scope);
23
62
  this.identity = { ...scope };
24
- this.db = new Dexie(options.name ?? "pmate-chat-outbox", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
25
- this.db.version(1).stores({ outbox: "[scope+hash],scope,[scope+threadId]" });
26
- this.outbox = this.db.table("outbox");
27
- this.ready = this.outbox.where("scope").equals(this.scope).toArray().then(records => {
28
- if (this.closed)
29
- return;
30
- records.filter(record => !record.confirmed).forEach(record => this.values.set(record.hash, record));
31
- this.emit();
32
- });
63
+ const factory = options.indexedDB ?? globalThis.indexedDB, name = options.name ?? "pmate-chat-outbox";
64
+ this.schemaReady = prepareOutboxSchema(factory, name);
65
+ this.db = outboxDatabase(factory, name);
66
+ this.outbox = this.db.table("outgoingMessages");
67
+ this.attachments = this.db.table("outgoingAttachments");
68
+ this.controlRevisions = this.db.table("outgoingControls");
69
+ this.epochs = this.db.table("scopeEpochs");
70
+ this.outbox.hook("creating", (_key, row) => { row.pendingState = row.confirmed ? 0 : 1; });
71
+ this.outbox.hook("updating", (changes, _key, row) => ({ pendingState: (Object.hasOwn(changes, "confirmed") ? changes.confirmed : row.confirmed) ? 0 : 1 }));
72
+ this.db.on("versionchange", () => { this.db.close({ disableAutoOpen: false }); return false; });
73
+ this.ready = this.restore();
74
+ void this.ready.catch(() => { });
75
+ if (typeof BroadcastChannel !== "undefined") {
76
+ this.channel = new BroadcastChannel(`pmate-chat-outbox:${this.scope}:${this.db.name}`);
77
+ this.channel.onmessage = event => { if (Number.isSafeInteger(event.data?.version) && event.data.version > this.version)
78
+ this.withdraw(); };
79
+ }
33
80
  this.offConnection = client.watchConnection(state => {
34
81
  if (state === "connected")
35
82
  void this.resume().catch(onError);
36
83
  });
37
84
  }
85
+ /** Read only the selected durable rows, without restoring or delivering an outbox. */
86
+ static async readSelected(scope, threadId, ids, version, options = {}) {
87
+ if (ids.length > 100)
88
+ throw new Error("INVALID_OUTBOX_SELECTION");
89
+ const key = messageScopeKey(scope), factory = options.indexedDB ?? globalThis.indexedDB, name = options.name ?? "pmate-chat-outbox";
90
+ await prepareOutboxSchema(factory, name);
91
+ const db = outboxDatabase(factory, name);
92
+ try {
93
+ return await db.transaction("r", db.table("outgoingMessages"), db.table("scopeEpochs"), async () => {
94
+ if (((await db.table("scopeEpochs").get(key))?.version ?? 0) !== version)
95
+ return [];
96
+ const rows = [];
97
+ for (const id of ids) {
98
+ const row = await db.table("outgoingMessages").get([key, id]);
99
+ rows.push(row ? splitAttachment(row).record : undefined);
100
+ }
101
+ return rows.flatMap(row => row && row.scope === key && row.threadId === threadId && !row.confirmed && (row.accessVersion ?? 0) === version ? [splitAttachment(row).record] : []);
102
+ });
103
+ }
104
+ finally {
105
+ db.close();
106
+ }
107
+ }
108
+ async readAccess() {
109
+ const access = await this.options.access?.();
110
+ if (access && (!Number.isSafeInteger(access.version) || access.version < 0 || typeof access.allowed !== "boolean"))
111
+ throw new Error("INVALID_OUTBOX_ACCESS");
112
+ return access;
113
+ }
114
+ async restore() {
115
+ await this.schemaReady;
116
+ const access = await this.readAccess();
117
+ const loaded = await this.db.transaction("rw", this.outbox, this.epochs, this.attachments, this.controlRevisions, async () => {
118
+ const current = (await this.epochs.get(this.scope))?.version ?? 0;
119
+ const version = access?.version ?? current;
120
+ if (version < current)
121
+ throw new Error("OUTBOX_SCOPE_CHANGED");
122
+ if (version > current) {
123
+ await this.epochs.put({ scope: this.scope, version });
124
+ await this.deleteRows();
125
+ }
126
+ const total = await this.outbox.where("scope").equals(this.scope).count();
127
+ const indexed = await this.outbox.where("[scope+pendingState+hash]").between([this.scope, 0, Dexie.minKey], [this.scope, 1, Dexie.maxKey], true, true).count();
128
+ return { version, advanced: version > current, legacy: total !== indexed };
129
+ });
130
+ this.version = loaded.version;
131
+ if (loaded.advanced)
132
+ this.channel?.postMessage({ version: this.version });
133
+ if (this.closed || this.withdrawn)
134
+ return;
135
+ const current = await this.readAccess();
136
+ if (current && (!current.allowed || current.version !== this.version))
137
+ return;
138
+ if (access?.allowed === false)
139
+ return;
140
+ let after;
141
+ const restored = new Map();
142
+ while (!this.closed && !this.withdrawn) {
143
+ const batch = await this.db.transaction("rw", this.outbox, this.epochs, this.attachments, this.controlRevisions, async () => {
144
+ if (((await this.epochs.get(this.scope))?.version ?? 0) !== this.version)
145
+ throw new Error("OUTBOX_SCOPE_CHANGED");
146
+ const keys = await (loaded.legacy
147
+ ? this.outbox.where("[scope+hash]").between([this.scope, after ?? Dexie.minKey], [this.scope, Dexie.maxKey], after === undefined, true)
148
+ : this.outbox.where("[scope+pendingState+hash]").between([this.scope, 1, after ?? Dexie.minKey], [this.scope, 1, Dexie.maxKey], after === undefined, true)).limit(64).primaryKeys();
149
+ if (!keys.length)
150
+ return { last: undefined, records: [] };
151
+ const last = keys.at(-1)[1];
152
+ // Key-only metadata covers confirmed history without reading wire bodies.
153
+ // Missing metadata identifies rows written by an older SDK after upgrade.
154
+ const confirmed = loaded.legacy ? await this.outbox.where("[scope+pendingState+hash]").between([this.scope, 0, keys[0][1]], [this.scope, 0, last], true, true).primaryKeys() : [];
155
+ const confirmedHashes = new Set(confirmed.map(key => key[1]));
156
+ const needed = keys.filter(key => !confirmedHashes.has(key[1]));
157
+ const records = [], writes = [], payloads = [];
158
+ let bytes = 0, processed = last;
159
+ for (const key of needed) {
160
+ const row = await this.outbox.get(key);
161
+ if (!row)
162
+ continue;
163
+ const size = row.voiceData?.bytes.byteLength ?? row.voiceBlob?.size ?? 0;
164
+ if (records.length && bytes + 2 * size > 16 * 1024 * 1024) {
165
+ processed = records.at(-1).hash;
166
+ break;
167
+ }
168
+ if (!row.confirmed && (row.accessVersion ?? 0) === this.version) {
169
+ const split = splitAttachment(row);
170
+ records.push(split.record);
171
+ bytes += 2 * size;
172
+ if (split.attachment) {
173
+ payloads.push(split.attachment);
174
+ writes.push(split.record);
175
+ }
176
+ else if (row.pendingState !== (row.confirmed ? 0 : 1))
177
+ writes.push({ ...row, pendingState: row.confirmed ? 0 : 1 });
178
+ }
179
+ else if (row.pendingState !== (row.confirmed ? 0 : 1))
180
+ writes.push({ ...row, pendingState: row.confirmed ? 0 : 1 });
181
+ }
182
+ if (payloads.length)
183
+ await this.attachments.bulkPut(payloads);
184
+ if (writes.length)
185
+ await this.outbox.bulkPut(writes);
186
+ return { last: processed, records };
187
+ });
188
+ for (const row of batch.records)
189
+ restored.set(row.hash, row);
190
+ if (batch.last === undefined)
191
+ break;
192
+ after = batch.last;
193
+ // Leave the database transaction before yielding to input/rendering work.
194
+ await new Promise(resolve => setTimeout(resolve, 0));
195
+ }
196
+ if (this.closed || this.withdrawn)
197
+ return;
198
+ const latest = await this.readAccess();
199
+ if (latest && (!latest.allowed || latest.version !== this.version))
200
+ return;
201
+ this.values = restored;
202
+ this.emit();
203
+ }
204
+ async checkAccess() {
205
+ if (this.closed)
206
+ throw new Error("CHAT_SENDER_CLOSED");
207
+ if (this.withdrawn)
208
+ throw new Error("OUTBOX_ACCESS_REVOKED");
209
+ const access = await this.readAccess();
210
+ if (access && access.version !== this.version) {
211
+ this.withdraw();
212
+ throw new Error("OUTBOX_SCOPE_CHANGED");
213
+ }
214
+ if (access && !access.allowed)
215
+ throw new Error("OUTBOX_ACCESS_REVOKED");
216
+ }
217
+ async withEpoch(mode, operation) {
218
+ await this.checkAccess();
219
+ try {
220
+ return await this.db.transaction(mode, this.outbox, this.epochs, this.attachments, this.controlRevisions, async () => {
221
+ if (this.closed || this.withdrawn)
222
+ throw new Error("OUTBOX_ACCESS_REVOKED");
223
+ if (((await this.epochs.get(this.scope))?.version ?? 0) !== this.version)
224
+ throw new Error("OUTBOX_SCOPE_CHANGED");
225
+ return operation();
226
+ });
227
+ }
228
+ catch (error) {
229
+ if (String(error).includes("OUTBOX_SCOPE_CHANGED"))
230
+ this.withdraw();
231
+ throw error;
232
+ }
233
+ }
234
+ async deleteRows() {
235
+ await this.outbox.where("[scope+hash]").between([this.scope, Dexie.minKey], [this.scope, Dexie.maxKey], true, true).delete();
236
+ await this.attachments.where("scope").equals(this.scope).delete();
237
+ await this.controlRevisions.where("scope").equals(this.scope).delete();
238
+ }
239
+ /** Stop disclosure immediately; durable invalidation is coordinated separately. */
240
+ withdraw() {
241
+ this.withdrawn = true;
242
+ this.failIO(new Error("OUTBOX_ACCESS_REVOKED"));
243
+ this.failAcceptances(new Error("OUTBOX_ACCESS_REVOKED"));
244
+ this.failConfirmations(new Error("OUTBOX_ACCESS_REVOKED"));
245
+ this.uploads.forEach(controller => controller.abort());
246
+ this.reconciliations.forEach(controller => controller.abort());
247
+ this.firstDelivery.clear();
248
+ this.attachmentLeases.forEach(release => release());
249
+ this.values.clear();
250
+ this.emit();
251
+ }
252
+ revoke(targetVersion) {
253
+ if (this.closed || this.closing)
254
+ return Promise.reject(new Error("CHAT_SENDER_CLOSED"));
255
+ if (this.revoking)
256
+ return this.revoking;
257
+ this.withdraw();
258
+ return this.revoking = (async () => {
259
+ await this.ready.catch(error => { if (!String(error).includes("OUTBOX_SCOPE_CHANGED"))
260
+ throw error; });
261
+ const version = await this.db.transaction("rw", this.outbox, this.epochs, this.attachments, this.controlRevisions, async () => {
262
+ const current = (await this.epochs.get(this.scope))?.version ?? 0;
263
+ const target = targetVersion ?? this.version + 1;
264
+ if (!Number.isSafeInteger(target) || target < 0)
265
+ throw new Error("INVALID_OUTBOX_EPOCH");
266
+ if (current >= target)
267
+ return current;
268
+ await this.epochs.put({ scope: this.scope, version: target });
269
+ await this.deleteRows();
270
+ return target;
271
+ });
272
+ this.channel?.postMessage({ version });
273
+ })();
274
+ }
38
275
  initialize() { return this.ready; }
39
276
  subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
40
277
  snapshot(threadId) {
278
+ if (this.closed || this.closing || this.withdrawn)
279
+ return this.empty;
41
280
  let snapshot = this.snapshots.get(threadId);
42
281
  if (!snapshot) {
43
282
  snapshot = [...this.values.values()].filter(record => threadId === undefined || record.threadId === threadId);
@@ -50,7 +289,8 @@ export class DurableChatSender {
50
289
  /** Resolves after the exact wire message is durable, independently of network delivery. */
51
290
  async enqueue(threadId, input) {
52
291
  const message = await this.persistOutgoing(threadId, input);
53
- void this.retry(message.hash).catch(error => this.onError(error));
292
+ if (!this.closed && !this.closing && !this.withdrawn)
293
+ void this.retry(message.hash).catch(error => this.onError(error));
54
294
  return message;
55
295
  }
56
296
  /** Compatibility API: resolves only after transport delivery. */
@@ -58,23 +298,155 @@ export class DurableChatSender {
58
298
  const message = await this.persistOutgoing(threadId, input);
59
299
  return this.retry(message.hash);
60
300
  }
61
- async persistOutgoing(threadId, input) {
62
- await this.ready;
63
- if (this.closed)
64
- throw new Error("CHAT_SENDER_CLOSED");
65
- const message = this.client.prepareChat(input.to, withChatTeam(input.body, this.identity.teamId), input.recipients);
66
- if (message.from !== this.identity.profileId)
67
- throw new Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
68
- const record = { scope: this.scope, threadId, hash: message.hash, message, status: "sending" };
69
- await this.outbox.put(record);
70
- if (this.closed)
71
- throw new Error("CHAT_SENDER_CLOSED");
72
- this.values.set(record.hash, record);
73
- this.emit();
74
- return message;
301
+ persistOutgoing(threadId, input) {
302
+ if (this.closed || this.closing || this.withdrawn)
303
+ return Promise.reject(new Error("OUTBOX_ACCESS_REVOKED"));
304
+ if (input.voiceBlob && (!(input.voiceBlob instanceof Blob) || input.voiceBlob.size === 0 || input.voiceBlob.size > 16 * 1024 * 1024))
305
+ return Promise.reject(new Error("INVALID_VOICE_ATTACHMENT"));
306
+ const reactionFloor = input.reactionRevisionFloor;
307
+ if (reactionFloor !== undefined && input.voiceBlob)
308
+ return Promise.reject(new Error("INVALID_MESSAGE_REACTION"));
309
+ if (reactionFloor !== undefined && (!Number.isSafeInteger(reactionFloor) || reactionFloor < 0 || reactionFloor >= Number.MAX_SAFE_INTEGER))
310
+ return Promise.reject(new Error("INVALID_REACTION_REVISION"));
311
+ let bytes;
312
+ try {
313
+ bytes = JSON.stringify([input.to, input.body, input.recipients, this.identity]).length * 3 + 1024 + (input.voiceBlob?.size ?? 0);
314
+ }
315
+ catch (error) {
316
+ return Promise.reject(error);
317
+ }
318
+ if (bytes > 20 * 1024 * 1024)
319
+ return Promise.reject(new Error("OUTBOX_RECORD_TOO_LARGE"));
320
+ if (this.acceptanceCount >= 4096 || this.acceptanceBytes + bytes > 64 * 1024 * 1024)
321
+ return Promise.reject(new Error("OUTBOX_ACCEPTANCE_BACKPRESSURE"));
322
+ this.acceptanceCount++;
323
+ this.acceptanceBytes += bytes;
324
+ const pending = (async () => {
325
+ await this.ready;
326
+ await this.checkAccess();
327
+ const message = this.client.prepareChat(input.to, withChatTeam(input.body, this.identity.teamId), input.recipients);
328
+ if (message.from !== this.identity.profileId)
329
+ throw new Error("OUTGOING_MESSAGE_IDENTITY_MISMATCH");
330
+ if (reactionFloor !== undefined) {
331
+ const body = message.body;
332
+ const reaction = body.kind === "message" ? body.content.reaction : undefined;
333
+ if (body.kind !== "message" || body.content.appId !== this.identity.appId || !reaction || reaction.version !== 1 || !validMessageIdentifier(reaction.messageId) || !validMessageIdentifier(reaction.emojiId) || typeof reaction.active !== "boolean")
334
+ throw new Error("INVALID_MESSAGE_REACTION");
335
+ }
336
+ const command = statefulGroup(message);
337
+ if (command)
338
+ message.hash = commandId(this.scope, this.version, threadId, message);
339
+ if (input.voiceBlob) {
340
+ const body = message.body;
341
+ if (body.kind !== "message" || !validVoice(body.content.voice))
342
+ throw new Error("INVALID_VOICE_ATTACHMENT");
343
+ }
344
+ const record = { ...(input.voiceBlob ? { voiceData: { bytes: await input.voiceBlob.arrayBuffer(), type: input.voiceBlob.type } } : {}), scope: this.scope, threadId, hash: message.hash, message, status: "sending", accessVersion: this.version };
345
+ const durable = await new Promise((resolve, reject) => {
346
+ this.acceptanceQueue.push({ record, reactionFloor, bytes, resolve, reject });
347
+ this.scheduleAcceptances();
348
+ });
349
+ return durable.message;
350
+ })().finally(() => { this.accepted.delete(pending); this.acceptanceCount--; this.acceptanceBytes -= bytes; });
351
+ this.accepted.add(pending);
352
+ return pending;
353
+ }
354
+ scheduleAcceptances() {
355
+ if (this.acceptanceTimer || this.acceptanceRunning || !this.acceptanceQueue.length)
356
+ return;
357
+ this.acceptanceTimer = setTimeout(() => { this.acceptanceTimer = undefined; void this.drainAcceptances(); }, 16);
358
+ }
359
+ failAcceptances(error) {
360
+ clearTimeout(this.acceptanceTimer);
361
+ this.acceptanceTimer = undefined;
362
+ for (const item of this.acceptanceQueue.splice(0))
363
+ item.reject(error);
364
+ }
365
+ drainAcceptances() {
366
+ const task = (async () => {
367
+ let bytes = 0, count = 0, operations = 0;
368
+ for (const item of this.acceptanceQueue) {
369
+ const size = item.bytes;
370
+ if (operations + (hasVoice(item.record) || item.reactionFloor !== undefined ? 2 : 1) > 128 || (count > 0 && bytes + size > 20 * 1024 * 1024))
371
+ break;
372
+ bytes += size;
373
+ count++;
374
+ operations += hasVoice(item.record) || item.reactionFloor !== undefined ? 2 : 1;
375
+ }
376
+ const batch = this.acceptanceQueue.splice(0, count);
377
+ try {
378
+ const result = await this.withEpoch("rw", async () => {
379
+ const commands = batch.filter(item => statefulGroup(item.record.message));
380
+ const previous = await this.outbox.bulkGet(commands.map(item => [this.scope, item.record.hash]));
381
+ const known = new Map(previous.filter((row) => Boolean(row && (row.accessVersion ?? 0) === this.version)).map(row => [row.hash, row]));
382
+ const writes = [], records = [], revisions = new Map();
383
+ for (const item of batch) {
384
+ let record = item.record;
385
+ if (item.reactionFloor !== undefined) {
386
+ const body = record.message.body;
387
+ const reaction = body.content.reaction;
388
+ const key = [this.scope, record.threadId, reaction.messageId, reaction.emojiId], encoded = JSON.stringify(key);
389
+ const previous = revisions.get(encoded) ?? await this.controlRevisions.get(key);
390
+ const revision = Math.max(item.reactionFloor, previous?.version === this.version ? previous.value : 0) + 1;
391
+ if (!Number.isSafeInteger(revision))
392
+ throw new Error("INVALID_REACTION_REVISION");
393
+ revisions.set(encoded, { scope: this.scope, threadId: record.threadId, target: reaction.messageId, emoji: reaction.emojiId, version: this.version, value: revision });
394
+ record = { ...record, message: { ...record.message, body: { ...body, content: { ...body.content, reaction: { ...reaction, revision } } } } };
395
+ }
396
+ const command = statefulGroup(record.message), old = command ? known.get(record.hash) : undefined;
397
+ if (old) {
398
+ if (old.message.from !== this.identity.profileId || old.message.hash !== record.hash || commandId(this.scope, this.version, record.threadId, old.message) !== record.hash)
399
+ throw new Error("OUTGOING_COMMAND_CONFLICT");
400
+ records.push(old);
401
+ }
402
+ else {
403
+ writes.push(record);
404
+ records.push(record);
405
+ if (command)
406
+ known.set(record.hash, record);
407
+ }
408
+ }
409
+ const split = writes.map(splitAttachment), payloads = split.flatMap(item => item.attachment ? [item.attachment] : []);
410
+ if (payloads.length)
411
+ await this.attachments.bulkPut(payloads);
412
+ if (revisions.size)
413
+ await this.controlRevisions.bulkPut([...revisions.values()]);
414
+ if (split.length)
415
+ await this.outbox.bulkPut(split.map(item => item.record));
416
+ const metadata = new Map(split.map(item => [item.record.hash, item.record]));
417
+ return { writes: split.map(item => item.record), records: records.map(record => metadata.get(record.hash) ?? record) };
418
+ });
419
+ await this.checkAccess();
420
+ for (const record of result.writes)
421
+ if (statefulGroup(record.message))
422
+ this.firstDelivery.add(record.hash);
423
+ let changed = false;
424
+ for (const record of result.records) {
425
+ if (record.confirmed) {
426
+ this.firstDelivery.delete(record.hash);
427
+ changed = this.values.delete(record.hash) || changed;
428
+ }
429
+ else {
430
+ const current = this.values.get(record.hash);
431
+ if (!current || current.status !== record.status || current.accessVersion !== record.accessVersion) {
432
+ this.values.set(record.hash, record);
433
+ changed = true;
434
+ }
435
+ }
436
+ }
437
+ if (changed)
438
+ this.emit();
439
+ batch.forEach((item, index) => item.resolve(result.records[index]));
440
+ }
441
+ catch (error) {
442
+ batch.forEach(item => item.reject(error));
443
+ }
444
+ })().finally(() => { this.acceptanceRunning = undefined; this.scheduleAcceptances(); });
445
+ this.acceptanceRunning = task;
446
+ return task;
75
447
  }
76
448
  retry(hash) {
77
- if (this.closed)
449
+ if (this.closed || this.closing || this.withdrawn)
78
450
  return Promise.reject(new Error("CHAT_SENDER_CLOSED"));
79
451
  const running = this.running.get(hash);
80
452
  if (running)
@@ -85,88 +457,392 @@ export class DurableChatSender {
85
457
  }
86
458
  async transmit(hash) {
87
459
  await this.ready;
88
- const record = await this.outbox.get([this.scope, hash]);
89
- if (!record || this.closed)
460
+ let record = await this.queueIO(hash);
461
+ if (!record || this.closed || this.withdrawn)
90
462
  throw new Error("OUTGOING_MESSAGE_UNAVAILABLE");
91
- if (record.status === "sent" || record.confirmed)
463
+ if (record.status === "sent" || record.confirmed) {
464
+ this.firstDelivery.delete(hash);
92
465
  return record.message;
466
+ }
93
467
  const sending = { ...record, status: "sending" };
94
468
  if (record.status !== "sending") {
95
469
  const latest = await this.save(sending);
96
470
  if (!latest || latest.confirmed || latest.status === "sent")
97
471
  return latest?.message ?? record.message;
98
472
  }
473
+ await this.checkAccess();
99
474
  if (this.values.get(hash)?.status !== "sending") {
100
475
  this.values.set(hash, sending);
101
476
  this.emit();
102
477
  }
478
+ let transmitting = false;
103
479
  try {
480
+ if (statefulGroup(record.message) && !this.firstDelivery.delete(hash)) {
481
+ const confirmed = await this.reconcile(record);
482
+ if (confirmed) {
483
+ await this.confirm([hash]);
484
+ return record.message;
485
+ }
486
+ }
487
+ if (hasVoice(record)) {
488
+ record = await this.prepareVoice(record);
489
+ if (record.confirmed || record.status === "sent")
490
+ return record.message;
491
+ }
492
+ await this.checkAccess();
493
+ if (this.closing)
494
+ throw new Error("CHAT_SENDER_CLOSED");
495
+ transmitting = true;
104
496
  const message = await this.client.sendPrepared(record.message);
105
497
  const sent = { ...record, message, status: "sent" };
106
- const committed = await this.save(sent);
107
- if (!this.closed) {
108
- if (committed?.confirmed || !committed)
109
- this.values.delete(hash);
110
- else
111
- this.values.set(hash, committed);
112
- this.emit();
113
- }
498
+ await this.save(sent);
114
499
  return message;
115
500
  }
116
501
  catch (error) {
117
- if (!this.closed) {
502
+ // A failed delivery can already be durable remotely, including the first
503
+ // lost ACK. Proof recovery never sends a second wire in this attempt.
504
+ if (!groupIdCollision(error) && statefulGroup(record.message) && this.options.reconcile && transmitting && !this.closed && !this.closing && !this.withdrawn) {
505
+ try {
506
+ if (await this.reconcile(record)) {
507
+ await this.confirm([hash]);
508
+ return record.message;
509
+ }
510
+ }
511
+ catch (verificationError) {
512
+ error = new AggregateError([error, verificationError], "OUTBOX_RECONCILIATION_FAILED");
513
+ }
514
+ }
515
+ if (!this.closed && !this.withdrawn && !(this.closing && statefulGroup(record.message))) {
118
516
  const failed = { ...record, status: "failed" };
119
517
  const committed = await this.save(failed);
120
- if (committed?.confirmed || committed?.status === "sent") {
121
- this.values.delete(hash);
122
- this.emit();
518
+ if (committed?.confirmed || committed?.status === "sent")
123
519
  return committed.message;
124
- }
125
- if (committed)
126
- this.values.set(hash, committed);
127
- else
128
- this.values.delete(hash);
129
- this.emit();
130
520
  }
131
521
  throw error;
132
522
  }
133
523
  }
134
- async save(record) {
135
- return this.db.transaction("rw", this.outbox, async () => {
136
- const previous = await this.outbox.get([this.scope, record.hash]);
137
- if (!previous || previous.confirmed || previous.status === "sent")
138
- return previous;
139
- await this.outbox.put(record);
140
- return record;
141
- });
524
+ async reconcile(record) {
525
+ await this.checkAccess();
526
+ if (this.closing || this.closed || this.withdrawn)
527
+ throw new Error("OUTBOX_RECONCILIATION_ABORTED");
528
+ if (!this.options.reconcile)
529
+ throw new Error("OUTBOX_RECONCILIATION_UNAVAILABLE");
530
+ const controller = new AbortController();
531
+ this.reconciliations.add(controller);
532
+ let abort;
533
+ const stopped = new Promise((_, reject) => { abort = () => reject(new Error("OUTBOX_RECONCILIATION_ABORTED")); controller.signal.addEventListener("abort", abort, { once: true }); });
534
+ const timer = setTimeout(() => controller.abort(), 10_000);
535
+ try {
536
+ const confirmed = await Promise.race([this.options.reconcile({ threadId: record.threadId, message: record.message }, controller.signal), stopped]);
537
+ await this.checkAccess();
538
+ if (this.closing || controller.signal.aborted)
539
+ throw new Error("OUTBOX_RECONCILIATION_ABORTED");
540
+ return confirmed;
541
+ }
542
+ finally {
543
+ clearTimeout(timer);
544
+ controller.signal.removeEventListener("abort", abort);
545
+ this.reconciliations.delete(controller);
546
+ }
547
+ }
548
+ /** Only explicit playback/transcription acquires a local payload, never snapshots. */
549
+ async acquireVoice(hash, threadId) {
550
+ await this.ready;
551
+ await this.checkAccess();
552
+ const record = await this.queueIO(hash);
553
+ if (!record || record.threadId !== threadId || !hasVoice(record))
554
+ return undefined;
555
+ const releaseBudget = this.reserveAttachment(record), key = Symbol(hash);
556
+ let url, released = false;
557
+ const release = () => { if (released)
558
+ return; released = true; if (url)
559
+ URL.revokeObjectURL(url); releaseBudget(); this.attachmentLeases.delete(key); };
560
+ this.attachmentLeases.set(key, release);
561
+ try {
562
+ const blob = await this.readVoice(record);
563
+ await this.checkAccess();
564
+ if (released || this.closing)
565
+ throw new Error("CHAT_SENDER_CLOSED");
566
+ url = URL.createObjectURL(blob);
567
+ return { url, release };
568
+ }
569
+ catch (error) {
570
+ release();
571
+ throw error;
572
+ }
573
+ }
574
+ reserveAttachment(record) {
575
+ const size = record.voiceAttachment?.size ?? record.voiceData?.bytes.byteLength ?? record.voiceBlob?.size ?? 0;
576
+ if (!Number.isSafeInteger(size) || size <= 0 || size > 16 * 1024 * 1024)
577
+ throw new Error("INVALID_VOICE_ATTACHMENT");
578
+ // Charge both the native read buffer and Blob construction, including active leases.
579
+ const bytes = 2 * size;
580
+ if (this.attachmentBytes + bytes > 64 * 1024 * 1024)
581
+ throw new Error("VOICE_ATTACHMENT_BACKPRESSURE");
582
+ this.attachmentBytes += bytes;
583
+ let released = false;
584
+ return () => { if (!released) {
585
+ released = true;
586
+ this.attachmentBytes -= bytes;
587
+ } };
588
+ }
589
+ async readVoice(record) {
590
+ const row = await this.withEpoch("r", () => this.attachments.get([this.scope, record.hash]));
591
+ await this.checkAccess();
592
+ if (!row || row.accessVersion !== this.version || row.size !== record.voiceAttachment?.size || row.type !== record.voiceAttachment.type || (row.bytes?.byteLength ?? row.blob?.size) !== row.size)
593
+ throw new Error("VOICE_ATTACHMENT_UNAVAILABLE");
594
+ return row.blob ?? new Blob([row.bytes], { type: row.type });
595
+ }
596
+ async prepareVoice(record) {
597
+ if (this.uploadWaiting >= 32)
598
+ throw new Error("VOICE_UPLOAD_BACKPRESSURE");
599
+ this.uploadWaiting++;
600
+ const previous = this.uploadTail;
601
+ let release;
602
+ this.uploadTail = new Promise(resolve => { release = resolve; });
603
+ try {
604
+ await previous;
605
+ await this.checkAccess();
606
+ if (this.closing)
607
+ throw new Error("CHAT_SENDER_CLOSED");
608
+ const latest = await this.queueIO(record.hash);
609
+ if (!latest)
610
+ throw new Error("OUTGOING_MESSAGE_UNAVAILABLE");
611
+ if (!hasVoice(latest) || latest.confirmed || latest.status === "sent")
612
+ return latest;
613
+ if (!this.options.uploadVoice)
614
+ throw new Error("VOICE_UPLOAD_UNAVAILABLE");
615
+ const release = this.reserveAttachment(latest);
616
+ const controller = new AbortController();
617
+ this.uploads.add(controller);
618
+ const timeout = setTimeout(() => controller.abort(), 30_000);
619
+ let url;
620
+ try {
621
+ const blob = await this.readVoice(latest);
622
+ if (controller.signal.aborted || this.closing)
623
+ throw new Error("CHAT_SENDER_CLOSED");
624
+ url = await this.options.uploadVoice(blob, controller.signal);
625
+ }
626
+ finally {
627
+ release();
628
+ clearTimeout(timeout);
629
+ this.uploads.delete(controller);
630
+ }
631
+ const parsed = new URL(url);
632
+ if (!["https:", "http:"].includes(parsed.protocol) || parsed.username || parsed.password)
633
+ throw new Error("INVALID_VOICE_UPLOAD_URL");
634
+ await this.checkAccess();
635
+ if (this.closing)
636
+ throw new Error("CHAT_SENDER_CLOSED");
637
+ const { voiceBlob: _blob, voiceData: _data, voiceAttachment: _attachment, ...uploaded } = latest;
638
+ const committed = await this.queueIO(record.hash, { ...uploaded, message: withVoiceUrl(latest.message, url) }, true);
639
+ if (!committed)
640
+ throw new Error("OUTGOING_MESSAGE_UNAVAILABLE");
641
+ return committed;
642
+ }
643
+ finally {
644
+ this.uploadWaiting--;
645
+ release();
646
+ }
647
+ }
648
+ save(record) { return this.queueIO(record.hash, record); }
649
+ queueIO(hash, record, uploaded = false) {
650
+ if (this.closed || this.withdrawn)
651
+ return Promise.reject(new Error("OUTBOX_ACCESS_REVOKED"));
652
+ const value = record ?? this.values.get(hash);
653
+ const bytes = value ? JSON.stringify(value.message).length * 3 + (value.voiceData?.bytes.byteLength ?? value.voiceBlob?.size ?? 0) : 0;
654
+ if (bytes > 20 * 1024 * 1024)
655
+ return Promise.reject(new Error("OUTBOX_RECORD_TOO_LARGE"));
656
+ if (this.ioCount >= 4096 || this.ioBytes + bytes > 64 * 1024 * 1024)
657
+ return Promise.reject(new Error("OUTBOX_IO_BACKPRESSURE"));
658
+ this.ioCount++;
659
+ this.ioBytes += bytes;
660
+ return new Promise((resolve, reject) => {
661
+ this.ioQueue.push({ hash, record, uploaded, bytes, resolve, reject });
662
+ this.scheduleIO();
663
+ }).finally(() => { this.ioCount--; this.ioBytes -= bytes; });
664
+ }
665
+ scheduleIO() {
666
+ if (this.ioTimer || this.ioRunning || !this.ioQueue.length)
667
+ return;
668
+ this.ioTimer = setTimeout(() => { this.ioTimer = undefined; void this.drainIO(); }, 16);
669
+ }
670
+ failIO(error) {
671
+ clearTimeout(this.ioTimer);
672
+ this.ioTimer = undefined;
673
+ for (const item of this.ioQueue.splice(0))
674
+ item.reject(error);
675
+ }
676
+ drainIO() {
677
+ const task = (async () => {
678
+ let count = 0, bytes = 0, operations = 0;
679
+ for (const item of this.ioQueue) {
680
+ if (operations + (item.uploaded ? 2 : 1) > 128 || (count > 0 && bytes + item.bytes > 20 * 1024 * 1024))
681
+ break;
682
+ count++;
683
+ bytes += item.bytes;
684
+ operations += item.uploaded ? 2 : 1;
685
+ }
686
+ const batch = this.ioQueue.splice(0, count);
687
+ try {
688
+ const records = await this.withEpoch(batch.some(item => item.record) ? "rw" : "r", async () => {
689
+ const hashes = [...new Set(batch.map(item => item.hash))];
690
+ const rows = await this.outbox.bulkGet(hashes.map(hash => [this.scope, hash]));
691
+ const current = new Map(hashes.map((hash, index) => [hash, rows[index]]));
692
+ const writes = new Map(), result = [];
693
+ for (const item of batch) {
694
+ const previous = current.get(item.hash);
695
+ // Preserve another document's confirmation, sent status or uploaded URL.
696
+ if (item.record && previous && !previous.confirmed && previous.status !== "sent" && !(hasVoice(item.record) && !hasVoice(previous)) && !(item.uploaded && !hasVoice(previous))) {
697
+ current.set(item.hash, item.record);
698
+ writes.set(item.hash, item.record);
699
+ }
700
+ result.push(current.get(item.hash));
701
+ }
702
+ if (writes.size) {
703
+ await this.outbox.bulkPut([...writes.values()]);
704
+ const released = [...writes.values()].filter(record => !hasVoice(record) && hasVoice(rows[hashes.indexOf(record.hash)]));
705
+ if (released.length)
706
+ await this.attachments.bulkDelete(released.map(record => [this.scope, record.hash]));
707
+ }
708
+ return result;
709
+ });
710
+ await this.checkAccess();
711
+ let changed = false;
712
+ batch.forEach((item, index) => {
713
+ if (!item.record)
714
+ return;
715
+ const record = records[index], old = this.values.get(item.hash);
716
+ if (!record || record.confirmed) {
717
+ changed = this.values.delete(item.hash) || changed;
718
+ }
719
+ else if (!old || old.status !== record.status || old.accessVersion !== record.accessVersion || JSON.stringify(old.message) !== JSON.stringify(record.message) || hasVoice(old) !== hasVoice(record)) {
720
+ this.values.set(item.hash, record);
721
+ changed = true;
722
+ }
723
+ });
724
+ if (changed)
725
+ this.emit();
726
+ batch.forEach((item, index) => item.resolve(records[index]));
727
+ }
728
+ catch (error) {
729
+ batch.forEach(item => item.reject(error));
730
+ }
731
+ })().finally(() => { this.ioRunning = undefined; this.scheduleIO(); });
732
+ this.ioRunning = task;
733
+ return task;
142
734
  }
143
735
  /** Confirm only after the authoritative message has been durably merged.
144
736
  * A tombstone prevents another tab's late failure from recreating the outbox. */
145
- async confirm(hashes) {
737
+ confirm(hashes) {
146
738
  hashes = [...new Set(hashes)];
147
739
  if (!hashes.length)
740
+ return Promise.resolve();
741
+ if (this.closed || this.closing || this.withdrawn)
742
+ return Promise.reject(new Error("OUTBOX_ACCESS_REVOKED"));
743
+ if (this.confirmationSize + hashes.length > 4096)
744
+ return Promise.reject(new Error("OUTBOX_CONFIRM_BACKPRESSURE"));
745
+ const pending = new Promise((resolve, reject) => this.confirmationQueue.push({ hashes, resolve, reject }));
746
+ this.confirmationSize += hashes.length;
747
+ this.scheduleConfirmations();
748
+ return pending;
749
+ }
750
+ scheduleConfirmations() {
751
+ if (this.confirmationTimer !== undefined || this.confirmationRunning || !this.confirmationQueue.length)
148
752
  return;
149
- await this.ready;
150
- await this.db.transaction("rw", this.outbox, async () => {
151
- const previous = await this.outbox.bulkGet(hashes.map(hash => [this.scope, hash]));
152
- const confirmed = previous.filter((record) => Boolean(record && !record.confirmed)).map(record => ({ ...record, status: "sent", confirmed: true }));
153
- if (confirmed.length)
154
- await this.outbox.bulkPut(confirmed);
753
+ this.confirmationTimer = setTimeout(() => { this.confirmationTimer = undefined; void this.drainConfirmations(); }, 16);
754
+ }
755
+ drainConfirmations() {
756
+ if (this.confirmationRunning)
757
+ return this.confirmationRunning;
758
+ const batch = this.confirmationQueue.splice(0);
759
+ if (!batch.length)
760
+ return Promise.resolve();
761
+ const size = batch.reduce((sum, item) => sum + item.hashes.length, 0);
762
+ return this.confirmationRunning = (async () => {
763
+ let failed = false, error;
764
+ try {
765
+ await this.confirmNow([...new Set(batch.flatMap(item => item.hashes))]);
766
+ }
767
+ catch (reason) {
768
+ failed = true;
769
+ error = reason;
770
+ }
771
+ this.confirmationSize -= size;
772
+ for (const item of batch)
773
+ if (failed)
774
+ item.reject(error);
775
+ else
776
+ item.resolve();
777
+ })().finally(() => {
778
+ this.confirmationRunning = undefined;
779
+ this.scheduleConfirmations();
155
780
  });
781
+ }
782
+ failConfirmations(error) {
783
+ clearTimeout(this.confirmationTimer);
784
+ this.confirmationTimer = undefined;
785
+ for (const item of this.confirmationQueue.splice(0)) {
786
+ this.confirmationSize -= item.hashes.length;
787
+ item.reject(error);
788
+ }
789
+ }
790
+ async flushConfirmations() {
791
+ while (this.confirmationRunning || this.confirmationQueue.length) {
792
+ clearTimeout(this.confirmationTimer);
793
+ this.confirmationTimer = undefined;
794
+ await (this.confirmationRunning ?? this.drainConfirmations());
795
+ }
796
+ }
797
+ async confirmNow(hashes) {
798
+ await this.ready;
156
799
  let changed = false;
157
- for (const hash of hashes)
158
- changed = this.values.delete(hash) || changed;
159
- if (changed)
160
- this.emit();
800
+ try {
801
+ for (let offset = 0; offset < hashes.length;) {
802
+ let end = offset, operations = 0;
803
+ while (end < hashes.length) {
804
+ const known = this.values.get(hashes[end]), cost = known && !hasVoice(known) ? 1 : 2;
805
+ if (operations + cost > 128)
806
+ break;
807
+ operations += cost;
808
+ end++;
809
+ }
810
+ const batch = hashes.slice(offset, end);
811
+ await this.withEpoch("rw", async () => {
812
+ const previous = await this.outbox.bulkGet(batch.map(hash => [this.scope, hash]));
813
+ const confirmed = previous.filter((record) => Boolean(record && !record.confirmed)).map(record => ({ ...record, voiceBlob: undefined, voiceData: undefined, voiceAttachment: undefined, status: "sent", confirmed: true }));
814
+ if (confirmed.length) {
815
+ await this.outbox.bulkPut(confirmed);
816
+ const voices = previous.filter((record) => Boolean(record && hasVoice(record)));
817
+ if (voices.length)
818
+ await this.attachments.bulkDelete(voices.map(record => [this.scope, record.hash]));
819
+ }
820
+ });
821
+ // Retire only committed rows. A later failed transaction leaves the
822
+ // remaining sends retryable, including after a browser restart.
823
+ for (const hash of batch) {
824
+ changed = this.values.delete(hash) || changed;
825
+ }
826
+ offset = end;
827
+ if (offset < hashes.length)
828
+ await new Promise(resolve => setTimeout(resolve, 0));
829
+ }
830
+ }
831
+ finally {
832
+ // One confirmation operation publishes at most once, also on partial
833
+ // failure so consumers see exactly the progress that was committed.
834
+ if (changed)
835
+ this.emit();
836
+ }
161
837
  }
162
838
  async resume() {
163
839
  await this.ready;
164
- if (this.closed)
840
+ if (this.closed || this.closing || this.withdrawn)
165
841
  return;
166
842
  // Only interrupted, unconfirmed sends resume automatically; failed sends require retry.
167
843
  for (const record of this.values.values())
168
844
  if (record.status === "sending") {
169
- if (this.closed)
845
+ if (this.closed || this.withdrawn)
170
846
  return;
171
847
  try {
172
848
  await this.retry(record.hash);
@@ -177,11 +853,51 @@ export class DurableChatSender {
177
853
  }
178
854
  }
179
855
  async close() {
180
- this.closed = true;
856
+ this.closing = true;
857
+ this.attachmentLeases.forEach(release => release());
858
+ this.uploads.forEach(controller => controller.abort());
859
+ this.reconciliations.forEach(controller => controller.abort());
181
860
  this.offConnection();
182
861
  this.listeners.clear();
183
- await this.ready;
184
- await Promise.allSettled([...this.running.values()]);
185
- this.db.close();
862
+ this.channel?.close();
863
+ this.channel = undefined;
864
+ try {
865
+ await this.ready;
866
+ await this.flushConfirmations();
867
+ await Promise.allSettled([...this.accepted, ...this.running.values(), ...(this.revoking ? [this.revoking] : [])]);
868
+ }
869
+ finally {
870
+ this.closed = true;
871
+ this.failConfirmations(new Error("CHAT_SENDER_CLOSED"));
872
+ this.firstDelivery.clear();
873
+ this.attachmentLeases.forEach(release => release());
874
+ this.values.clear();
875
+ this.snapshots.clear();
876
+ this.db.close();
877
+ }
186
878
  }
187
879
  }
880
+ function statefulGroup(message) { const body = message.body; return body?.kind === "group" && (body.action === "groupCreate" || body.action === "groupUpdate" || body.action === "groupDissolve"); }
881
+ function commandId(scope, version, threadId, message) {
882
+ return bytesToHex(blake3(new TextEncoder().encode(JSON.stringify(["chat-command:v1", scope, version, threadId, message.to, ordered(message.body)]))));
883
+ }
884
+ function ordered(value) {
885
+ if (Array.isArray(value))
886
+ return value.map(ordered);
887
+ if (value && typeof value === "object")
888
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, ordered(item)]));
889
+ return value;
890
+ }
891
+ function validVoice(value) { const voice = value; return Boolean(voice && typeof voice.url === "string" && Number.isFinite(voice.durationMs) && voice.durationMs > 0); }
892
+ function withVoiceUrl(message, url) {
893
+ const body = message.body;
894
+ return { ...message, body: { ...body, content: { ...body.content, voice: { ...body.content.voice, url } } } };
895
+ }
896
+ function hasVoice(record) { return Boolean(record && (record.voiceBlob || record.voiceData || record.voiceAttachment)); }
897
+ function splitAttachment(record) {
898
+ const { voiceBlob, voiceData, ...metadata } = record;
899
+ if (!voiceBlob && !voiceData)
900
+ return { record: metadata };
901
+ const size = voiceData?.bytes.byteLength ?? voiceBlob.size, type = voiceData?.type ?? voiceBlob.type;
902
+ return { record: { ...metadata, pendingState: record.confirmed ? 0 : 1, voiceAttachment: { size, type } }, attachment: { scope: record.scope, hash: record.hash, accessVersion: record.accessVersion ?? 0, size, type, ...(voiceData ? { bytes: voiceData.bytes } : { blob: voiceBlob }) } };
903
+ }