@pmate/chat-sdk 0.13.0-profile.14 → 0.13.0-profile.16

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.
@@ -5,6 +5,7 @@ import { type ProfileOperation } from "./profileProjection.js";
5
5
  import type { ProfileIdentity } from "./profileStoreTypes.js";
6
6
  import { type ChatRuntimeMessage } from "./protocol.js";
7
7
  import type { OnlineReachEvent } from "./reach.js";
8
+ import { type SocialGroup } from "./socialReadClient.js";
8
9
  export type ProfileChatHost = {
9
10
  identity: ProfileIdentity;
10
11
  memory: ProfileMemoryStore;
@@ -13,6 +14,7 @@ export type ProfileChatHost = {
13
14
  synchronize(): Promise<void>;
14
15
  waitForCommand(id: string): Promise<void>;
15
16
  voiceAttachment(id: string): Promise<Blob | null>;
17
+ readGroup(groupId: string, teamId: string): Promise<SocialGroup>;
16
18
  };
17
19
  export declare function getProfileChatRuntime(chat: Chat): ProfileChat;
18
20
  export declare function createProfileChat(host: ProfileChatHost, teamId: string): Chat;
@@ -24,6 +26,8 @@ export declare class ProfileChat implements Chat {
24
26
  readonly host: ProfileChatHost;
25
27
  readonly teamId: string;
26
28
  private discussion?;
29
+ private groupRequests;
30
+ private groupChecks;
27
31
  private views;
28
32
  private preparedInputs;
29
33
  private limits;
@@ -78,6 +82,7 @@ export declare class ProfileChat implements Chat {
78
82
  }[];
79
83
  }>;
80
84
  sendPrepared(threadId: string, wire: ChatRuntimeMessage, options?: SendOptions, voiceBlob?: Blob): Promise<ChatRuntimeMessage>;
85
+ private persistPrepared;
81
86
  sendMessage(id: string, content: OutgoingContent, options?: SendOptions): Promise<SentMessage>;
82
87
  retryMessage(messageId: string): Promise<{
83
88
  id: string;
@@ -101,6 +106,8 @@ export declare class ProfileChat implements Chat {
101
106
  release: () => void;
102
107
  }>;
103
108
  getGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
109
+ private loadGroup;
110
+ private refreshChangedGroups;
104
111
  refreshGroup(id: string, options?: ReadOptions): Promise<ChatGroup>;
105
112
  private waitGroup;
106
113
  createGroup(input: {
@@ -2,10 +2,11 @@ import { ChatError } from "../chatError.js";
2
2
  import { registerChatStore } from "../framework.js";
3
3
  import { profileDiscussionId } from "./profileProjection.js";
4
4
  import { createRuntimeMsg } from "./protocol.js";
5
- import { outgoingContent } from "./outgoingContent.js";
5
+ import { outgoingContent, validMessageIdentifier } 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 { SocialReadError } from "./socialReadClient.js";
9
10
  import { scopedGroupDenial } from "./groupDenial.js";
10
11
  const sessions = new WeakMap();
11
12
  export function getProfileChatRuntime(chat) {
@@ -34,6 +35,8 @@ export class ProfileChat {
34
35
  host;
35
36
  teamId;
36
37
  discussion;
38
+ groupRequests = new Map();
39
+ groupChecks = new Map();
37
40
  views = new Map();
38
41
  preparedInputs = new Map();
39
42
  limits = new Map();
@@ -53,7 +56,7 @@ export class ProfileChat {
53
56
  ? this.subscribeThread(target, () => listener()) : this.subscribeChat(() => target()));
54
57
  registerChatStore(this, { getSnapshot: ((id) => id === undefined ? this.summary : this.snapshot(id)),
55
58
  subscribeThread: (id, listener) => this.subscribeThread(id, () => listener()), subscribeChanges });
56
- this.offList = host.memory.subscribeThreadList(() => this.prepareSummary());
59
+ this.offList = host.memory.subscribeThreadList(() => { this.prepareSummary(); this.refreshChangedGroups(); });
57
60
  this.prepareSummary();
58
61
  }
59
62
  assertOpen() { if (this.closed)
@@ -76,7 +79,7 @@ export class ProfileChat {
76
79
  assertAccessible(id) { this.assertOpen(); const error = this.accessError(id); if (error)
77
80
  throw error; }
78
81
  group(thread) {
79
- const group = thread?.group;
82
+ const group = thread?.internal?.groupSource === "api" ? thread.group : undefined;
80
83
  if (!group)
81
84
  return;
82
85
  const base = { groupId: group.groupId, teamId: group.teamId ?? this.teamId, ownerId: group.ownerId, revision: group.revision };
@@ -240,6 +243,16 @@ export class ProfileChat {
240
243
  }) };
241
244
  }
242
245
  async sendPrepared(threadId, wire, options = {}, voiceBlob) {
246
+ const parent = this.parent(threadId);
247
+ if (parent?.kind === "group" && wire.body.kind !== "group") {
248
+ const group = await this.getGroup(threadId);
249
+ if (group.status !== "active")
250
+ throw new ChatError("access-denied", "Group dissolved");
251
+ wire = { ...wire, recipients: [...group.memberIds] };
252
+ }
253
+ return this.persistPrepared(threadId, wire, options, voiceBlob);
254
+ }
255
+ async persistPrepared(threadId, wire, options = {}, voiceBlob) {
243
256
  this.assertAccessible(threadId);
244
257
  if (!this.discussion && this.thread(threadId)?.kind === "discussion")
245
258
  throw new ChatError("invalid-input", "Use a discussion session to send replies");
@@ -260,10 +273,13 @@ export class ProfileChat {
260
273
  throw new ChatError("unavailable", "Conversation is not prepared");
261
274
  const kind = parent.kind === "dm" ? "dm" : "group", identity = this.host.identity;
262
275
  const expectedId = kind === "group" ? groupThreadId(identity.appId, parent.internal.targetId, this.teamId) : dmThreadId(identity.appId, identity.profileId, parent.internal.targetId, this.teamId);
263
- const input = outgoingContent({ ...identity, teamId: this.teamId }, { id: expectedId, kind, targetId: parent.internal.targetId, teamId: this.teamId, memberIds: parent.group?.members }, { ...content, ...(this.discussion ? { threadRootId: this.discussion.rootId } : {}) });
276
+ const group = kind === "group" ? await this.getGroup(id) : undefined;
277
+ if (group?.status === "dissolved")
278
+ throw new ChatError("access-denied", "Group dissolved");
279
+ const input = outgoingContent({ ...identity, teamId: this.teamId }, { id: expectedId, kind, targetId: parent.internal.targetId, teamId: this.teamId, memberIds: group?.status === "active" ? group.memberIds : undefined }, { ...content, ...(this.discussion ? { threadRootId: this.discussion.rootId } : {}) });
264
280
  const wire = createRuntimeMsg(identity.profileId, input.to, 1, input.body);
265
281
  wire.recipients = input.recipients;
266
- await this.sendPrepared(id, wire, options, input.voiceBlob);
282
+ await this.persistPrepared(id, wire, options, input.voiceBlob);
267
283
  return { id: wire.hash, timestamp: wire.t };
268
284
  }
269
285
  async retryMessage(messageId) {
@@ -315,22 +331,91 @@ export class ProfileChat {
315
331
  const objectUrl = URL.createObjectURL(blob);
316
332
  return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) };
317
333
  }
318
- async getGroup(id, options = {}) { this.assertAccessible(id); options.signal?.throwIfAborted(); const group = this.group(this.parent(id)); if (!group)
319
- throw new ChatError("unavailable", "Group is not prepared"); return group; }
320
- async refreshGroup(id, options = {}) { await this.host.synchronize(); return this.getGroup(id, options); }
334
+ async getGroup(id, options = {}) {
335
+ this.assertOpen();
336
+ options.signal?.throwIfAborted();
337
+ const parent = this.parent(id), access = this.accessError(id);
338
+ // A previous group projection/denial can be repaired by a fresh authorized read.
339
+ // Team revocation and foreign scopes still fail before the request.
340
+ if (!this.host.memory.isTeamAvailable(this.teamId) || parent?.teamId !== this.teamId || parent?.kind !== "group" || !parent.internal?.targetId) {
341
+ if (access)
342
+ throw access;
343
+ throw new ChatError("unavailable", "Conversation is not prepared");
344
+ }
345
+ const key = parent.threadId;
346
+ let pending = this.groupRequests.get(key);
347
+ if (!pending) {
348
+ this.groupChecks.set(key, parent.internal.groupControlRevision ?? 0);
349
+ pending = this.loadGroup(key, parent.internal.targetId);
350
+ this.groupRequests.set(key, pending);
351
+ void pending.finally(() => { this.groupRequests.delete(key); if (!this.closed)
352
+ this.refreshChangedGroups(); }).catch(() => { });
353
+ }
354
+ const group = await pending;
355
+ options.signal?.throwIfAborted();
356
+ this.assertOpen();
357
+ return group;
358
+ }
359
+ async loadGroup(id, groupId, attempt = 0) {
360
+ const expectedAccessRevision = this.host.memory.getAccessRevision();
361
+ const expectedControlRevision = this.host.memory.getThread(id)?.internal?.groupControlRevision ?? 0;
362
+ this.groupChecks.set(id, expectedControlRevision);
363
+ let value;
364
+ try {
365
+ value = await this.host.readGroup(groupId, this.teamId);
366
+ }
367
+ catch (error) {
368
+ if (error instanceof SocialReadError && error.status === 403) {
369
+ this.assertOpen();
370
+ await this.host.submit({ type: "groupDenied", threadId: id, expectedAccessRevision }, true);
371
+ throw scopedGroupDenial(new ChatError("access-denied", "Group access denied", { threadId: id, status: 403 }));
372
+ }
373
+ throw error;
374
+ }
375
+ this.assertOpen();
376
+ if (!value || value.appId !== this.host.identity.appId || value.teamId !== this.teamId || value.groupId !== groupId ||
377
+ !validMessageIdentifier(value.ownerId) || !validMessageIdentifier(value.revision) || !Number.isSafeInteger(value.versionNumber) || value.versionNumber < 1 ||
378
+ !["active", "dissolved"].includes(value.status ?? ""))
379
+ throw Error("INVALID_GROUP_METADATA");
380
+ if (value.status === "active" && (!Array.isArray(value.members) || !value.members.length || value.members.length > 256 ||
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"))
383
+ throw Error("INVALID_GROUP_METADATA");
384
+ try {
385
+ await this.host.submit({ type: "groupSnapshot", threadId: id, group: value, expectedAccessRevision, expectedControlRevision }, true);
386
+ }
387
+ catch (error) {
388
+ if (error?.message === "GROUP_METADATA_STALE" && attempt < 2)
389
+ return this.loadGroup(id, groupId, attempt + 1);
390
+ throw error;
391
+ }
392
+ this.assertOpen();
393
+ const group = this.group(this.host.memory.getThread(id));
394
+ if (!group)
395
+ throw new ChatError("unavailable", "Group is not prepared");
396
+ // Directory callers may read the prepared store without a subscription.
397
+ this.prepare(id);
398
+ return group;
399
+ }
400
+ refreshChangedGroups() {
401
+ for (const [id, revision] of this.groupChecks) {
402
+ const thread = this.host.memory.getThread(id);
403
+ if (thread && (thread.internal?.groupControlRevision ?? 0) !== revision && !this.groupRequests.has(id))
404
+ void this.getGroup(id).catch(() => { });
405
+ }
406
+ }
407
+ async refreshGroup(id, options = {}) {
408
+ const pending = this.groupRequests.get(this.parent(id)?.threadId ?? id);
409
+ if (pending)
410
+ await pending.catch(() => { });
411
+ return this.getGroup(id, options);
412
+ }
321
413
  async waitGroup(id, previous) {
322
- const get = () => { const group = this.group(this.parent(id)); return group && group.revision !== previous ? group : undefined; };
323
- const current = get();
324
- if (current)
325
- return current;
326
- return new Promise((resolve, reject) => {
327
- const timer = setTimeout(() => { off(); reject(new ChatError("unavailable", "Waiting for group confirmation")); }, 30000);
328
- const off = this.host.memory.subscribeThread(id, () => { const group = get(); if (group) {
329
- clearTimeout(timer);
330
- off();
331
- resolve(group);
332
- } });
333
- });
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;
334
419
  }
335
420
  async createGroup(input) {
336
421
  return createUniqueGroup(input.groupId, async (groupId) => {
@@ -1,6 +1,7 @@
1
1
  import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
2
  import { ProfileWorkerClient, type ProfileMessagePort } from "./profileWorkerClient.js";
3
3
  import { type ProfileWorkerConfiguration } from "./profileWorkerHost.js";
4
+ import { type SocialGroup } from "./socialReadClient.js";
4
5
  import type { ProfileOperation } from "./profileProjection.js";
5
6
  type WorkerHandle = ProfileMessagePort & {
6
7
  terminate(): void;
@@ -10,6 +11,7 @@ export type ProfileCoordinatorOptions = {
10
11
  createWorker: () => WorkerHandle;
11
12
  onError?: (error: unknown) => void;
12
13
  onProgress?: (progress: unknown) => void;
14
+ fetch?: typeof fetch;
13
15
  requestTimeoutMs?: number;
14
16
  };
15
17
  /** One application document, one dedicated Worker and one stable UI memory store.
@@ -24,6 +26,8 @@ export declare class ProfileCoordinator {
24
26
  private restarting?;
25
27
  private openingAbort?;
26
28
  private closed;
29
+ private groupRequests;
30
+ private groupAbort;
27
31
  get identity(): import("./inboxStore.js").InboxScope;
28
32
  get client(): ProfileWorkerClient;
29
33
  constructor(options: ProfileCoordinatorOptions);
@@ -40,6 +44,8 @@ export declare class ProfileCoordinator {
40
44
  synchronize(): Promise<void>;
41
45
  waitForCommand(id: string): Promise<void>;
42
46
  voiceAttachment(id: string): Promise<Blob | null>;
47
+ /** Current group authority comes from Hub, independently of Inbox history. */
48
+ readGroup(groupId: string, teamId: string): Promise<SocialGroup>;
43
49
  updateToken(token: string): Promise<void>;
44
50
  close(): Promise<void>;
45
51
  }
@@ -1,6 +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
5
  /** One application document, one dedicated Worker and one stable UI memory store.
5
6
  * A failed Worker is terminated before its replacement is created. */
6
7
  export class ProfileCoordinator {
@@ -13,6 +14,8 @@ export class ProfileCoordinator {
13
14
  restarting;
14
15
  openingAbort;
15
16
  closed = false;
17
+ groupRequests = new Map();
18
+ groupAbort = new AbortController();
16
19
  get identity() { return this.options.configuration.identity; }
17
20
  get client() { if (!this.connection)
18
21
  throw Error("PROFILE_WORKER_NOT_STARTED"); return this.connection; }
@@ -149,6 +152,23 @@ export class ProfileCoordinator {
149
152
  synchronize() { return this.invoke(client => client.synchronize()); }
150
153
  waitForCommand(id) { return this.invoke(client => client.waitForCommand(id)); }
151
154
  voiceAttachment(id) { return this.invoke(client => client.voiceAttachment(id)); }
155
+ /** Current group authority comes from Hub, independently of Inbox history. */
156
+ readGroup(groupId, teamId) {
157
+ if (this.closed)
158
+ 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
+ const network = this.options.configuration.network;
163
+ if (!network)
164
+ 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);
167
+ this.groupRequests.set(key, task);
168
+ void task.finally(() => { if (this.groupRequests.get(key) === task)
169
+ this.groupRequests.delete(key); }).catch(() => { });
170
+ return task;
171
+ }
152
172
  async updateToken(token) {
153
173
  if (!this.options.configuration.network)
154
174
  return;
@@ -160,6 +180,8 @@ export class ProfileCoordinator {
160
180
  if (this.closed)
161
181
  return;
162
182
  this.closed = true;
183
+ this.groupAbort.abort();
184
+ this.groupRequests.clear();
163
185
  // Stop the port immediately so requests cannot outlive the Profile.
164
186
  this.disposeWorker();
165
187
  await this.starting?.catch(() => { });
@@ -131,8 +131,6 @@ export class ProfileOwner {
131
131
  } };
132
132
  for (const thread of this.projection.threads.values())
133
133
  for (const [messageId, intents] of Object.entries(thread.internal?.pendingReadingIntents ?? {})) {
134
- if (!this.projection.messages.get(messageId)?.sourceSeq)
135
- continue;
136
134
  for (const intent of intents) {
137
135
  if (pending.length >= 200)
138
136
  await flush();
@@ -43,6 +43,16 @@ export type ProfileLocalOperation = {
43
43
  targetId: string;
44
44
  teamId: string;
45
45
  title?: string;
46
+ } | {
47
+ type: "groupSnapshot";
48
+ threadId: string;
49
+ group: import("./socialReadClient.js").SocialGroup;
50
+ expectedControlRevision?: number;
51
+ expectedAccessRevision: number;
52
+ } | {
53
+ type: "groupDenied";
54
+ threadId: string;
55
+ expectedAccessRevision: number;
46
56
  } | {
47
57
  type: "teamAccess";
48
58
  teamId: string;
@@ -13,7 +13,7 @@ function mergeAssignedLists(source, destination) {
13
13
  merged[key] = [...new Map([...(merged[key] ?? []), ...values].map(value => [JSON.stringify(value), value])).values()];
14
14
  return merged;
15
15
  }
16
- const supportedLocalOperations = new Set(["restoreReadingSources", "restoreMessageReadingFacts", "migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
16
+ const supportedLocalOperations = new Set(["restoreReadingSources", "restoreMessageReadingFacts", "migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "groupSnapshot", "groupDenied", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
17
17
  /** Committed authority for the replay reducer. Drafts contain only changed rows;
18
18
  * failure discards the draft, leaving both entities and indexes untouched. */
19
19
  export class ProfileProjection {
@@ -146,6 +146,10 @@ class ProfileProjectionDraft {
146
146
  return Error("PROFILE_OPERATION_UNSUPPORTED");
147
147
  if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
148
148
  return Error("PROFILE_ACCESS_CHECK_STALE");
149
+ if (operation.type === "groupSnapshot" && operation.expectedControlRevision !== undefined && operation.expectedControlRevision !== (this.thread(operation.threadId)?.internal?.groupControlRevision ?? 0))
150
+ return Error("GROUP_METADATA_STALE");
151
+ if ((operation.type === "groupSnapshot" || operation.type === "groupDenied") && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
152
+ return Error("PROFILE_ACCESS_CHECK_STALE");
149
153
  if (operation.type !== "send" && operation.type !== "observe")
150
154
  return;
151
155
  const thread = this.thread(operation.threadId);
@@ -432,6 +436,30 @@ class ProfileProjectionDraft {
432
436
  recipients: message.recipients, body: operation.message.body, threadKind: this.thread(message.threadId)?.kind === "dm" ? "dm" : "group" }) });
433
437
  return;
434
438
  }
439
+ if (operation.type === "groupSnapshot" || operation.type === "groupDenied") {
440
+ const thread = this.thread(operation.threadId);
441
+ if (!thread || thread.kind !== "group")
442
+ throw Error("INVALID_GROUP_CONVERSATION");
443
+ if (operation.type === "groupDenied") {
444
+ this.putThread({ ...thread, status: "unavailable", group: undefined, internal: { ...thread.internal, groupSource: "api" } });
445
+ return;
446
+ }
447
+ const group = operation.group;
448
+ if (group.appId !== this.base.identity.appId || group.teamId !== thread.teamId || group.groupId !== thread.internal?.targetId)
449
+ throw Error("INVALID_GROUP_METADATA");
450
+ if (thread.internal?.groupSource === "api" && thread.group) {
451
+ if (thread.group.versionNumber > group.versionNumber)
452
+ return;
453
+ if (thread.group.versionNumber === group.versionNumber && thread.group.revision !== group.revision)
454
+ throw Error("GROUP_REVISION_CONFLICT");
455
+ if (JSON.stringify(thread.group) === JSON.stringify(group) && thread.status === "ready")
456
+ return;
457
+ }
458
+ this.putThread({ ...thread, group, title: group.title ?? "", avatar: group.avatar ?? undefined,
459
+ status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready",
460
+ internal: { ...thread.internal, groupSource: "api" } });
461
+ return;
462
+ }
435
463
  if (operation.type === "register") {
436
464
  this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
437
465
  return;
@@ -534,9 +562,9 @@ class ProfileProjectionDraft {
534
562
  if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
535
563
  continue;
536
564
  if (!message.sourceSeq) {
537
- if (!thread.internal?.pendingReadingIntents?.[id]?.some(intent => intent.policy === operation.policy))
538
- this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: message.sourceThreadId, messageId: id,
539
- commandId: `${operation.commandId}:${encodeURIComponent(id)}`, policy: operation.policy, createdAt: operation.createdAt });
565
+ const previous = this.thread(message.sourceThreadId)?.internal?.pendingReadingIntents?.[id]?.find(intent => intent.policy === operation.policy);
566
+ this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: message.sourceThreadId, messageId: id,
567
+ commandId: previous?.commandId ?? `${operation.commandId}:${encodeURIComponent(id)}`, policy: operation.policy, createdAt: previous?.createdAt ?? operation.createdAt });
540
568
  continue;
541
569
  }
542
570
  const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
@@ -583,8 +611,12 @@ class ProfileProjectionDraft {
583
611
  if (body?.kind === "group") {
584
612
  const control = canonical ? { ...wire, threadId: parent.threadId, teamId: parent.teamId } : wire;
585
613
  const controls = { ...parent.internal?.groupControls, [wire.messageId]: control };
586
- const group = projectInboxGroup(this.base.identity.appId, wire.to, parent.teamId, Object.values(controls));
587
- this.putThread({ ...parent, internal: { ...parent.internal, groupControls: controls },
614
+ const group = parent.internal?.groupSource === "api" ? undefined : projectInboxGroup(this.base.identity.appId, wire.to, parent.teamId, Object.values(controls));
615
+ // A delivered removal/dissolution closes access immediately while Hub is
616
+ // rechecked. It never replaces the API-owned metadata with replayed state.
617
+ const revoked = parent.internal?.groupSource === "api" && (body.action === "groupDissolve" ||
618
+ body.action === "groupUpdate" && Array.isArray(body.payload?.members) && !body.payload.members.includes(this.base.identity.profileId));
619
+ this.putThread({ ...parent, ...(revoked ? { status: "unavailable" } : {}), internal: { ...parent.internal, groupControls: controls, groupControlRevision: (parent.internal?.groupControlRevision ?? 0) + 1 },
588
620
  ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined,
589
621
  status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}) });
590
622
  return;
@@ -657,6 +689,14 @@ class ProfileProjectionDraft {
657
689
  delete intents[operation.messageId];
658
690
  this.putThread({ ...source, internal: { ...source.internal, pendingReadingIntents: intents } });
659
691
  }
692
+ // Relationship-only historical invitations may never receive a message ordinal.
693
+ // Preserve an actual local observation separately from the deferred server cursor.
694
+ if (message && !message.sourceSeq && message.sourceThreadId === source.threadId &&
695
+ message.presentation?.kind === "invitation" && message.readPolicy === "visible" && operation.policy === "visible" &&
696
+ !message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId)) {
697
+ this.setMessage({ ...message, explicitReadingFacts: [...message.explicitReadingFacts,
698
+ { profileId: this.base.identity.profileId, kind: "observed" }] });
699
+ }
660
700
  if (!known || message.from === this.base.identity.profileId || message.recalled || message.readPolicy === "discussion" ||
661
701
  (operation.policy === "played") !== (message.readPolicy === "explicit"))
662
702
  return;
@@ -800,7 +840,7 @@ class ProfileProjectionDraft {
800
840
  const targetId = destination.internal?.targetId ?? source.internal?.targetId;
801
841
  const groupControls = Object.fromEntries(Object.entries({ ...source.internal?.groupControls, ...destination.internal?.groupControls })
802
842
  .map(([id, value]) => [id, { ...value, threadId: destination.threadId, teamId: data.teamId }]));
803
- const group = targetId ? projectInboxGroup(this.base.identity.appId, targetId, data.teamId, Object.values(groupControls)) : undefined;
843
+ const group = destination.internal?.groupSource === "api" ? destination.group : targetId ? projectInboxGroup(this.base.identity.appId, targetId, data.teamId, Object.values(groupControls)) : undefined;
804
844
  const organizationRevisions = { ...source.internal?.organizationRevisions };
805
845
  for (const [root, revision] of Object.entries(destination.internal?.organizationRevisions ?? {}))
806
846
  organizationRevisions[root] = Math.max(organizationRevisions[root] ?? -1, revision);
@@ -42,6 +42,8 @@ export type ProfileThread = {
42
42
  revision: number;
43
43
  internal?: {
44
44
  targetId?: string;
45
+ groupSource?: "api";
46
+ groupControlRevision?: number;
45
47
  groupControls?: Record<string, unknown>;
46
48
  organizationRevisions?: Record<string, number>;
47
49
  assignments?: Record<string, string>;
@@ -105,7 +107,7 @@ export type ProfileMessage = {
105
107
  receiptStatus: "unknown" | "ready";
106
108
  explicitReadingFacts: {
107
109
  profileId: string;
108
- kind: "played" | "preserved";
110
+ kind: "played" | "preserved" | "observed";
109
111
  revision?: string;
110
112
  }[];
111
113
  controlVersions: Record<string, string | number>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.13.0-profile.14",
3
+ "version": "0.13.0-profile.16",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",