@pmate/chat-sdk 0.13.0-profile.5 → 0.13.0-profile.7
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 +0 -1
- package/lib/runtime/profileChat.js +0 -1
- package/lib/runtime/profileCommitQueue.js +15 -2
- package/lib/runtime/profileDatabase.js +14 -6
- package/lib/runtime/profileGenerationBuilder.js +1 -1
- package/lib/runtime/profileLegacyInbox.js +5 -1
- package/lib/runtime/profileMemoryStore.js +4 -2
- package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
- package/lib/runtime/profileOutboxDispatcher.js +38 -10
- package/lib/runtime/profileOwner.js +3 -3
- package/lib/runtime/profileProjection.d.ts +6 -4
- package/lib/runtime/profileProjection.js +91 -23
- package/lib/runtime/profileReadingIndex.js +1 -1
- package/lib/runtime/profileStoreTypes.d.ts +3 -0
- package/package.json +1 -1
|
@@ -133,7 +133,6 @@ 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>;
|
|
138
137
|
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
139
138
|
grantAccess(expectedAccessRevision: number): Promise<void>;
|
|
@@ -352,7 +352,6 @@ 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
|
-
revokeThread(id) { return this.host.submit({ type: "revoke", threadId: this.key(id) }, true); }
|
|
356
355
|
revokeAccess() { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: false }, true); }
|
|
357
356
|
/** Call only after a fresh authoritative Team membership check succeeds. */
|
|
358
357
|
grantAccess(expectedAccessRevision) { return this.host.submit({ type: "teamAccess", teamId: this.teamId, allowed: true, expectedAccessRevision }, true); }
|
|
@@ -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) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision)
|
|
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 && (batch.windowStart ?? current.windowStart) === current.windowStart)
|
|
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, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
102
|
+
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, windowStart: batch.windowStart ?? current.windowStart, 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
|
});
|
|
@@ -107,10 +107,18 @@ export class ProfileDatabase extends Dexie {
|
|
|
107
107
|
/** Restore from one consistent transaction, never mix data across a switch. */
|
|
108
108
|
async restore() {
|
|
109
109
|
return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
|
|
110
|
-
|
|
110
|
+
let current = await this.inboxState.get("current");
|
|
111
111
|
const generation = current?.activeGeneration;
|
|
112
|
-
|
|
113
|
-
|
|
112
|
+
const threads = generation ? await this.threads.where("generation").equals(generation).toArray() : [];
|
|
113
|
+
if (current && current.windowStart === undefined) {
|
|
114
|
+
// Additive migration for early Profile caches. Restoration already reads
|
|
115
|
+
// these records; never replace a committed range with a startup default.
|
|
116
|
+
const build = await this.inboxState.get(`build:${generation}`);
|
|
117
|
+
const inferred = build?.windowStart ?? (threads.length ? threads.reduce((start, row) => Math.max(start, row.coverage.windowStart), threads[0].coverage.windowStart) : undefined);
|
|
118
|
+
if (inferred !== undefined)
|
|
119
|
+
current = { ...current, windowStart: inferred };
|
|
120
|
+
}
|
|
121
|
+
return { current, threads,
|
|
114
122
|
windows: generation ? await this.windows.where("generation").equals(generation).toArray() : [],
|
|
115
123
|
messages: generation ? await this.messages.where("generation").equals(generation).toArray() : [],
|
|
116
124
|
outbox: await this.outbox.toArray(),
|
|
@@ -191,7 +199,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
191
199
|
if (build.status !== "validated")
|
|
192
200
|
throw Error("PROFILE_BUILD_NOT_VALIDATED");
|
|
193
201
|
const next = { ...current, key: "current", activeGeneration: generation, epoch: build.epoch,
|
|
194
|
-
committedSeq: build.committedSeq, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
|
|
202
|
+
committedSeq: build.committedSeq, windowStart: build.windowStart ?? current.windowStart, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
|
|
195
203
|
await this.inboxState.put({ ...build, status: "active" });
|
|
196
204
|
await this.inboxState.put(next);
|
|
197
205
|
return next;
|
|
@@ -49,7 +49,7 @@ export class ProfileGenerationBuilder {
|
|
|
49
49
|
committedSeq: (start - 1n).toString(), projectionVersion: 1, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
|
|
50
50
|
windowStart: bootstrap.windowStart, buildRevision: 0 };
|
|
51
51
|
const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
|
|
52
|
-
epoch: build.epoch, committedSeq: build.committedSeq, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
|
|
52
|
+
epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
|
|
53
53
|
const prepared = projection.prepareBasis(bootstrap), lease = this.lease();
|
|
54
54
|
const next = { ...build, buildRevision: prepared.current.commitRevision };
|
|
55
55
|
await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
|
|
@@ -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 });
|
|
@@ -299,14 +299,16 @@ export class ProfileMemoryStore {
|
|
|
299
299
|
mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
|
|
300
300
|
source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
|
|
301
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;
|
|
302
304
|
const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
|
|
303
305
|
from: message.from, recipients: message.recipients, body: message.content, threadKind: thread?.kind === "dm" ? "dm" : "group", teamId: thread?.teamId });
|
|
304
306
|
const visibleContent = message.recalled ? { kind: "system", text: "" } : content;
|
|
305
307
|
const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
|
|
306
308
|
...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
|
|
307
309
|
status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
|
|
308
|
-
recalled: message.recalled ?? false, unread:
|
|
309
|
-
attentionEligible: message.mention, reading:
|
|
310
|
+
recalled: message.recalled ?? false, unread: readingUnknown ? undefined : !read,
|
|
311
|
+
attentionEligible: message.mention, reading: readingUnknown ? undefined : { seq: message.sourceSeq, read,
|
|
310
312
|
readPolicy: policy === "visible" ? "visible" : "explicit" },
|
|
311
313
|
reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
|
|
312
314
|
this.presented.set(message.messageId, value);
|
|
@@ -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
|
}
|
|
@@ -35,12 +35,12 @@ export class ProfileOwner {
|
|
|
35
35
|
owner.lease = lease;
|
|
36
36
|
try {
|
|
37
37
|
await options.database.initialize(ownerId, lease.fence, { activeGeneration: crypto.randomUUID(), epoch: options.epoch,
|
|
38
|
-
committedSeq: "0", projectionVersion: 1 });
|
|
38
|
+
committedSeq: "0", projectionVersion: 1, windowStart: options.windowStart });
|
|
39
39
|
const restored = await options.database.restore();
|
|
40
40
|
if (!restored.current || restored.current.epoch !== options.epoch)
|
|
41
41
|
throw Error("PROFILE_EPOCH_REBUILD_REQUIRED");
|
|
42
42
|
const snapshot = { ...restored, current: restored.current };
|
|
43
|
-
owner.projection = new ProfileProjection(options.database.identity, snapshot, options.windowStart);
|
|
43
|
+
owner.projection = new ProfileProjection(options.database.identity, snapshot, restored.current.windowStart ?? options.windowStart);
|
|
44
44
|
owner.builder = new ProfileGenerationBuilder(options.database, () => owner.lease);
|
|
45
45
|
owner.memory.restore(snapshot);
|
|
46
46
|
owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
|
|
@@ -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, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
|
|
221
|
+
committedSeq: prepared.current.committedSeq, windowStart: prepared.current.windowStart, 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;
|
|
@@ -30,9 +35,6 @@ export type ProfileLocalOperation = {
|
|
|
30
35
|
targetId: string;
|
|
31
36
|
teamId: string;
|
|
32
37
|
title?: string;
|
|
33
|
-
} | {
|
|
34
|
-
type: "revoke";
|
|
35
|
-
threadId: string;
|
|
36
38
|
} | {
|
|
37
39
|
type: "teamAccess";
|
|
38
40
|
teamId: 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 {
|
|
@@ -135,6 +136,8 @@ class ProfileProjectionDraft {
|
|
|
135
136
|
this.receiptsReady = base.current.receiptsReady;
|
|
136
137
|
}
|
|
137
138
|
localAccessError(operation) {
|
|
139
|
+
if (!supportedLocalOperations.has(operation.type))
|
|
140
|
+
return Error("PROFILE_OPERATION_UNSUPPORTED");
|
|
138
141
|
if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
|
|
139
142
|
return Error("PROFILE_ACCESS_CHECK_STALE");
|
|
140
143
|
if (operation.type !== "send" && operation.type !== "observe")
|
|
@@ -219,27 +222,49 @@ class ProfileProjectionDraft {
|
|
|
219
222
|
return this.thread(message.discussionThreadId)?.readingStatus === "read";
|
|
220
223
|
if (message.from === this.base.identity.profileId)
|
|
221
224
|
return true;
|
|
222
|
-
if (!message.sourceSeq)
|
|
223
|
-
return false;
|
|
224
225
|
if (message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId))
|
|
225
226
|
return true;
|
|
226
227
|
const source = thread && this.source(thread, message.sourceThreadId);
|
|
227
228
|
if (source?.preservedReadMessageIds.includes(message.messageId) || source?.explicitReadMessageIds.includes(message.messageId) || source?.pendingExplicitReadMessageIds?.includes(message.messageId))
|
|
228
229
|
return true;
|
|
229
|
-
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;
|
|
230
234
|
}
|
|
231
235
|
contribution(message, thread) {
|
|
232
|
-
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 };
|
|
233
237
|
}
|
|
234
|
-
updateSummary(id, unreadDelta, mentionDelta) {
|
|
235
|
-
if (!unreadDelta && !mentionDelta)
|
|
238
|
+
updateSummary(id, unreadDelta, mentionDelta, unknownDelta = 0) {
|
|
239
|
+
if (!unreadDelta && !mentionDelta && !unknownDelta)
|
|
236
240
|
return;
|
|
237
241
|
const thread = this.thread(id);
|
|
238
|
-
const
|
|
239
|
-
|
|
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 },
|
|
240
265
|
firstUnreadMessageId: this.firstUnread(id), readingStatus: unreadCount === null ? "unknown" : unreadCount > 0 ? "unread" : "read" });
|
|
241
266
|
if (thread.parentThreadId)
|
|
242
|
-
this.updateSummary(thread.parentThreadId, unreadDelta, mentionDelta);
|
|
267
|
+
this.updateSummary(thread.parentThreadId, unreadDelta, mentionDelta, unknownDelta);
|
|
243
268
|
}
|
|
244
269
|
setMessage(next) {
|
|
245
270
|
const previous = this.message(next.messageId);
|
|
@@ -249,11 +274,11 @@ class ProfileProjectionDraft {
|
|
|
249
274
|
this.readingIndex(next.threadId).upsert(next, this.base.identity.profileId, this.source(this.thread(next.threadId), next.sourceThreadId));
|
|
250
275
|
this.messages.set(next.messageId, { ...next, revision: this.revision });
|
|
251
276
|
if (previous?.threadId === next.threadId)
|
|
252
|
-
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));
|
|
253
278
|
else {
|
|
254
279
|
if (previous)
|
|
255
|
-
this.updateSummary(previous.threadId, -before.unread, -before.mentions);
|
|
256
|
-
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));
|
|
257
282
|
}
|
|
258
283
|
}
|
|
259
284
|
insert(message, historical = false) {
|
|
@@ -321,7 +346,7 @@ class ProfileProjectionDraft {
|
|
|
321
346
|
this.assign(event);
|
|
322
347
|
break;
|
|
323
348
|
case "relationshipUpdated":
|
|
324
|
-
this.relationship(event);
|
|
349
|
+
this.relationship(event, basis);
|
|
325
350
|
break;
|
|
326
351
|
default: throw Error(`UNSUPPORTED_INBOX_EVENT:${event.kind}`);
|
|
327
352
|
}
|
|
@@ -329,6 +354,16 @@ class ProfileProjectionDraft {
|
|
|
329
354
|
this.seq = seq;
|
|
330
355
|
}
|
|
331
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
|
+
}
|
|
332
367
|
if (operation.type === "teamAccess") {
|
|
333
368
|
if (!operation.teamId)
|
|
334
369
|
throw Error("INVALID_PROFILE_TEAM");
|
|
@@ -383,12 +418,6 @@ class ProfileProjectionDraft {
|
|
|
383
418
|
this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
|
|
384
419
|
return;
|
|
385
420
|
}
|
|
386
|
-
if (operation.type === "revoke") {
|
|
387
|
-
const thread = this.thread(operation.threadId);
|
|
388
|
-
if (thread && thread.status !== "unavailable")
|
|
389
|
-
this.putThread({ ...thread, status: "unavailable", readingStatus: "unknown", unreadCount: null, mentionCount: null });
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
421
|
if (operation.type === "restoreReceipt") {
|
|
393
422
|
this.reading({ inboxSeq: "0", sourceId: "receipt-baseline", acceptedAt: 0, kind: "readingUpdated", fact: { ...operation.data, receiptOnly: true } });
|
|
394
423
|
return;
|
|
@@ -486,6 +515,12 @@ class ProfileProjectionDraft {
|
|
|
486
515
|
continue;
|
|
487
516
|
if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
|
|
488
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
|
+
}
|
|
489
524
|
const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
|
|
490
525
|
if (operation.policy === "played" || !message.sourceSeq)
|
|
491
526
|
group.explicitReadMessageIds.push(id);
|
|
@@ -700,8 +735,12 @@ class ProfileProjectionDraft {
|
|
|
700
735
|
index.remove(message);
|
|
701
736
|
}
|
|
702
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);
|
|
703
742
|
this.putThread(next);
|
|
704
|
-
this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions);
|
|
743
|
+
this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions, unknownDelta);
|
|
705
744
|
}
|
|
706
745
|
organize(event) {
|
|
707
746
|
const data = event.fact;
|
|
@@ -741,12 +780,41 @@ class ProfileProjectionDraft {
|
|
|
741
780
|
this.move(this.message(ref.messageId), destination.threadId);
|
|
742
781
|
this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...source.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
|
|
743
782
|
}
|
|
744
|
-
relationship(event) {
|
|
783
|
+
relationship(event, basis = false) {
|
|
745
784
|
const data = event.fact;
|
|
746
785
|
if (!data.pairId || ![data.actorId, data.targetId].includes(this.base.identity.profileId))
|
|
747
786
|
throw Error("INVALID_INBOX_RELATIONSHIP");
|
|
748
|
-
if (data.threadId)
|
|
749
|
-
|
|
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);
|
|
750
818
|
}
|
|
751
819
|
finish() {
|
|
752
820
|
return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
|
|
@@ -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 = {
|
|
@@ -114,6 +115,7 @@ export type ProfileCurrentState = {
|
|
|
114
115
|
key: "current";
|
|
115
116
|
epoch: string;
|
|
116
117
|
committedSeq: string;
|
|
118
|
+
windowStart?: number;
|
|
117
119
|
activeGeneration: string;
|
|
118
120
|
projectionVersion: number;
|
|
119
121
|
commitRevision: number;
|
|
@@ -160,6 +162,7 @@ export type ProfileWriteBatch = {
|
|
|
160
162
|
generation: string;
|
|
161
163
|
epoch: string;
|
|
162
164
|
committedSeq: string;
|
|
165
|
+
windowStart?: number;
|
|
163
166
|
receiptsReady?: boolean;
|
|
164
167
|
localMigrations?: string[];
|
|
165
168
|
revokedTeamIds?: string[];
|
package/package.json
CHANGED