@pmate/chat-sdk 0.14.0-seq.0 → 0.14.0-seq.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 (42) hide show
  1. package/README.md +1 -3
  2. package/lib/chatContract.d.ts +2 -0
  3. package/lib/chatTypes.d.ts +3 -0
  4. package/lib/internal/chatEngine.d.ts +3 -7
  5. package/lib/messageView.js +1 -1
  6. package/lib/runtime/activity.d.ts +2 -1
  7. package/lib/runtime/activity.js +4 -1
  8. package/lib/runtime/botAuth.d.ts +1 -0
  9. package/lib/runtime/botAuth.js +1 -0
  10. package/lib/runtime/chatClient.d.ts +2 -0
  11. package/lib/runtime/chatClient.js +38 -7
  12. package/lib/runtime/chatSession.d.ts +2 -0
  13. package/lib/runtime/groupClient.d.ts +2 -0
  14. package/lib/runtime/groupClient.js +5 -1
  15. package/lib/runtime/inboxDeletion.d.ts +7 -0
  16. package/lib/runtime/inboxDeletion.js +21 -0
  17. package/lib/runtime/inboxGroup.js +6 -2
  18. package/lib/runtime/inboxStore.js +33 -3
  19. package/lib/runtime/messageControls.js +6 -3
  20. package/lib/runtime/messageStore.d.ts +1 -0
  21. package/lib/runtime/messageTimeline.d.ts +1 -0
  22. package/lib/runtime/messageTimeline.js +8 -5
  23. package/lib/runtime/outgoingContent.d.ts +2 -0
  24. package/lib/runtime/outgoingContent.js +6 -2
  25. package/lib/runtime/profileChat.d.ts +5 -1
  26. package/lib/runtime/profileChat.js +43 -16
  27. package/lib/runtime/profileCoordinator.d.ts +5 -0
  28. package/lib/runtime/profileCoordinator.js +51 -6
  29. package/lib/runtime/profileDatabase.d.ts +1 -0
  30. package/lib/runtime/profileDatabase.js +2 -0
  31. package/lib/runtime/profileLegacyInbox.js +1 -1
  32. package/lib/runtime/profileMemoryStore.d.ts +1 -0
  33. package/lib/runtime/profileMemoryStore.js +1 -1
  34. package/lib/runtime/profileOutboxDispatcher.js +1 -1
  35. package/lib/runtime/profileOwner.js +2 -2
  36. package/lib/runtime/profileProjection.d.ts +2 -0
  37. package/lib/runtime/profileProjection.js +76 -9
  38. package/lib/runtime/profileStoreTypes.d.ts +2 -0
  39. package/lib/runtime/readSync.js +1 -1
  40. package/lib/runtime/socialReadClient.d.ts +53 -0
  41. package/lib/runtime/socialReadClient.js +114 -11
  42. package/package.json +6 -7
@@ -84,7 +84,7 @@ export class ProfileChat {
84
84
  return;
85
85
  const base = { groupId: group.groupId, teamId: group.teamId ?? this.teamId, ownerId: group.ownerId, revision: group.revision };
86
86
  return group.status === "dissolved" ? { ...base, status: "dissolved", dissolvedBy: group.dissolvedBy, dissolvedAt: group.dissolvedAt }
87
- : { ...base, status: "active", title: group.title ?? "", avatar: group.avatar ?? undefined, memberIds: group.members ?? [] };
87
+ : { ...base, status: "active", title: group.title ?? "", avatar: group.avatar ?? undefined, ...(group.background == null ? {} : { background: group.background }), ...(group.description == null ? {} : { description: group.description }), memberIds: group.members ?? [] };
88
88
  }
89
89
  empty(id) {
90
90
  return { threadId: id, messages: [], hasEarlier: false, unread: undefined, group: undefined, readCounts: undefined, status: "pending", ready: false };
@@ -379,7 +379,7 @@ export class ProfileChat {
379
379
  throw Error("INVALID_GROUP_METADATA");
380
380
  if (value.status === "active" && (!Array.isArray(value.members) || !value.members.length || value.members.length > 256 ||
381
381
  !value.members.every(validMessageIdentifier) || !value.members.includes(value.ownerId) || !value.members.includes(this.host.identity.profileId) ||
382
- typeof value.title !== "string" || value.avatar != null && typeof value.avatar !== "string"))
382
+ typeof value.title !== "string" || value.background != null && typeof value.background !== "string" || value.description != null && (typeof value.description !== "string" || [...value.description].length > 500) || value.avatar != null && typeof value.avatar !== "string"))
383
383
  throw Error("INVALID_GROUP_METADATA");
384
384
  try {
385
385
  await this.host.submit({ type: "groupSnapshot", threadId: id, group: value, expectedAccessRevision, expectedControlRevision }, true);
@@ -410,32 +410,59 @@ export class ProfileChat {
410
410
  await pending.catch(() => { });
411
411
  return this.getGroup(id, options);
412
412
  }
413
- async waitGroup(id, previous) {
414
- // Delivered commands have an accepted index cursor; the API is the authority.
415
- const group = await this.refreshGroup(id);
416
- if (previous !== undefined && group.revision === previous)
417
- throw new ChatError("unavailable", "Waiting for group confirmation");
418
- return group;
413
+ async confirmGroup(id, matches) {
414
+ for (const delay of [0, 150, 400]) {
415
+ if (delay)
416
+ await new Promise(resolve => setTimeout(resolve, delay));
417
+ this.assertAccessible(id);
418
+ try {
419
+ const group = await this.refreshGroup(id);
420
+ if (matches(group))
421
+ return group;
422
+ }
423
+ catch (error) {
424
+ if (!(error instanceof SocialReadError) || ![404, 503].includes(error.status))
425
+ throw error;
426
+ }
427
+ }
428
+ throw new ChatError("unavailable", "Waiting for group confirmation");
419
429
  }
420
430
  async createGroup(input) {
421
431
  return createUniqueGroup(input.groupId, async (groupId) => {
422
- const id = await this.resolveThreadId({ groupId });
423
- await this.sendControl(id, { groupCreate: { title: input.title, members: input.members } });
424
- return { ...await this.waitGroup(id), threadId: id };
432
+ const threadId = await this.resolveThreadId({ groupId });
433
+ const group = await this.sendControl(threadId, { groupCreate: { title: input.title, members: input.members } });
434
+ return { ...group, threadId };
425
435
  });
426
436
  }
427
- async sendControl(id, content) {
437
+ async sendControl(id, content, previous) {
428
438
  const parent = this.parent(id), identity = this.host.identity;
429
439
  if (!parent?.internal?.targetId)
430
440
  throw new ChatError("unavailable", "Conversation is not prepared");
431
441
  const input = outgoingContent({ ...identity, teamId: this.teamId }, { id: groupThreadId(identity.appId, parent.internal.targetId, this.teamId), kind: "group", targetId: parent.internal.targetId, teamId: this.teamId, memberIds: parent.group?.members }, content);
432
442
  const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
433
443
  wire.recipients = input.recipients;
434
- await this.sendPrepared(id, wire, { waitFor: "delivered" });
435
- await this.host.synchronize();
444
+ try {
445
+ await this.sendPrepared(id, wire, { waitFor: "delivered" });
446
+ }
447
+ catch (error) {
448
+ // An interrupted acknowledgement can leave the group change committed.
449
+ const group = await this.confirmGroup(id, current => current.revision === wire.hash).catch(() => undefined);
450
+ if (!group)
451
+ throw error;
452
+ await this.host.submit({ type: "commandResult", commandId: wire.hash, state: "confirmed" }, true).catch(() => { });
453
+ return group;
454
+ }
455
+ // Group metadata is authoritative independently of the Inbox catch-up.
456
+ return this.confirmGroup(id, group => group.revision !== previous);
457
+ }
458
+ async updateGroup(id, changes) {
459
+ const previous = await this.getGroup(id);
460
+ return this.sendControl(id, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }, previous.revision);
461
+ }
462
+ async dissolveGroup(id, options = {}) {
463
+ const previous = await this.getGroup(id);
464
+ return this.sendControl(id, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }, previous.revision);
436
465
  }
437
- 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); }
438
- 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); }
439
466
  synchronizeReading() { return this.host.synchronize(); }
440
467
  revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
441
468
  /** Call only after a fresh authoritative Team membership check succeeds. */
@@ -13,6 +13,8 @@ export type ProfileCoordinatorOptions = {
13
13
  onProgress?: (progress: unknown) => void;
14
14
  fetch?: typeof fetch;
15
15
  requestTimeoutMs?: number;
16
+ /** Use the Hub's Team-scoped group batch endpoint when available. */
17
+ batchGroupReads?: boolean;
16
18
  };
17
19
  /** One application document, one dedicated Worker and one stable UI memory store.
18
20
  * A failed Worker is terminated before its replacement is created. */
@@ -27,6 +29,7 @@ export declare class ProfileCoordinator {
27
29
  private openingAbort?;
28
30
  private closed;
29
31
  private groupRequests;
32
+ private groupBatches;
30
33
  private groupAbort;
31
34
  get identity(): import("./inboxStore.js").InboxScope;
32
35
  get client(): ProfileWorkerClient;
@@ -46,6 +49,8 @@ export declare class ProfileCoordinator {
46
49
  voiceAttachment(id: string): Promise<Blob | null>;
47
50
  /** Current group authority comes from Hub, independently of Inbox history. */
48
51
  readGroup(groupId: string, teamId: string): Promise<SocialGroup>;
52
+ private queueGroupRead;
53
+ private flushGroupReads;
49
54
  updateToken(token: string): Promise<void>;
50
55
  close(): Promise<void>;
51
56
  }
@@ -1,7 +1,7 @@
1
1
  import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
2
  import { ProfileWorkerClient } from "./profileWorkerClient.js";
3
3
  import { openProfileWorker, profileChannelName } from "./profileWorkerHost.js";
4
- import { SocialReadClient } from "./socialReadClient.js";
4
+ import { groupReadBatchSize, SocialReadClient } from "./socialReadClient.js";
5
5
  /** One application document, one dedicated Worker and one stable UI memory store.
6
6
  * A failed Worker is terminated before its replacement is created. */
7
7
  export class ProfileCoordinator {
@@ -15,6 +15,7 @@ export class ProfileCoordinator {
15
15
  openingAbort;
16
16
  closed = false;
17
17
  groupRequests = new Map();
18
+ groupBatches = new Map();
18
19
  groupAbort = new AbortController();
19
20
  get identity() { return this.options.configuration.identity; }
20
21
  get client() { if (!this.connection)
@@ -156,19 +157,63 @@ export class ProfileCoordinator {
156
157
  readGroup(groupId, teamId) {
157
158
  if (this.closed)
158
159
  return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
159
- const key = JSON.stringify([teamId, groupId]), pending = this.groupRequests.get(key);
160
- if (pending)
161
- return pending;
162
160
  const network = this.options.configuration.network;
163
161
  if (!network)
164
162
  return Promise.reject(Error("PROFILE_NETWORK_UNAVAILABLE"));
165
- const task = new SocialReadClient({ ...this.identity, token: network.token, hubHttpUrl: network.hubHttpUrl.replace(/^ws/, "http"), fetch: this.options.fetch })
166
- .group({ groupId, teamId }, this.groupAbort.signal);
163
+ const key = JSON.stringify([network.token, network.hubHttpUrl, teamId, groupId]);
164
+ const pending = this.groupRequests.get(key);
165
+ if (pending)
166
+ return pending;
167
+ const client = new SocialReadClient({ ...this.identity, token: network.token, hubHttpUrl: network.hubHttpUrl.replace(/^ws/, "http"), fetch: this.options.fetch });
168
+ const task = this.options.batchGroupReads && teamId
169
+ ? this.queueGroupRead(client, JSON.stringify([network.token, network.hubHttpUrl, teamId]), teamId, groupId)
170
+ : client.group({ groupId, teamId }, this.groupAbort.signal);
167
171
  this.groupRequests.set(key, task);
168
172
  void task.finally(() => { if (this.groupRequests.get(key) === task)
169
173
  this.groupRequests.delete(key); }).catch(() => { });
170
174
  return task;
171
175
  }
176
+ queueGroupRead(client, key, teamId, groupId) {
177
+ return new Promise((resolve, reject) => {
178
+ const pending = { groupId, resolve, reject };
179
+ const queued = this.groupBatches.get(key);
180
+ if (queued) {
181
+ queued.push(pending);
182
+ return;
183
+ }
184
+ const batch = [pending];
185
+ this.groupBatches.set(key, batch);
186
+ queueMicrotask(() => {
187
+ this.groupBatches.delete(key);
188
+ void this.flushGroupReads(client, teamId, batch);
189
+ });
190
+ });
191
+ }
192
+ async flushGroupReads(client, teamId, pending) {
193
+ const signal = this.groupAbort.signal;
194
+ for (let start = 0; start < pending.length; start += groupReadBatchSize) {
195
+ const batch = pending.slice(start, start + groupReadBatchSize);
196
+ try {
197
+ signal.throwIfAborted();
198
+ if (batch.length === 1) {
199
+ batch[0].resolve(await client.group({ groupId: batch[0].groupId, teamId }, signal));
200
+ continue;
201
+ }
202
+ const byId = new Map(batch.map(request => [request.groupId, request]));
203
+ for (const result of await client.groupBatch({ groupIds: [...byId.keys()], teamId }, signal)) {
204
+ const request = byId.get(result.groupId);
205
+ if ("error" in result)
206
+ request.reject(result.error);
207
+ else
208
+ request.resolve(result.data);
209
+ }
210
+ }
211
+ catch (error) {
212
+ for (const request of batch)
213
+ request.reject(error);
214
+ }
215
+ }
216
+ }
172
217
  async updateToken(token) {
173
218
  if (!this.options.configuration.network)
174
219
  return;
@@ -28,6 +28,7 @@ export declare class ProfileDatabase extends Dexie {
28
28
  threads?: ProfileThread[];
29
29
  windows?: ProfileWindow[];
30
30
  messages?: ProfileMessage[];
31
+ deleteMessages?: string[];
31
32
  }): Promise<void>;
32
33
  /** Bounded maintenance on the serial Worker queue. Building
33
34
  * and validated generations remain resumable; outbox is never involved. */
@@ -110,6 +110,8 @@ export class ProfileDatabase extends Dexie {
110
110
  const current = await this.inboxState.get("current");
111
111
  if (current?.activeGeneration === build.generation)
112
112
  throw Error("PROFILE_BUILD_IS_ACTIVE");
113
+ if (rows.deleteMessages?.length)
114
+ await this.messages.bulkDelete(rows.deleteMessages.map(id => [build.generation, id]));
113
115
  if (rows.messages?.length)
114
116
  await this.messages.bulkPut(rows.messages);
115
117
  if (rows.windows?.length)
@@ -102,7 +102,7 @@ export async function migrateLegacyInbox(owner, options = {}) {
102
102
  readThroughSeq: 0, explicitReadMessageIds: [row.id] }, `explicit:${row.id}`));
103
103
  }
104
104
  for (const row of rows.facts)
105
- if (["threadOrganized", "threadAssigned", "relationshipUpdated"].includes(row.kind))
105
+ if (["threadOrganized", "threadAssigned", "relationshipUpdated", "messageDeleted"].includes(row.kind))
106
106
  await push(restore(row.kind, row.value, row.id));
107
107
  for (const row of rows.receipts)
108
108
  await push({ type: "restoreReceipt", data: { appId: identity.appId, profileId: identity.profileId,
@@ -74,6 +74,7 @@ export declare class ProfileMemoryStore {
74
74
  mine: boolean;
75
75
  status: "sending" | "sent" | "failed" | "read";
76
76
  recalled: boolean;
77
+ recalledAt?: number;
77
78
  unread?: boolean;
78
79
  attentionEligible?: boolean;
79
80
  reading?: Readonly<{
@@ -343,7 +343,7 @@ export class ProfileMemoryStore {
343
343
  const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
344
344
  ...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
345
345
  status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
346
- recalled: message.recalled ?? false, unread: readingUnknown ? undefined : !read,
346
+ recalled: message.recalled ?? false, recalledAt: message.recalledAt, unread: readingUnknown ? undefined : !read,
347
347
  attentionEligible: message.mention, reading: readingUnknown ? undefined : { seq: message.sourceSeq, read,
348
348
  readPolicy: policy === "visible" ? "visible" : "explicit" },
349
349
  reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
@@ -122,7 +122,7 @@ export class ProfileOutboxDispatcher {
122
122
  }
123
123
  async reading(command) {
124
124
  const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/reading`, {
125
- method: "POST", headers: { authorization: `Bearer ${await this.options.getToken()}`, "content-type": "application/json" },
125
+ method: "POST", headers: { authorization: `Bearer ${await this.options.getToken()}`, "content-type": "application/json", "x-pmate-stream-protocol": "seq-v1" },
126
126
  body: JSON.stringify({ ...command.payload, operationId: command.commandId }),
127
127
  signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(10000)]), cache: "no-store", redirect: "error",
128
128
  });
@@ -186,7 +186,7 @@ export class ProfileOwner {
186
186
  const prepared = this.projection.prepare(events);
187
187
  // A replayed cursor or already-observed reading candidate must not even
188
188
  // open a readwrite transaction. Only small sync metadata is compared here.
189
- const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteOutbox].some(rows => rows.length) &&
189
+ const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteMessages, prepared.deleteOutbox].some(rows => rows.length) &&
190
190
  JSON.stringify({ ...prepared.current, commitRevision: fromRevision }) === JSON.stringify(this.current);
191
191
  if (unchanged)
192
192
  return prepared.rejected;
@@ -196,7 +196,7 @@ export class ProfileOwner {
196
196
  if (committed.commitRevision === fromRevision)
197
197
  return prepared.rejected;
198
198
  prepared.current = committed;
199
- const delta = { current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
199
+ const delta = { deleteMessages: prepared.deleteMessages, current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
200
200
  protocolVersion: PROFILE_PROTOCOL_VERSION, generation: committed.activeGeneration,
201
201
  fromRevision, toRevision: committed.commitRevision };
202
202
  this.projection.accept(prepared);
@@ -102,6 +102,7 @@ export type PreparedProfileProjection = {
102
102
  messages: ProfileMessage[];
103
103
  readingIndices: Map<string, ProfileReadingIndex>;
104
104
  outbox: ProfileOutboxCommand[];
105
+ deleteMessages: string[];
105
106
  deleteOutbox: string[];
106
107
  rejected?: readonly (Error | undefined)[];
107
108
  };
@@ -128,6 +129,7 @@ export declare class ProfileProjection {
128
129
  messages: ProfileMessage[];
129
130
  readingIndices: Map<string, ProfileReadingIndex>;
130
131
  outbox: ProfileOutboxCommand[];
132
+ deleteMessages: string[];
131
133
  deleteOutbox: string[];
132
134
  };
133
135
  prepareBasis(bootstrap: InboxBootstrap): PreparedProfileProjection;
@@ -1,3 +1,4 @@
1
+ import { hideDeletedQuote, inboxDeletion, recallTarget } from "./inboxDeletion.js";
1
2
  import { inboxSequence } from "./inboxStore.js";
2
3
  import { messageMentionsProfile, messageRequiresPlayback } from "./readingContent.js";
3
4
  import { messageThreadRoot } from "./messageThread.js";
@@ -95,6 +96,8 @@ export class ProfileProjection {
95
96
  this.children.set(row.parentThreadId, children);
96
97
  }
97
98
  }
99
+ for (const id of prepared.deleteMessages)
100
+ this.messages.delete(id);
98
101
  for (const row of prepared.messages) {
99
102
  this.messages.set(row.messageId, row);
100
103
  }
@@ -127,6 +130,7 @@ class ProfileProjectionDraft {
127
130
  windows = new Map();
128
131
  readingIndices = new Map();
129
132
  outbox = new Map();
133
+ deleteMessages = new Set();
130
134
  deleteOutbox = new Set();
131
135
  seq;
132
136
  revision;
@@ -178,7 +182,7 @@ class ProfileProjectionDraft {
178
182
  return Error("INVALID_MESSAGE_REACTION");
179
183
  }
180
184
  }
181
- message(id) { return this.messages.get(id) ?? this.base.messages.get(id); }
185
+ message(id) { return this.deleteMessages.has(id) ? undefined : this.messages.get(id) ?? this.base.messages.get(id); }
182
186
  thread(id) { return this.threads.get(id) ?? this.base.threads.get(id); }
183
187
  ensure(id, kind = "group", extra = {}) {
184
188
  const previous = this.thread(id);
@@ -349,6 +353,9 @@ class ProfileProjectionDraft {
349
353
  case "readingUpdated":
350
354
  this.reading(event);
351
355
  break;
356
+ case "messageDeleted":
357
+ this.deleteInboxMessages(event);
358
+ break;
352
359
  case "threadOrganized":
353
360
  this.organize(event);
354
361
  break;
@@ -593,12 +600,66 @@ class ProfileProjectionDraft {
593
600
  this.reading(eventForLocalReading(this.base.identity, sourceId, thread.rootMessageId, values), false);
594
601
  }
595
602
  }
603
+ deleteInboxMessages(event) {
604
+ const { threadId, teamId, messageIds } = inboxDeletion(event.fact);
605
+ const source = this.ensure(threadId, "group", { teamId });
606
+ const key = JSON.stringify(teamId);
607
+ const deleted = new Set([...(source.internal?.deletedMessageIds?.[key] ?? []), ...messageIds]);
608
+ this.putThread({ ...source, internal: {
609
+ ...source.internal, deletedMessageIds: { ...source.internal?.deletedMessageIds, [key]: [...deleted] },
610
+ } });
611
+ for (const id of messageIds) {
612
+ const message = this.message(id);
613
+ if (!message || message.sourceThreadId !== threadId || this.thread(message.threadId)?.teamId !== teamId)
614
+ continue;
615
+ const thread = this.thread(message.threadId);
616
+ const before = this.contribution(message);
617
+ const unknown = this.unknownReading(message);
618
+ const directory = this.directory(message.threadId);
619
+ const change = directory.remove(id, this.revision);
620
+ directory.accept(change);
621
+ for (const row of change.windows)
622
+ this.windows.set(JSON.stringify([row.threadId, row.windowId]), row);
623
+ this.readingIndex(message.threadId).remove(message);
624
+ this.messages.delete(id);
625
+ this.deleteMessages.add(id);
626
+ const last = directory.readPage(undefined, 1)[0];
627
+ const participantCounts = { ...thread.internal?.participantCounts, [message.from]: Math.max(0, (thread.internal?.participantCounts?.[message.from] ?? 1) - 1) };
628
+ this.putThread({ ...this.thread(message.threadId), messageCount: directory.count, windowCount: change.windowCount,
629
+ lastMessageId: last?.messageId, lastActivityAt: last?.orderKey[0] ?? 0, internal: { ...this.thread(message.threadId)?.internal, participantCounts },
630
+ participantProfileIds: Object.keys(participantCounts).filter(profile => participantCounts[profile] > 0).sort() });
631
+ this.updateSummary(message.threadId, -before.unread, -before.mentions, -unknown);
632
+ }
633
+ for (const id of new Set([...this.base.messages.keys(), ...this.messages.keys()])) {
634
+ const row = this.message(id);
635
+ if (!row || row.sourceThreadId !== threadId || this.thread(row.threadId)?.teamId !== teamId)
636
+ continue;
637
+ const content = hideDeletedQuote(row.content, deleted);
638
+ const quote = row.presentation?.quote;
639
+ if (content === row.content && (!quote?.messageId || !deleted.has(quote.messageId)))
640
+ continue;
641
+ const presentation = row.presentation && {
642
+ ...row.presentation,
643
+ quote: quote?.messageId && deleted.has(quote.messageId) ? { ...quote, content: "[消息已删除]" } : quote,
644
+ richContent: hideDeletedQuote({ content: row.presentation.richContent }, deleted).content,
645
+ };
646
+ this.messages.set(id, { ...row, content, presentation, revision: this.revision });
647
+ }
648
+ }
596
649
  add(event) {
597
- const wire = event.fact;
650
+ let wire = event.fact;
598
651
  if (!wire.messageId || !wire.threadId || !wire.from || !Number.isSafeInteger(wire.seq) || wire.seq < 1 || !["dm", "group"].includes(wire.threadKind))
599
652
  throw Error("INVALID_INBOX_MESSAGE");
600
653
  if (wire.from !== this.base.identity.profileId && !wire.recipients?.includes(this.base.identity.profileId) && !(wire.threadKind === "dm" && wire.to === this.base.identity.profileId))
601
654
  throw Error("INBOX_MESSAGE_INACCESSIBLE");
655
+ const deleted = this.thread(wire.threadId)?.internal?.deletedMessageIds?.[JSON.stringify(wire.teamId)];
656
+ if (deleted?.length) {
657
+ const ids = new Set(deleted);
658
+ const target = recallTarget(wire.body);
659
+ if (ids.has(wire.messageId) || (target && ids.has(target)))
660
+ return;
661
+ wire = { ...wire, body: hideDeletedQuote(wire.body, ids) };
662
+ }
602
663
  let source = this.ensure(wire.threadId, wire.threadKind, { teamId: wire.teamId, internal: { targetId: wire.to } });
603
664
  const targetId = wire.threadKind === "dm" && wire.from !== this.base.identity.profileId ? wire.from : wire.to;
604
665
  if (source.kind !== wire.threadKind || source.teamId !== wire.teamId || source.internal?.targetId !== targetId) {
@@ -624,7 +685,7 @@ class ProfileProjectionDraft {
624
685
  const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
625
686
  const recall = body?.kind === "recall" ? body.targetMessageId : body?.content?.recall?.messageId;
626
687
  if (reaction || recall) {
627
- this.control(parent.threadId, wire, reaction, recall);
688
+ this.control(parent.threadId, wire, reaction, recall, event.fact.sourceAcceptedAt ?? wire.serverCreatedAt);
628
689
  return;
629
690
  }
630
691
  const accepted = event.fact.sourceAcceptedAt ?? event.acceptedAt;
@@ -661,7 +722,7 @@ class ProfileProjectionDraft {
661
722
  if (pending)
662
723
  for (const entry of pending) {
663
724
  const saved = entry;
664
- this.control(parent.threadId, saved.wire, saved.reaction, saved.recall);
725
+ this.control(parent.threadId, saved.wire, saved.reaction, saved.recall, saved.recalledAt);
665
726
  }
666
727
  for (const origin of new Set([source.threadId, parent.threadId])) {
667
728
  const intents = this.thread(origin)?.internal?.pendingReadingIntents?.[wire.messageId] ?? [];
@@ -709,7 +770,7 @@ class ProfileProjectionDraft {
709
770
  this.local({ type: "restoreReadingCommand", command: { commandId: operation.commandId, kind: operation.policy === "played" ? "played" : "reading",
710
771
  threadId: message.threadId, createdAt: operation.createdAt, payload: fact, state: "pending", attempts: 0 } });
711
772
  }
712
- control(threadId, wire, reaction, recall) {
773
+ control(threadId, wire, reaction, recall, recalledAt) {
713
774
  const targetId = recall ?? reaction?.messageId;
714
775
  if (typeof targetId !== "string")
715
776
  throw Error("INVALID_MESSAGE_CONTROL");
@@ -717,12 +778,18 @@ class ProfileProjectionDraft {
717
778
  if (!target) {
718
779
  const thread = this.thread(threadId), entries = thread.internal?.pendingControls?.[targetId] ?? [];
719
780
  this.putThread({ ...thread, internal: { ...thread.internal, pendingControls: { ...thread.internal?.pendingControls,
720
- [targetId]: [...entries, { wire, reaction, recall }] } } });
781
+ [targetId]: [...entries, { wire, reaction, recall, recalledAt }] } } });
721
782
  return;
722
783
  }
723
784
  if (recall) {
724
- if (wire.from === target.from && !target.recalled)
725
- this.setMessage({ ...target, recalled: true });
785
+ if (wire.from !== target.from)
786
+ return;
787
+ const confirmedAt = typeof recalledAt === "number" && Number.isSafeInteger(recalledAt) && recalledAt > 0
788
+ ? Math.min(target.recalledAt ?? recalledAt, recalledAt)
789
+ : target.recalledAt;
790
+ if (!target.recalled || confirmedAt !== target.recalledAt) {
791
+ this.setMessage({ ...target, recalled: true, recalledAt: confirmedAt });
792
+ }
726
793
  return;
727
794
  }
728
795
  if (reaction.version !== 1 || typeof reaction.emojiId !== "string" || !Number.isSafeInteger(reaction.revision) || reaction.revision < 1 || typeof reaction.active !== "boolean")
@@ -941,7 +1008,7 @@ class ProfileProjectionDraft {
941
1008
  return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
942
1009
  localMigrations: this.localMigrations ?? this.base.current.localMigrations, revokedTeamIds: this.revokedTeamIds ?? this.base.current.revokedTeamIds, teamAccessRevision: this.teamAccessRevision ?? this.base.current.teamAccessRevision },
943
1010
  threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
944
- outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
1011
+ deleteMessages: [...this.deleteMessages], outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
945
1012
  }
946
1013
  }
947
1014
  function eventForLocalReading(identity, threadId, root, values) {
@@ -47,6 +47,7 @@ export type ProfileThread = {
47
47
  groupControls?: Record<string, unknown>;
48
48
  organizationRevisions?: Record<string, number>;
49
49
  assignments?: Record<string, string>;
50
+ deletedMessageIds?: Record<string, string[]>;
50
51
  pendingControls?: Record<string, unknown[]>;
51
52
  messageRoots?: Record<string, string>;
52
53
  pendingReceipts?: Record<string, string[]>;
@@ -103,6 +104,7 @@ export type ProfileMessage = {
103
104
  }[];
104
105
  sendStatus?: "sending" | "failed" | "sent";
105
106
  recalled?: boolean;
107
+ recalledAt?: number;
106
108
  readBy: string[];
107
109
  receiptStatus: "unknown" | "ready";
108
110
  explicitReadingFacts: {
@@ -152,7 +152,7 @@ export class ReadSyncClient {
152
152
  let receipt;
153
153
  try {
154
154
  receipt = await this.request("/api/social/reading", {
155
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
155
+ method: "POST", headers: { "content-type": "application/json", "x-pmate-stream-protocol": "seq-v1" }, body: JSON.stringify({ ...operation, appId, profileId }),
156
156
  });
157
157
  }
158
158
  catch (error) {
@@ -22,6 +22,26 @@ export type MessageThreadSummary = {
22
22
  lastReplyAt: number | null;
23
23
  participantProfileIds: string[];
24
24
  };
25
+ export type TeamTask = {
26
+ id: string;
27
+ teamId: string;
28
+ discussionId: string;
29
+ threadId: string;
30
+ title: string;
31
+ description: string;
32
+ kind: "standard" | "flow";
33
+ status: "todo" | "inProgress" | "done";
34
+ assigneeId: string | null;
35
+ revision: number;
36
+ createdBy: string;
37
+ createdAt: number;
38
+ updatedBy: string;
39
+ updatedAt: number;
40
+ };
41
+ export type TeamTaskPage = {
42
+ tasks: TeamTask[];
43
+ nextAfterId: string | null;
44
+ };
25
45
  export type SocialGroup = {
26
46
  appId: string;
27
47
  groupId: string;
@@ -29,6 +49,8 @@ export type SocialGroup = {
29
49
  ownerId: string;
30
50
  members?: readonly string[];
31
51
  title?: string;
52
+ background?: string | null;
53
+ description?: string | null;
32
54
  avatar?: string | null;
33
55
  revision: string;
34
56
  versionNumber?: number;
@@ -50,6 +72,14 @@ export declare class SocialReadError extends Error {
50
72
  readonly status: number;
51
73
  constructor(status: number, message: string);
52
74
  }
75
+ export declare const groupReadBatchSize = 32;
76
+ type GroupReadResult = {
77
+ groupId: string;
78
+ data: SocialGroup;
79
+ } | {
80
+ groupId: string;
81
+ error: SocialReadError;
82
+ };
53
83
  /** Authenticated profile reads through Hub; no fallback to public indexer URLs.
54
84
  * Create a new client when identity changes, so in-flight requests retain their
55
85
  * original account scope. Team ownership is validated again by the server.
@@ -74,6 +104,7 @@ export declare class SocialReadClient {
74
104
  threadRootId?: string;
75
105
  mainOnly?: boolean;
76
106
  }, signal?: AbortSignal): Promise<SocialMessagePage>;
107
+ private validateMessagePage;
77
108
  messageThreads(input: {
78
109
  threadId: string;
79
110
  teamId?: string;
@@ -84,16 +115,38 @@ export declare class SocialReadClient {
84
115
  revision: number;
85
116
  items: MessageThreadSummary[];
86
117
  }>;
118
+ teamTasks(input: {
119
+ teamId: string;
120
+ afterId?: string;
121
+ limit?: number;
122
+ }, signal?: AbortSignal): Promise<TeamTaskPage>;
123
+ teamTask(input: {
124
+ teamId: string;
125
+ id: string;
126
+ }, signal?: AbortSignal): Promise<TeamTask>;
127
+ taskMessagePage(input: {
128
+ teamId: string;
129
+ taskId: string;
130
+ limit?: number;
131
+ before?: string;
132
+ after?: string;
133
+ }, signal?: AbortSignal): Promise<SocialMessagePage>;
87
134
  group(input: {
88
135
  groupId: string;
89
136
  teamId?: string;
90
137
  }, signal?: AbortSignal): Promise<SocialGroup>;
138
+ groupBatch(input: {
139
+ groupIds: readonly string[];
140
+ teamId: string;
141
+ }, signal?: AbortSignal): Promise<GroupReadResult[]>;
91
142
  relationship(input: {
92
143
  peerId: string;
93
144
  teamId?: string;
94
145
  }): Promise<SocialRelationship | null>;
146
+ private requireMerryTaskTeam;
95
147
  private teamQuery;
96
148
  private requireTeam;
97
149
  private list;
98
150
  private request;
99
151
  }
152
+ export {};