@pmate/chat-sdk 0.13.0-profile.4 → 0.13.0-profile.6
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.
- package/lib/runtime/profileChat.d.ts +2 -1
- package/lib/runtime/profileChat.js +4 -5
- package/lib/runtime/profileCommitQueue.js +15 -2
- package/lib/runtime/profileDatabase.js +2 -2
- package/lib/runtime/profileLegacyInbox.js +5 -1
- package/lib/runtime/profileMemoryStore.d.ts +2 -0
- package/lib/runtime/profileMemoryStore.js +14 -5
- package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
- package/lib/runtime/profileOutboxDispatcher.js +38 -10
- package/lib/runtime/profileOwner.js +1 -1
- package/lib/runtime/profileProjection.d.ts +14 -3
- package/lib/runtime/profileProjection.js +112 -24
- package/lib/runtime/profileReadingIndex.js +1 -1
- package/lib/runtime/profileStoreTypes.d.ts +5 -0
- package/package.json +1 -1
|
@@ -133,8 +133,9 @@ export declare class ProfileChat implements Chat {
|
|
|
133
133
|
expectedRevision?: string;
|
|
134
134
|
}): Promise<ChatGroup>;
|
|
135
135
|
synchronizeReading(): Promise<void>;
|
|
136
|
-
revokeThread(id: string): Promise<void>;
|
|
137
136
|
revokeAccess(): Promise<void>;
|
|
137
|
+
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
138
|
+
grantAccess(expectedAccessRevision: number): Promise<void>;
|
|
138
139
|
firstUnread(id: string): string | undefined;
|
|
139
140
|
readPage(id: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly Readonly<{
|
|
140
141
|
id: string;
|
|
@@ -68,7 +68,7 @@ export class ProfileChat {
|
|
|
68
68
|
const parent = this.parent(id), thread = this.thread(id);
|
|
69
69
|
if (parent && parent.teamId !== this.teamId || thread && thread.teamId !== this.teamId)
|
|
70
70
|
return new ChatError("invalid-input", "Conversation belongs to another Team");
|
|
71
|
-
if (parent?.status === "unavailable" || thread?.status === "unavailable") {
|
|
71
|
+
if (!this.host.memory.isTeamAvailable(this.teamId) || parent?.status === "unavailable" || thread?.status === "unavailable") {
|
|
72
72
|
const error = new ChatError("access-denied", "Conversation unavailable", { threadId: id, status: 403 });
|
|
73
73
|
return parent?.kind === "group" ? scopedGroupDenial(error) : error;
|
|
74
74
|
}
|
|
@@ -352,10 +352,9 @@ export class ProfileChat {
|
|
|
352
352
|
async updateGroup(id, changes) { const previous = await this.getGroup(id); await this.sendControl(id, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
353
353
|
async dissolveGroup(id, options = {}) { const previous = await this.getGroup(id); await this.sendControl(id, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }); return this.waitGroup(id, previous.revision); }
|
|
354
354
|
synchronizeReading() { return this.host.synchronize(); }
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
await this.revokeThread(thread.threadId); }
|
|
355
|
+
revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
|
|
356
|
+
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
357
|
+
grantAccess(expectedAccessRevision) { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: true, expectedAccessRevision }, true); }
|
|
359
358
|
firstUnread(id) { this.assertAccessible(id); return this.thread(id)?.firstUnreadMessageId; }
|
|
360
359
|
readPage(id, anchor, limit, direction = "older") {
|
|
361
360
|
this.assertAccessible(id);
|
|
@@ -84,8 +84,21 @@ export class ProfileCommitQueue {
|
|
|
84
84
|
entry.resolve(); });
|
|
85
85
|
}
|
|
86
86
|
catch (error) {
|
|
87
|
-
|
|
88
|
-
|
|
87
|
+
if (error?.message === "PROFILE_WRITER_FENCED") {
|
|
88
|
+
// This producer can never commit again. Reject only its volatile intake;
|
|
89
|
+
// durable commands and the Inbox cursor remain with the next owner.
|
|
90
|
+
this.closed = true;
|
|
91
|
+
clearTimeout(this.timer);
|
|
92
|
+
const pending = this.entries.splice(0);
|
|
93
|
+
this.bytes = 0;
|
|
94
|
+
this.retryBatch = undefined;
|
|
95
|
+
for (const entry of pending)
|
|
96
|
+
entry.reject(error);
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
this.retryBatch = batch;
|
|
100
|
+
this.retryAt = Date.now() + this.options.retryMs;
|
|
101
|
+
}
|
|
89
102
|
try {
|
|
90
103
|
this.options.onError?.(error);
|
|
91
104
|
}
|
|
@@ -81,7 +81,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
81
81
|
throw Error("PROFILE_CURSOR_REGRESSION");
|
|
82
82
|
const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
|
|
83
83
|
const localMigrations = batch.localMigrations ? [...new Set([...(current.localMigrations ?? []), ...batch.localMigrations])] : current.localMigrations;
|
|
84
|
-
if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations))
|
|
84
|
+
if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision)
|
|
85
85
|
return current;
|
|
86
86
|
if (batch.messages?.length)
|
|
87
87
|
await this.messages.bulkPut(batch.messages);
|
|
@@ -99,7 +99,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
99
99
|
await this.outbox.bulkDelete(batch.deleteOutbox);
|
|
100
100
|
if (!Number.isSafeInteger(current.commitRevision + 1))
|
|
101
101
|
throw Error("PROFILE_REVISION_EXHAUSTED");
|
|
102
|
-
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
102
|
+
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
103
103
|
await this.inboxState.put(next);
|
|
104
104
|
return next;
|
|
105
105
|
});
|
|
@@ -81,8 +81,12 @@ export async function migrateLegacyInbox(owner, options = {}) {
|
|
|
81
81
|
await push(restore("messageAdded", row.value, row.id));
|
|
82
82
|
rows.messages.sort((a, b) => a.value.serverCreatedAt - b.value.serverCreatedAt || a.value.threadId.localeCompare(b.value.threadId) || (a.value.seq ?? 0) - (b.value.seq ?? 0) || a.id.localeCompare(b.id));
|
|
83
83
|
for (const row of rows.messages) {
|
|
84
|
-
if (!row.value.seq)
|
|
84
|
+
if (!row.value.seq) {
|
|
85
|
+
const body = row.value.body;
|
|
86
|
+
if (body?.kind === "contact" && body.action === "friendRequest")
|
|
87
|
+
await push({ type: "restoreInvitation", message: row.value, acceptedAt: row.acceptedAt, recalled: row.recalled });
|
|
85
88
|
continue;
|
|
89
|
+
}
|
|
86
90
|
const body = row.value.body;
|
|
87
91
|
const value = row.root ? { ...row.value, body: { ...body, content: { ...body?.content, threadRootId: row.root } } } : row.value;
|
|
88
92
|
await push({ ...restore("messageAdded", { ...value, sourceAcceptedAt: row.acceptedAt }, row.id, row.acceptedAt), recalled: row.recalled });
|
|
@@ -56,6 +56,8 @@ export declare class ProfileMemoryStore {
|
|
|
56
56
|
};
|
|
57
57
|
getThread(threadId: string): ProfileThread | undefined;
|
|
58
58
|
getMessage(messageId: string): ProfileMessage | undefined;
|
|
59
|
+
getAccessRevision(): number;
|
|
60
|
+
isTeamAvailable(teamId: string | undefined): boolean;
|
|
59
61
|
isThreadAvailable(threadId: string): boolean;
|
|
60
62
|
getPresentedMessage(messageId: string): Readonly<{
|
|
61
63
|
id: string;
|
|
@@ -47,9 +47,11 @@ export class ProfileMemoryStore {
|
|
|
47
47
|
getStatus() { return { phase: this.phase, generation: this.current?.activeGeneration, revision: this.current?.commitRevision }; }
|
|
48
48
|
getThread(threadId) { return this.threads.get(threadId); }
|
|
49
49
|
getMessage(messageId) { return this.entities.get(messageId); }
|
|
50
|
+
getAccessRevision() { return this.current?.teamAccessRevision ?? 0; }
|
|
51
|
+
isTeamAvailable(teamId) { return !teamId || !this.current?.revokedTeamIds?.includes(teamId); }
|
|
50
52
|
isThreadAvailable(threadId) {
|
|
51
53
|
const thread = this.threads.get(threadId);
|
|
52
|
-
return thread?.status === "ready" && (!thread.parentThreadId || this.threads.get(thread.parentThreadId)?.status === "ready");
|
|
54
|
+
return thread?.status === "ready" && this.isTeamAvailable(thread.teamId) && (!thread.parentThreadId || this.threads.get(thread.parentThreadId)?.status === "ready" && this.isTeamAvailable(this.threads.get(thread.parentThreadId)?.teamId));
|
|
53
55
|
}
|
|
54
56
|
getPresentedMessage(messageId) {
|
|
55
57
|
const message = this.entities.get(messageId);
|
|
@@ -236,6 +238,11 @@ export class ProfileMemoryStore {
|
|
|
236
238
|
directory.accept({ windows: [window], windowCount: 0 });
|
|
237
239
|
affected.add(window.threadId);
|
|
238
240
|
}
|
|
241
|
+
const accessChanged = new Set([...(this.current.revokedTeamIds ?? []), ...(delta.current.revokedTeamIds ?? [])].filter(id => this.current.revokedTeamIds?.includes(id) !== delta.current.revokedTeamIds?.includes(id)));
|
|
242
|
+
if (accessChanged.size)
|
|
243
|
+
for (const thread of this.threads.values())
|
|
244
|
+
if (thread.teamId && accessChanged.has(thread.teamId))
|
|
245
|
+
affected.add(thread.threadId);
|
|
239
246
|
this.current = delta.current;
|
|
240
247
|
for (const message of delta.messages) {
|
|
241
248
|
this.indexMessage(message);
|
|
@@ -273,7 +280,7 @@ export class ProfileMemoryStore {
|
|
|
273
280
|
}
|
|
274
281
|
}
|
|
275
282
|
}
|
|
276
|
-
this.publish(affected, delta.threads.length > 0);
|
|
283
|
+
this.publish(affected, delta.threads.length > 0 || accessChanged.size > 0);
|
|
277
284
|
if (added.length)
|
|
278
285
|
for (const listener of this.messageListeners)
|
|
279
286
|
this.notify(() => listener(added));
|
|
@@ -292,14 +299,16 @@ export class ProfileMemoryStore {
|
|
|
292
299
|
mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
|
|
293
300
|
source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
|
|
294
301
|
policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
|
|
302
|
+
const discussionStatus = policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus : undefined;
|
|
303
|
+
const readingUnknown = policy === "discussion" && discussionStatus !== "read" && discussionStatus !== "unread" || !message.sourceSeq && !mine && !read || thread?.readingStatus === "unknown" && !thread.internal?.unknownReadingCount;
|
|
295
304
|
const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
|
|
296
305
|
from: message.from, recipients: message.recipients, body: message.content, threadKind: thread?.kind === "dm" ? "dm" : "group", teamId: thread?.teamId });
|
|
297
306
|
const visibleContent = message.recalled ? { kind: "system", text: "" } : content;
|
|
298
307
|
const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
|
|
299
308
|
...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
|
|
300
309
|
status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
|
|
301
|
-
recalled: message.recalled ?? false, unread:
|
|
302
|
-
attentionEligible: message.mention, reading:
|
|
310
|
+
recalled: message.recalled ?? false, unread: readingUnknown ? undefined : !read,
|
|
311
|
+
attentionEligible: message.mention, reading: readingUnknown ? undefined : { seq: message.sourceSeq, read,
|
|
303
312
|
readPolicy: policy === "visible" ? "visible" : "explicit" },
|
|
304
313
|
reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
|
|
305
314
|
this.presented.set(message.messageId, value);
|
|
@@ -343,7 +352,7 @@ export class ProfileMemoryStore {
|
|
|
343
352
|
if (affected.has(JSON.parse(key)[0]))
|
|
344
353
|
this.pageCache.delete(key);
|
|
345
354
|
if (directoryChanged) {
|
|
346
|
-
this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion")
|
|
355
|
+
this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion" && this.isTeamAvailable(thread.teamId))
|
|
347
356
|
.sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.threadId.localeCompare(b.threadId));
|
|
348
357
|
}
|
|
349
358
|
for (const thread of affected)
|
|
@@ -17,6 +17,7 @@ export declare class ProfileOutboxDispatcher {
|
|
|
17
17
|
private timer?;
|
|
18
18
|
private scheduled?;
|
|
19
19
|
private off?;
|
|
20
|
+
private retryAt;
|
|
20
21
|
private closed;
|
|
21
22
|
private controller;
|
|
22
23
|
constructor(options: ProfileOutboxDispatcherOptions);
|
|
@@ -25,6 +26,8 @@ export declare class ProfileOutboxDispatcher {
|
|
|
25
26
|
private schedule;
|
|
26
27
|
drain(): Promise<void>;
|
|
27
28
|
private transition;
|
|
29
|
+
private target;
|
|
30
|
+
private nextCommand;
|
|
28
31
|
private run;
|
|
29
32
|
private reading;
|
|
30
33
|
close(): Promise<void>;
|
|
@@ -8,6 +8,7 @@ export class ProfileOutboxDispatcher {
|
|
|
8
8
|
timer;
|
|
9
9
|
scheduled;
|
|
10
10
|
off;
|
|
11
|
+
retryAt = new Map();
|
|
11
12
|
closed = false;
|
|
12
13
|
controller = new AbortController();
|
|
13
14
|
constructor(options) {
|
|
@@ -38,26 +39,51 @@ export class ProfileOutboxDispatcher {
|
|
|
38
39
|
return this.running;
|
|
39
40
|
const task = this.run();
|
|
40
41
|
this.running = task;
|
|
41
|
-
void task.finally(() => { if (this.running === task)
|
|
42
|
-
this.running = undefined;
|
|
42
|
+
void task.finally(() => { if (this.running === task) {
|
|
43
|
+
this.running = undefined;
|
|
44
|
+
if (!this.closed && this.options.owner.active && this.nextCommand())
|
|
45
|
+
this.schedule();
|
|
46
|
+
} }).catch(() => { });
|
|
43
47
|
return task;
|
|
44
48
|
}
|
|
45
49
|
async transition(command, state) {
|
|
46
50
|
await this.options.owner.enqueue({ type: "commandResult", commandId: command.commandId, state }, 128, true);
|
|
47
51
|
}
|
|
48
|
-
|
|
52
|
+
target(command) {
|
|
53
|
+
const memory = this.options.owner.memory, thread = memory.getThread(command.threadId);
|
|
54
|
+
const parent = thread?.parentThreadId ? memory.getThread(thread.parentThreadId) : thread;
|
|
55
|
+
const canonical = parent?.internal?.assignments?.[parent.threadId] ?? parent?.threadId ?? command.threadId;
|
|
56
|
+
const root = command.kind !== "message" ? command.payload.threadRootId : thread?.rootMessageId;
|
|
57
|
+
return { scope: JSON.stringify([canonical, command.kind === "message" ? "message" : "reading", command.kind === "message" ? null : root ?? null]), threadId: root ? profileDiscussionId(canonical, root) : canonical };
|
|
58
|
+
}
|
|
59
|
+
nextCommand(blocked = new Set()) {
|
|
49
60
|
const owner = this.options.owner;
|
|
61
|
+
if (owner.memory.getStatus().phase !== "ready")
|
|
62
|
+
return;
|
|
63
|
+
const commands = owner.commands().sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId));
|
|
64
|
+
const existing = new Set(commands.map(command => command.commandId));
|
|
65
|
+
for (const id of this.retryAt.keys())
|
|
66
|
+
if (!existing.has(id))
|
|
67
|
+
this.retryAt.delete(id);
|
|
68
|
+
for (const command of commands) {
|
|
69
|
+
const target = this.target(command);
|
|
70
|
+
if (blocked.has(target.scope) || !owner.memory.isThreadAvailable(target.threadId))
|
|
71
|
+
continue;
|
|
72
|
+
if (command.state === "failed" && (this.retryAt.get(command.commandId) ?? 0) > Date.now()) {
|
|
73
|
+
blocked.add(target.scope);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
return command;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async run() {
|
|
80
|
+
const owner = this.options.owner, blocked = new Set();
|
|
50
81
|
// Refresh from committed memory after each ACK so work accepted during a
|
|
51
82
|
// network wait is picked up without waiting for another ten-second tick.
|
|
52
83
|
while (!this.closed && owner.active) {
|
|
53
84
|
if (owner.memory.getStatus().phase !== "ready")
|
|
54
85
|
return;
|
|
55
|
-
const command =
|
|
56
|
-
const thread = owner.memory.getThread(command.threadId);
|
|
57
|
-
const canonical = thread?.internal?.assignments?.[thread.threadId] ?? command.threadId;
|
|
58
|
-
const root = command.kind !== "message" ? command.payload.threadRootId : undefined;
|
|
59
|
-
return owner.memory.isThreadAvailable(root ? profileDiscussionId(canonical, root) : canonical);
|
|
60
|
-
}).sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId))[0];
|
|
86
|
+
const command = this.nextCommand(blocked);
|
|
61
87
|
if (!command)
|
|
62
88
|
return;
|
|
63
89
|
await this.transition(command, "sending");
|
|
@@ -82,12 +108,14 @@ export class ProfileOutboxDispatcher {
|
|
|
82
108
|
await this.reading(command);
|
|
83
109
|
if (!this.closed && owner.active)
|
|
84
110
|
await this.transition(command, "confirmed");
|
|
111
|
+
this.retryAt.delete(command.commandId);
|
|
85
112
|
}
|
|
86
113
|
catch (error) {
|
|
114
|
+
this.retryAt.set(command.commandId, Date.now() + 10000);
|
|
115
|
+
blocked.add(this.target(command).scope);
|
|
87
116
|
if (!this.closed && owner.active)
|
|
88
117
|
await this.transition(command, "failed");
|
|
89
118
|
this.report(error);
|
|
90
|
-
return;
|
|
91
119
|
}
|
|
92
120
|
}
|
|
93
121
|
}
|
|
@@ -218,7 +218,7 @@ export class ProfileOwner {
|
|
|
218
218
|
const prepared = this.projection.prepare(events);
|
|
219
219
|
const committed = await this.options.database.commit({ ...prepared, ownerId: this.lease.ownerId, fence: this.lease.fence,
|
|
220
220
|
generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
|
|
221
|
-
committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations });
|
|
221
|
+
committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
|
|
222
222
|
if (committed.commitRevision === fromRevision)
|
|
223
223
|
return prepared.rejected;
|
|
224
224
|
prepared.current = committed;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type InboxEvent, type InboxBootstrap } from "./inboxStore.js";
|
|
1
|
+
import { type InboxEvent, type InboxMessage, type InboxBootstrap } from "./inboxStore.js";
|
|
2
2
|
import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
3
3
|
import { ProfileWindowDirectory } from "./profileWindows.js";
|
|
4
4
|
import type { ProfileSnapshot } from "./profileMemoryStore.js";
|
|
@@ -23,6 +23,11 @@ export type ProfileLocalOperation = {
|
|
|
23
23
|
type: "restoreEvent";
|
|
24
24
|
event: InboxEvent;
|
|
25
25
|
recalled?: boolean;
|
|
26
|
+
} | {
|
|
27
|
+
type: "restoreInvitation";
|
|
28
|
+
message: InboxMessage;
|
|
29
|
+
acceptedAt: number;
|
|
30
|
+
recalled?: boolean;
|
|
26
31
|
} | {
|
|
27
32
|
type: "register";
|
|
28
33
|
threadId: string;
|
|
@@ -31,8 +36,14 @@ export type ProfileLocalOperation = {
|
|
|
31
36
|
teamId: string;
|
|
32
37
|
title?: string;
|
|
33
38
|
} | {
|
|
34
|
-
type: "
|
|
35
|
-
|
|
39
|
+
type: "teamAccess";
|
|
40
|
+
teamId: string;
|
|
41
|
+
allowed: false;
|
|
42
|
+
} | {
|
|
43
|
+
type: "teamAccess";
|
|
44
|
+
teamId: string;
|
|
45
|
+
allowed: true;
|
|
46
|
+
expectedAccessRevision: number;
|
|
36
47
|
} | {
|
|
37
48
|
type: "send";
|
|
38
49
|
threadId: string;
|
|
@@ -7,6 +7,7 @@ import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
|
7
7
|
import { compareProfileOrder, ProfileWindowDirectory } from "./profileWindows.js";
|
|
8
8
|
import { projectMessageContent } from "../messageView.js";
|
|
9
9
|
export const profileDiscussionId = (parent, root) => `discussion:${JSON.stringify([parent, root])}`;
|
|
10
|
+
const supportedLocalOperations = new Set(["migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
|
|
10
11
|
/** Committed authority for the replay reducer. Drafts contain only changed rows;
|
|
11
12
|
* failure discards the draft, leaving both entities and indexes untouched. */
|
|
12
13
|
export class ProfileProjection {
|
|
@@ -125,6 +126,8 @@ class ProfileProjectionDraft {
|
|
|
125
126
|
revision;
|
|
126
127
|
receiptsReady;
|
|
127
128
|
localMigrations;
|
|
129
|
+
revokedTeamIds;
|
|
130
|
+
teamAccessRevision;
|
|
128
131
|
readingCommands = new Map();
|
|
129
132
|
constructor(base) {
|
|
130
133
|
this.base = base;
|
|
@@ -133,11 +136,17 @@ class ProfileProjectionDraft {
|
|
|
133
136
|
this.receiptsReady = base.current.receiptsReady;
|
|
134
137
|
}
|
|
135
138
|
localAccessError(operation) {
|
|
139
|
+
if (!supportedLocalOperations.has(operation.type))
|
|
140
|
+
return Error("PROFILE_OPERATION_UNSUPPORTED");
|
|
141
|
+
if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
|
|
142
|
+
return Error("PROFILE_ACCESS_CHECK_STALE");
|
|
136
143
|
if (operation.type !== "send" && operation.type !== "observe")
|
|
137
144
|
return;
|
|
138
145
|
const thread = this.thread(operation.threadId);
|
|
139
146
|
const parentId = thread?.parentThreadId ?? (operation.type === "send" ? operation.parentThreadId : undefined);
|
|
140
147
|
const parent = parentId ? this.thread(parentId) : undefined;
|
|
148
|
+
if ((this.revokedTeamIds ?? this.base.current.revokedTeamIds ?? []).includes((parent ?? thread)?.teamId ?? ""))
|
|
149
|
+
return Error("PROFILE_TEAM_ACCESS_REVOKED");
|
|
141
150
|
if (thread?.status !== "ready" && !(operation.type === "send" && !thread && parent?.status === "ready") || parentId && parent?.status !== "ready")
|
|
142
151
|
return Error("PROFILE_THREAD_NOT_READY");
|
|
143
152
|
if (operation.type === "send") {
|
|
@@ -213,27 +222,49 @@ class ProfileProjectionDraft {
|
|
|
213
222
|
return this.thread(message.discussionThreadId)?.readingStatus === "read";
|
|
214
223
|
if (message.from === this.base.identity.profileId)
|
|
215
224
|
return true;
|
|
216
|
-
if (!message.sourceSeq)
|
|
217
|
-
return false;
|
|
218
225
|
if (message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId))
|
|
219
226
|
return true;
|
|
220
227
|
const source = thread && this.source(thread, message.sourceThreadId);
|
|
221
228
|
if (source?.preservedReadMessageIds.includes(message.messageId) || source?.explicitReadMessageIds.includes(message.messageId) || source?.pendingExplicitReadMessageIds?.includes(message.messageId))
|
|
222
229
|
return true;
|
|
223
|
-
return message.readPolicy !== "explicit" && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0);
|
|
230
|
+
return !!message.sourceSeq && message.readPolicy !== "explicit" && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0);
|
|
231
|
+
}
|
|
232
|
+
unknownReading(message, thread = message && this.thread(message.threadId)) {
|
|
233
|
+
return message && !message.sourceSeq && message.from !== this.base.identity.profileId && !this.read(message, thread) ? 1 : 0;
|
|
224
234
|
}
|
|
225
235
|
contribution(message, thread) {
|
|
226
|
-
return message && message.readPolicy !== "discussion" && !this.read(message, thread) ? { unread: 1, mentions: message.mention ? 1 : 0 } : { unread: 0, mentions: 0 };
|
|
236
|
+
return message && !this.unknownReading(message, thread) && message.readPolicy !== "discussion" && !this.read(message, thread) ? { unread: 1, mentions: message.mention ? 1 : 0 } : { unread: 0, mentions: 0 };
|
|
227
237
|
}
|
|
228
|
-
updateSummary(id, unreadDelta, mentionDelta) {
|
|
229
|
-
if (!unreadDelta && !mentionDelta)
|
|
238
|
+
updateSummary(id, unreadDelta, mentionDelta, unknownDelta = 0) {
|
|
239
|
+
if (!unreadDelta && !mentionDelta && !unknownDelta)
|
|
230
240
|
return;
|
|
231
241
|
const thread = this.thread(id);
|
|
232
|
-
const
|
|
233
|
-
|
|
242
|
+
const unknownReadingCount = Math.max(0, (thread.internal?.unknownReadingCount ?? 0) + unknownDelta);
|
|
243
|
+
let unreadCount = null, mentionCount = null;
|
|
244
|
+
if (!unknownReadingCount) {
|
|
245
|
+
if (thread.unreadCount === null || thread.mentionCount === null) {
|
|
246
|
+
const summary = this.readingIndex(id).summary(thread.readingSources);
|
|
247
|
+
unreadCount = summary.unread;
|
|
248
|
+
mentionCount = summary.mentions;
|
|
249
|
+
const children = new Set(this.base.children.get(id));
|
|
250
|
+
for (const row of this.threads.values())
|
|
251
|
+
if (row.parentThreadId === id)
|
|
252
|
+
children.add(row.threadId);
|
|
253
|
+
for (const childId of children) {
|
|
254
|
+
const child = this.thread(childId);
|
|
255
|
+
unreadCount += child?.unreadCount ?? 0;
|
|
256
|
+
mentionCount += child?.mentionCount ?? 0;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
unreadCount = Math.max(0, thread.unreadCount + unreadDelta);
|
|
261
|
+
mentionCount = Math.max(0, thread.mentionCount + mentionDelta);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
this.putThread({ ...thread, unreadCount, mentionCount, internal: { ...thread.internal, unknownReadingCount },
|
|
234
265
|
firstUnreadMessageId: this.firstUnread(id), readingStatus: unreadCount === null ? "unknown" : unreadCount > 0 ? "unread" : "read" });
|
|
235
266
|
if (thread.parentThreadId)
|
|
236
|
-
this.updateSummary(thread.parentThreadId, unreadDelta, mentionDelta);
|
|
267
|
+
this.updateSummary(thread.parentThreadId, unreadDelta, mentionDelta, unknownDelta);
|
|
237
268
|
}
|
|
238
269
|
setMessage(next) {
|
|
239
270
|
const previous = this.message(next.messageId);
|
|
@@ -243,11 +274,11 @@ class ProfileProjectionDraft {
|
|
|
243
274
|
this.readingIndex(next.threadId).upsert(next, this.base.identity.profileId, this.source(this.thread(next.threadId), next.sourceThreadId));
|
|
244
275
|
this.messages.set(next.messageId, { ...next, revision: this.revision });
|
|
245
276
|
if (previous?.threadId === next.threadId)
|
|
246
|
-
this.updateSummary(next.threadId, after.unread - before.unread, after.mentions - before.mentions);
|
|
277
|
+
this.updateSummary(next.threadId, after.unread - before.unread, after.mentions - before.mentions, this.unknownReading(next) - this.unknownReading(previous));
|
|
247
278
|
else {
|
|
248
279
|
if (previous)
|
|
249
|
-
this.updateSummary(previous.threadId, -before.unread, -before.mentions);
|
|
250
|
-
this.updateSummary(next.threadId, after.unread, after.mentions);
|
|
280
|
+
this.updateSummary(previous.threadId, -before.unread, -before.mentions, -this.unknownReading(previous));
|
|
281
|
+
this.updateSummary(next.threadId, after.unread, after.mentions, this.unknownReading(next));
|
|
251
282
|
}
|
|
252
283
|
}
|
|
253
284
|
insert(message, historical = false) {
|
|
@@ -315,7 +346,7 @@ class ProfileProjectionDraft {
|
|
|
315
346
|
this.assign(event);
|
|
316
347
|
break;
|
|
317
348
|
case "relationshipUpdated":
|
|
318
|
-
this.relationship(event);
|
|
349
|
+
this.relationship(event, basis);
|
|
319
350
|
break;
|
|
320
351
|
default: throw Error(`UNSUPPORTED_INBOX_EVENT:${event.kind}`);
|
|
321
352
|
}
|
|
@@ -323,6 +354,30 @@ class ProfileProjectionDraft {
|
|
|
323
354
|
this.seq = seq;
|
|
324
355
|
}
|
|
325
356
|
local(operation) {
|
|
357
|
+
if (operation.type === "restoreInvitation") {
|
|
358
|
+
const wire = operation.message, body = wire.body;
|
|
359
|
+
if (wire.appId !== this.base.identity.appId || wire.seq || body?.kind !== "contact" || body.action !== "friendRequest" || ![wire.from, wire.to].includes(this.base.identity.profileId))
|
|
360
|
+
throw Error("INVALID_LEGACY_INVITATION");
|
|
361
|
+
this.invitation({ threadId: wire.threadId, messageId: wire.messageId, actorId: wire.from, targetId: wire.to, teamId: wire.teamId, createdAt: wire.serverCreatedAt }, operation.acceptedAt);
|
|
362
|
+
const message = operation.recalled && this.message(wire.messageId);
|
|
363
|
+
if (message && !message.recalled)
|
|
364
|
+
this.setMessage({ ...message, recalled: true });
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (operation.type === "teamAccess") {
|
|
368
|
+
if (!operation.teamId)
|
|
369
|
+
throw Error("INVALID_PROFILE_TEAM");
|
|
370
|
+
const revoked = new Set(this.revokedTeamIds ?? this.base.current.revokedTeamIds ?? []);
|
|
371
|
+
if (operation.allowed && !revoked.has(operation.teamId))
|
|
372
|
+
return;
|
|
373
|
+
if (operation.allowed)
|
|
374
|
+
revoked.delete(operation.teamId);
|
|
375
|
+
else
|
|
376
|
+
revoked.add(operation.teamId);
|
|
377
|
+
this.revokedTeamIds = [...revoked].sort();
|
|
378
|
+
this.teamAccessRevision = (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0) + 1;
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
326
381
|
if (operation.type === "restoreReadingCommand") {
|
|
327
382
|
const command = operation.command, data = command.payload;
|
|
328
383
|
if (!["reading", "played"].includes(command.kind) || !command.commandId || data.appId !== this.base.identity.appId || data.profileId !== this.base.identity.profileId)
|
|
@@ -363,12 +418,6 @@ class ProfileProjectionDraft {
|
|
|
363
418
|
this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
|
|
364
419
|
return;
|
|
365
420
|
}
|
|
366
|
-
if (operation.type === "revoke") {
|
|
367
|
-
const thread = this.thread(operation.threadId);
|
|
368
|
-
if (thread && thread.status !== "unavailable")
|
|
369
|
-
this.putThread({ ...thread, status: "unavailable", readingStatus: "unknown", unreadCount: null, mentionCount: null });
|
|
370
|
-
return;
|
|
371
|
-
}
|
|
372
421
|
if (operation.type === "restoreReceipt") {
|
|
373
422
|
this.reading({ inboxSeq: "0", sourceId: "receipt-baseline", acceptedAt: 0, kind: "readingUpdated", fact: { ...operation.data, receiptOnly: true } });
|
|
374
423
|
return;
|
|
@@ -466,6 +515,12 @@ class ProfileProjectionDraft {
|
|
|
466
515
|
continue;
|
|
467
516
|
if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
|
|
468
517
|
continue;
|
|
518
|
+
if (!message.sourceSeq) {
|
|
519
|
+
if (!thread.internal?.pendingReadingIntents?.[id]?.some(intent => intent.policy === operation.policy))
|
|
520
|
+
this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: message.sourceThreadId, messageId: id,
|
|
521
|
+
commandId: `${operation.commandId}:${encodeURIComponent(id)}`, policy: operation.policy, createdAt: operation.createdAt });
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
469
524
|
const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
|
|
470
525
|
if (operation.policy === "played" || !message.sourceSeq)
|
|
471
526
|
group.explicitReadMessageIds.push(id);
|
|
@@ -680,8 +735,12 @@ class ProfileProjectionDraft {
|
|
|
680
735
|
index.remove(message);
|
|
681
736
|
}
|
|
682
737
|
const after = index.summary(next.readingSources);
|
|
738
|
+
const unknownDelta = [...new Set(data.explicitReadMessageIds)].reduce((delta, messageId) => {
|
|
739
|
+
const message = this.message(messageId);
|
|
740
|
+
return message?.threadId === id ? delta + this.unknownReading(message, next) - this.unknownReading(message, thread) : delta;
|
|
741
|
+
}, 0);
|
|
683
742
|
this.putThread(next);
|
|
684
|
-
this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions);
|
|
743
|
+
this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions, unknownDelta);
|
|
685
744
|
}
|
|
686
745
|
organize(event) {
|
|
687
746
|
const data = event.fact;
|
|
@@ -721,16 +780,45 @@ class ProfileProjectionDraft {
|
|
|
721
780
|
this.move(this.message(ref.messageId), destination.threadId);
|
|
722
781
|
this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...source.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
|
|
723
782
|
}
|
|
724
|
-
relationship(event) {
|
|
783
|
+
relationship(event, basis = false) {
|
|
725
784
|
const data = event.fact;
|
|
726
785
|
if (!data.pairId || ![data.actorId, data.targetId].includes(this.base.identity.profileId))
|
|
727
786
|
throw Error("INVALID_INBOX_RELATIONSHIP");
|
|
728
|
-
if (data.threadId)
|
|
729
|
-
|
|
787
|
+
if (!data.threadId) {
|
|
788
|
+
if (data.action === "friendRequest" && data.messageId && !basis && event.acceptedAt >= this.base.windowStart)
|
|
789
|
+
throw Error("INVALID_INBOX_INVITATION");
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
const peer = data.actorId === this.base.identity.profileId ? data.targetId : data.actorId;
|
|
793
|
+
this.ensureDirectThread(data.threadId, peer, data.teamId);
|
|
794
|
+
if (data.action !== "friendRequest" || typeof data.messageId !== "string" || basis || event.acceptedAt < this.base.windowStart)
|
|
795
|
+
return;
|
|
796
|
+
this.invitation(data, event.acceptedAt);
|
|
797
|
+
}
|
|
798
|
+
ensureDirectThread(id, peer, teamId) {
|
|
799
|
+
const thread = this.ensure(id, "dm", { teamId, internal: { targetId: peer } });
|
|
800
|
+
if (thread.kind !== "dm" || thread.teamId !== teamId || thread.internal?.targetId !== peer)
|
|
801
|
+
this.putThread({ ...thread, kind: "dm", teamId, internal: { ...thread.internal, targetId: peer } });
|
|
802
|
+
}
|
|
803
|
+
invitation(data, acceptedAt) {
|
|
804
|
+
if (acceptedAt < this.base.windowStart)
|
|
805
|
+
return;
|
|
806
|
+
if (!data.threadId || !data.messageId || !data.actorId || !data.targetId || !Number.isSafeInteger(data.createdAt))
|
|
807
|
+
throw Error("INVALID_INBOX_INVITATION");
|
|
808
|
+
this.ensureDirectThread(data.threadId, data.actorId === this.base.identity.profileId ? data.targetId : data.actorId, data.teamId);
|
|
809
|
+
if (this.message(data.messageId))
|
|
810
|
+
return;
|
|
811
|
+
const body = { kind: "contact", threadKind: "dm", action: "friendRequest", payload: { appId: this.base.identity.appId, ...(data.teamId ? { teamId: data.teamId } : {}) } };
|
|
812
|
+
const message = { generation: this.base.current.activeGeneration, messageId: data.messageId, threadId: data.threadId, sourceThreadId: data.threadId,
|
|
813
|
+
orderKey: [data.createdAt, data.threadId, 0, data.messageId], from: data.actorId, recipients: [data.targetId], content: body, attachmentRefs: [], reactions: [], readBy: [], receiptStatus: "unknown",
|
|
814
|
+
explicitReadingFacts: [], controlVersions: {}, readPolicy: "visible", revision: this.revision,
|
|
815
|
+
presentation: projectMessageContent({ id: data.messageId, threadId: data.threadId, threadKind: "dm", teamId: data.teamId, timestamp: data.createdAt, from: data.actorId, recipients: [data.targetId], body }) };
|
|
816
|
+
this.setMessage(message);
|
|
817
|
+
this.insert(message, true);
|
|
730
818
|
}
|
|
731
819
|
finish() {
|
|
732
820
|
return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
|
|
733
|
-
localMigrations: this.localMigrations ?? this.base.current.localMigrations },
|
|
821
|
+
localMigrations: this.localMigrations ?? this.base.current.localMigrations, revokedTeamIds: this.revokedTeamIds ?? this.base.current.revokedTeamIds, teamAccessRevision: this.teamAccessRevision ?? this.base.current.teamAccessRevision },
|
|
734
822
|
threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
|
|
735
823
|
outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
|
|
736
824
|
}
|
|
@@ -82,7 +82,7 @@ export class ProfileReadingIndex {
|
|
|
82
82
|
}
|
|
83
83
|
upsert(message, profileId, source) {
|
|
84
84
|
this.remove(message);
|
|
85
|
-
if (message.from === profileId || message.recalled || message.readPolicy === "discussion" ||
|
|
85
|
+
if (!message.sourceSeq || message.from === profileId || message.recalled || message.readPolicy === "discussion" ||
|
|
86
86
|
message.explicitReadingFacts.some(fact => fact.profileId === profileId) ||
|
|
87
87
|
source?.explicitReadMessageIds.includes(message.messageId) || source?.pendingExplicitReadMessageIds?.includes(message.messageId) || source?.preservedReadMessageIds.includes(message.messageId))
|
|
88
88
|
return;
|
|
@@ -54,6 +54,7 @@ export type ProfileThread = {
|
|
|
54
54
|
createdAt: number;
|
|
55
55
|
}[]>;
|
|
56
56
|
participantCounts?: Record<string, number>;
|
|
57
|
+
unknownReadingCount?: number;
|
|
57
58
|
};
|
|
58
59
|
};
|
|
59
60
|
export type ProfileMessageRef = {
|
|
@@ -119,6 +120,8 @@ export type ProfileCurrentState = {
|
|
|
119
120
|
commitRevision: number;
|
|
120
121
|
receiptsReady?: boolean;
|
|
121
122
|
localMigrations?: string[];
|
|
123
|
+
revokedTeamIds?: string[];
|
|
124
|
+
teamAccessRevision?: number;
|
|
122
125
|
};
|
|
123
126
|
export type ProfileWriterLease = {
|
|
124
127
|
key: "lease";
|
|
@@ -160,6 +163,8 @@ export type ProfileWriteBatch = {
|
|
|
160
163
|
committedSeq: string;
|
|
161
164
|
receiptsReady?: boolean;
|
|
162
165
|
localMigrations?: string[];
|
|
166
|
+
revokedTeamIds?: string[];
|
|
167
|
+
teamAccessRevision?: number;
|
|
163
168
|
threads?: ProfileThread[];
|
|
164
169
|
windows?: ProfileWindow[];
|
|
165
170
|
messages?: ProfileMessage[];
|
package/package.json
CHANGED