@pmate/chat-sdk 0.13.0-profile.9 → 0.14.0-seq.1
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/README.md +41 -0
- package/lib/runtime/profileChat.d.ts +7 -0
- package/lib/runtime/profileChat.js +105 -20
- package/lib/runtime/profileCoordinator.d.ts +6 -0
- package/lib/runtime/profileCoordinator.js +23 -0
- package/lib/runtime/profileDatabase.js +2 -1
- package/lib/runtime/profileGenerationBuilder.js +17 -13
- package/lib/runtime/profileInboxFeed.js +3 -2
- package/lib/runtime/profileLegacyInbox.js +2 -1
- package/lib/runtime/profileMemoryStore.d.ts +8 -2
- package/lib/runtime/profileMemoryStore.js +49 -9
- package/lib/runtime/profileOutboxDispatcher.js +5 -2
- package/lib/runtime/profileOwner.d.ts +2 -0
- package/lib/runtime/profileOwner.js +9 -5
- package/lib/runtime/profileProjection.d.ts +19 -1
- package/lib/runtime/profileProjection.js +139 -18
- package/lib/runtime/profileStoreTypes.d.ts +3 -1
- package/lib/runtime/profileWindows.d.ts +2 -0
- package/lib/runtime/profileWindows.js +13 -3
- package/lib/runtime/profileWorkerClient.js +1 -0
- package/lib/runtime/profileWorkerHost.js +1 -1
- package/lib/runtime/readSync.d.ts +1 -1
- package/lib/runtime/readSync.js +11 -7
- package/lib/runtime/sourceCursor.d.ts +6 -0
- package/lib/runtime/sourceCursor.js +7 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -389,3 +389,44 @@ The per-Profile database upgrades to schema 2 by deleting only the obsolete `lea
|
|
|
389
389
|
On a Worker error or command timeout, the coordinator terminates the old Worker before replacement. The replacement restores committed data into the same UI memory store. An interrupted command is replayed with its original IDs; a message committed before a lost reply remains one message. Waiting for remote delivery does not itself time out or repeatedly restart an offline Worker. Completed generation switches publish one prepared snapshot; routine updates send only their delta.
|
|
390
390
|
|
|
391
391
|
Tests cover v1 upgrade preservation, atomic writes, idle zero transactions, one Worker on concurrent startup, serial restart, crash after commit/before reply, immediate startup cancellation, generation switching, and memory-only reads/subscriptions. Native frame rate, real-account upgrade and server synchronization still require application acceptance.
|
|
392
|
+
|
|
393
|
+
### Projection v2 repair (0.13.0-profile.10)
|
|
394
|
+
|
|
395
|
+
An existing v1 projection remains committed while a new generation rebuilds from the retained Inbox range. It is marked `restoring`, so the application cannot treat an incomplete or obsolete projection as an empty ready conversation. The rebuild resumes its saved progress after interruption, validates complete message/window references and atomically switches the active generation. Incompatible unfinished generations are eligible for bounded cleanup; the active generation and current-version builds remain protected.
|
|
396
|
+
|
|
397
|
+
Thread assignment carries group controls and metadata, child discussions, reading sources, pending controls/receipts and local reading intents into the destination Team. Later source events still resolve into that canonical Thread. Organization retains its assigned agent; reply counts remain independent of agent ownership. Confirmed and pending reading sources and per-message played/preserved facts survive generation reconciliation, as do durable pending sends.
|
|
398
|
+
|
|
399
|
+
The upgrade regression starts with an obsolete cached projection containing inaccessible discussion children, a locally played voice and a failed outgoing message. It interrupts the rebuild with HTTP 503, reopens the owner, resumes the same generation and verifies group/discussion metadata, reading and the exact durable outgoing message without clearing any store. Full SDK suite: 766 passed, one production-only test skipped.
|
|
400
|
+
|
|
401
|
+
Duplicate Inbox events, registrations and already-read observations are rejected as no-op batches before opening an IndexedDB write transaction; queue and store tests verify zero transactions as well as unchanged revisions.
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
### Profile disposal (0.13.0-profile.11)
|
|
405
|
+
|
|
406
|
+
Final `ProfileCoordinator.close()` releases its UI memory entities, page caches,
|
|
407
|
+
reading indexes and subscriptions after pending startup/recovery settles. It also
|
|
408
|
+
terminates the Worker. Previously, retaining a closed coordinator retained its
|
|
409
|
+
full UI projection. Already published message/page objects remain unchanged.
|
|
410
|
+
Worker recovery keeps the same prepared UI store until its replacement snapshot
|
|
411
|
+
is validated; it must not call the final disposal path. Direct memory-store users
|
|
412
|
+
may call `dispose()` when permanently discarding that Profile. This release does
|
|
413
|
+
not claim that process RSS immediately falls or resolve all recovery peak memory.
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
### Sparse Window paging (0.13.0-profile.12)
|
|
417
|
+
|
|
418
|
+
Organizing messages may leave many empty sealed Windows. Their identities and
|
|
419
|
+
historical routing boundaries remain durable, while the in-memory page directory
|
|
420
|
+
now indexes only nonempty blocks. Reading a small page no longer walks intervening
|
|
421
|
+
empty block contents. A 10,002-Window regression with only two populated blocks
|
|
422
|
+
checks older/newer anchors, retained block identities and forked directories.
|
|
423
|
+
No storage schema or Window merge behavior changes.
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
### Empty Window display directory (0.13.0-profile.13)
|
|
427
|
+
|
|
428
|
+
Prepared `getWindowIds()` now returns only nonempty display blocks. Durable empty
|
|
429
|
+
sealed Windows still retain their identities and remain directly readable for
|
|
430
|
+
historical routing; they no longer consume load-older steps. Empty/refilled
|
|
431
|
+
transitions notify Window-list subscribers. Message-only changes retain the same
|
|
432
|
+
published ID array, and previously published arrays stay unchanged.
|
|
@@ -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
|
|
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.
|
|
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 = {}) {
|
|
319
|
-
|
|
320
|
-
|
|
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
|
-
|
|
323
|
-
const
|
|
324
|
-
if (
|
|
325
|
-
|
|
326
|
-
return
|
|
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,9 +180,12 @@ 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(() => { });
|
|
166
188
|
await this.restarting?.catch(() => { });
|
|
189
|
+
this.memory.dispose();
|
|
167
190
|
}
|
|
168
191
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
1
2
|
import Dexie, {} from "dexie";
|
|
2
3
|
import { inboxSequence } from "./inboxStore.js";
|
|
3
4
|
export function profileDatabaseName(identity) {
|
|
@@ -128,7 +129,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
128
129
|
if (!current)
|
|
129
130
|
return 0;
|
|
130
131
|
const builds = (await this.inboxState.toArray()).filter((row) => row.key.startsWith("build:"));
|
|
131
|
-
const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.status === "building" || row.status === "validated").map(row => row.generation)]);
|
|
132
|
+
const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.projectionVersion === PROFILE_PROJECTION_VERSION && (row.status === "building" || row.status === "validated")).map(row => row.generation)]);
|
|
132
133
|
let removed = 0;
|
|
133
134
|
for (const table of [this.messages, this.windows, this.threads]) {
|
|
134
135
|
if (removed === limit)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProfileDatabase } from "./profileDatabase.js";
|
|
2
|
-
import { ProfileProjection } from "./profileProjection.js";
|
|
3
|
-
import { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
2
|
+
import { profileDiscussionId, ProfileProjection } from "./profileProjection.js";
|
|
3
|
+
import { ProfileMemoryStore, PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
4
4
|
import { inboxSequence } from "./inboxStore.js";
|
|
5
5
|
/** Called only by the owner's serial commit queue. Network catch-up happens
|
|
6
6
|
* outside this class; each staged page is one bounded local transaction. */
|
|
@@ -38,15 +38,17 @@ export class ProfileGenerationBuilder {
|
|
|
38
38
|
throw Error("INVALID_INBOX_BOOTSTRAP");
|
|
39
39
|
const saved = await this.database.restoreGeneration(generation);
|
|
40
40
|
if (saved.build) {
|
|
41
|
+
if (saved.build.projectionVersion !== PROFILE_PROJECTION_VERSION)
|
|
42
|
+
throw Error("PROFILE_BUILD_INCOMPATIBLE");
|
|
41
43
|
if (saved.build.epoch !== bootstrap.epoch || saved.build.throughSeq !== bootstrap.headSeq || saved.build.windowStart !== bootstrap.windowStart)
|
|
42
44
|
throw Error("PROFILE_BUILD_ID_COLLISION");
|
|
43
45
|
return;
|
|
44
46
|
}
|
|
45
47
|
const build = { key: `build:${generation}`, generation, epoch: bootstrap.epoch,
|
|
46
|
-
committedSeq: (start - 1n).toString(), projectionVersion:
|
|
48
|
+
committedSeq: (start - 1n).toString(), projectionVersion: PROFILE_PROJECTION_VERSION, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
|
|
47
49
|
windowStart: bootstrap.windowStart, buildRevision: 0 };
|
|
48
50
|
const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
|
|
49
|
-
epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion:
|
|
51
|
+
epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: PROFILE_PROJECTION_VERSION, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
|
|
50
52
|
const prepared = projection.prepareBasis(bootstrap);
|
|
51
53
|
const next = { ...build, buildRevision: prepared.current.commitRevision };
|
|
52
54
|
await this.database.saveGeneration(next, prepared);
|
|
@@ -99,15 +101,17 @@ export class ProfileGenerationBuilder {
|
|
|
99
101
|
for (const intent of intents)
|
|
100
102
|
operations.push({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent, defer: true });
|
|
101
103
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
operations.push({ type: "
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
104
|
+
const parentId = thread.parentThreadId ?? thread.threadId;
|
|
105
|
+
const parent = projection.threads.get(parentId);
|
|
106
|
+
const canonical = parent?.internal?.assignments?.[parentId] ?? parentId;
|
|
107
|
+
const destination = thread.rootMessageId ? profileDiscussionId(canonical, thread.rootMessageId) : canonical;
|
|
108
|
+
if (projection.threads.has(destination) && thread.readingSources.length)
|
|
109
|
+
operations.push({ type: "restoreReadingSources", threadId: destination, sources: thread.readingSources });
|
|
110
|
+
}
|
|
111
|
+
for (const message of active.messages.values()) {
|
|
112
|
+
const facts = message.explicitReadingFacts.filter(fact => fact.profileId === this.database.identity.profileId);
|
|
113
|
+
if (facts.length && projection.messages.has(message.messageId))
|
|
114
|
+
operations.push({ type: "restoreMessageReadingFacts", messageId: message.messageId, facts });
|
|
111
115
|
}
|
|
112
116
|
for (const command of active.outbox.values())
|
|
113
117
|
if (command.kind !== "message")
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
1
2
|
import { inboxSequence } from "./inboxStore.js";
|
|
2
3
|
/** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
|
|
3
4
|
* backpressured by durable owner commits; long requests never hold its queue. */
|
|
@@ -114,7 +115,7 @@ export class ProfileInboxFeed {
|
|
|
114
115
|
}
|
|
115
116
|
async rebuild() {
|
|
116
117
|
const bootstrap = await this.request("bootstrap");
|
|
117
|
-
const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch);
|
|
118
|
+
const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch && build.projectionVersion === PROFILE_PROJECTION_VERSION);
|
|
118
119
|
const generation = pending?.generation ?? await this.options.owner.beginGeneration(bootstrap);
|
|
119
120
|
const build = await this.options.owner.generationProgress(generation);
|
|
120
121
|
this.building = { generation, epoch: build.epoch, target: build.throughSeq ?? bootstrap.headSeq };
|
|
@@ -146,7 +147,7 @@ export class ProfileInboxFeed {
|
|
|
146
147
|
await this.options.prepare?.();
|
|
147
148
|
if (this.building)
|
|
148
149
|
await this.resumeBuild();
|
|
149
|
-
if (this.options.owner.current.epoch === "uninitialized")
|
|
150
|
+
if (this.options.owner.current.epoch === "uninitialized" || this.options.owner.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
|
|
150
151
|
await this.rebuild();
|
|
151
152
|
let current = this.options.owner.current;
|
|
152
153
|
let page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
1
2
|
import { inboxSequence } from "./inboxStore.js";
|
|
2
3
|
export async function openLegacyDatabase(factory, name) {
|
|
3
4
|
return new Promise((resolve, reject) => {
|
|
@@ -50,7 +51,7 @@ export async function migrateLegacyInbox(owner, options = {}) {
|
|
|
50
51
|
if (!cursor?.initialized || !cursor.epoch)
|
|
51
52
|
return false;
|
|
52
53
|
const seq = inboxSequence(cursor.seq);
|
|
53
|
-
const generation = `legacy-inbox:${JSON.stringify([cursor.epoch, cursor.seq])}`;
|
|
54
|
+
const generation = `legacy-inbox:v${PROFILE_PROJECTION_VERSION}:${JSON.stringify([cursor.epoch, cursor.seq])}`;
|
|
54
55
|
await owner.beginGeneration({ ...identity, epoch: cursor.epoch, startSeq: (seq + 1n).toString(), headSeq: cursor.seq,
|
|
55
56
|
windowStart: cursor.windowStart, basis: [] }, generation);
|
|
56
57
|
if ((await owner.generationProgress(generation)).status === "validated") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ProfileCurrentState, ProfileMessage, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
2
2
|
import type { ChatMessage } from "../chatTypes.js";
|
|
3
3
|
export declare const PROFILE_PROTOCOL_VERSION = 2;
|
|
4
|
-
export declare const PROFILE_PROJECTION_VERSION =
|
|
4
|
+
export declare const PROFILE_PROJECTION_VERSION = 2;
|
|
5
5
|
export type ProfileSnapshot = {
|
|
6
6
|
current: ProfileCurrentState;
|
|
7
7
|
threads: ProfileThread[];
|
|
@@ -24,6 +24,7 @@ export type ProfileDelta = {
|
|
|
24
24
|
export declare class ProfileMemoryStore {
|
|
25
25
|
private onError;
|
|
26
26
|
private profileId;
|
|
27
|
+
private preparePresentation;
|
|
27
28
|
private windowRows;
|
|
28
29
|
private messageWindows;
|
|
29
30
|
private windowPages;
|
|
@@ -32,6 +33,7 @@ export declare class ProfileMemoryStore {
|
|
|
32
33
|
private windowListeners;
|
|
33
34
|
private windowListListeners;
|
|
34
35
|
private dirtyWindows;
|
|
36
|
+
private dirtyWindowLists;
|
|
35
37
|
private readonly emptyWindowIds;
|
|
36
38
|
private current?;
|
|
37
39
|
private entities;
|
|
@@ -47,7 +49,11 @@ export declare class ProfileMemoryStore {
|
|
|
47
49
|
private presented;
|
|
48
50
|
private readingIndices;
|
|
49
51
|
private presentedPages;
|
|
50
|
-
constructor(onError?: (error: unknown) => void, profileId?: string);
|
|
52
|
+
constructor(onError?: (error: unknown) => void, profileId?: string, preparePresentation?: boolean);
|
|
53
|
+
/** Release a disposed Profile without mutating snapshots held by React.
|
|
54
|
+
* Worker replacement deliberately keeps this store alive; only final close
|
|
55
|
+
* may discard its entities and subscriptions. */
|
|
56
|
+
dispose(): void;
|
|
51
57
|
private notify;
|
|
52
58
|
getStatus(): {
|
|
53
59
|
phase: "ready" | "restoring";
|
|
@@ -2,12 +2,13 @@ import { ProfileWindowDirectory } from "./profileWindows.js";
|
|
|
2
2
|
import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
3
3
|
import { projectMessageContent } from "../messageView.js";
|
|
4
4
|
export const PROFILE_PROTOCOL_VERSION = 2;
|
|
5
|
-
export const PROFILE_PROJECTION_VERSION =
|
|
5
|
+
export const PROFILE_PROJECTION_VERSION = 2;
|
|
6
6
|
/** Storage-free consumer shared by the owner, page adapters and WebView replicas.
|
|
7
7
|
* Only committed snapshots/deltas enter here; reads cannot initiate I/O. */
|
|
8
8
|
export class ProfileMemoryStore {
|
|
9
9
|
onError;
|
|
10
10
|
profileId;
|
|
11
|
+
preparePresentation;
|
|
11
12
|
windowRows = new Map();
|
|
12
13
|
messageWindows = new Map();
|
|
13
14
|
windowPages = new Map();
|
|
@@ -16,6 +17,7 @@ export class ProfileMemoryStore {
|
|
|
16
17
|
windowListeners = new Map();
|
|
17
18
|
windowListListeners = new Map();
|
|
18
19
|
dirtyWindows = new Set();
|
|
20
|
+
dirtyWindowLists = new Set();
|
|
19
21
|
emptyWindowIds = [];
|
|
20
22
|
current;
|
|
21
23
|
entities = new Map();
|
|
@@ -31,9 +33,38 @@ export class ProfileMemoryStore {
|
|
|
31
33
|
presented = new Map();
|
|
32
34
|
readingIndices = new Map();
|
|
33
35
|
presentedPages = new WeakMap();
|
|
34
|
-
constructor(onError = () => { }, profileId = "") {
|
|
36
|
+
constructor(onError = () => { }, profileId = "", preparePresentation = true) {
|
|
35
37
|
this.onError = onError;
|
|
36
38
|
this.profileId = profileId;
|
|
39
|
+
this.preparePresentation = preparePresentation;
|
|
40
|
+
}
|
|
41
|
+
/** Release a disposed Profile without mutating snapshots held by React.
|
|
42
|
+
* Worker replacement deliberately keeps this store alive; only final close
|
|
43
|
+
* may discard its entities and subscriptions. */
|
|
44
|
+
dispose() {
|
|
45
|
+
this.windowRows.clear();
|
|
46
|
+
this.messageWindows.clear();
|
|
47
|
+
this.windowPages.clear();
|
|
48
|
+
this.windowAccess.clear();
|
|
49
|
+
this.windowIds.clear();
|
|
50
|
+
this.windowListeners.clear();
|
|
51
|
+
this.windowListListeners.clear();
|
|
52
|
+
this.dirtyWindows.clear();
|
|
53
|
+
this.dirtyWindowLists.clear();
|
|
54
|
+
this.entities.clear();
|
|
55
|
+
this.threads.clear();
|
|
56
|
+
this.directories.clear();
|
|
57
|
+
this.listeners.clear();
|
|
58
|
+
this.listListeners.clear();
|
|
59
|
+
this.messageListeners.clear();
|
|
60
|
+
this.pageCache.clear();
|
|
61
|
+
this.epochs.clear();
|
|
62
|
+
this.presented.clear();
|
|
63
|
+
this.readingIndices.clear();
|
|
64
|
+
this.presentedPages = new WeakMap();
|
|
65
|
+
this.list = [];
|
|
66
|
+
this.current = undefined;
|
|
67
|
+
this.phase = "restoring";
|
|
37
68
|
}
|
|
38
69
|
notify(listener) { try {
|
|
39
70
|
listener();
|
|
@@ -73,6 +104,9 @@ export class ProfileMemoryStore {
|
|
|
73
104
|
windowKey(threadId, windowId) { return JSON.stringify([threadId, windowId]); }
|
|
74
105
|
installWindow(window) {
|
|
75
106
|
const key = this.windowKey(window.threadId, window.windowId);
|
|
107
|
+
const previous = this.windowRows.get(key);
|
|
108
|
+
if (!previous || (previous.count === 0) !== (window.count === 0))
|
|
109
|
+
this.dirtyWindowLists.add(window.threadId);
|
|
76
110
|
for (const ref of this.windowRows.get(key)?.refs ?? [])
|
|
77
111
|
if (this.messageWindows.get(ref.messageId) === key)
|
|
78
112
|
this.messageWindows.delete(ref.messageId);
|
|
@@ -131,7 +165,7 @@ export class ProfileMemoryStore {
|
|
|
131
165
|
}
|
|
132
166
|
restore(snapshot) {
|
|
133
167
|
const generation = snapshot.current.activeGeneration;
|
|
134
|
-
if (snapshot.current.projectionVersion
|
|
168
|
+
if (![1, PROFILE_PROJECTION_VERSION].includes(snapshot.current.projectionVersion))
|
|
135
169
|
throw Error("PROFILE_PROJECTION_INCOMPATIBLE");
|
|
136
170
|
for (const row of [...snapshot.threads, ...snapshot.windows, ...snapshot.messages])
|
|
137
171
|
if (row.generation !== generation)
|
|
@@ -174,7 +208,7 @@ export class ProfileMemoryStore {
|
|
|
174
208
|
this.prepareMessageView(row);
|
|
175
209
|
}
|
|
176
210
|
this.current = snapshot.current;
|
|
177
|
-
this.phase = snapshot.current.epoch === "uninitialized" ? "restoring" : "ready";
|
|
211
|
+
this.phase = snapshot.current.epoch === "uninitialized" || snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION ? "restoring" : "ready";
|
|
178
212
|
this.pageCache.clear();
|
|
179
213
|
this.epochs.clear();
|
|
180
214
|
this.publish(affected, true);
|
|
@@ -291,6 +325,8 @@ export class ProfileMemoryStore {
|
|
|
291
325
|
this.readingIndices.set(message.threadId, index);
|
|
292
326
|
}
|
|
293
327
|
prepareMessageView(message) {
|
|
328
|
+
if (!this.preparePresentation)
|
|
329
|
+
return;
|
|
294
330
|
const thread = this.threads.get(message.threadId);
|
|
295
331
|
const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
|
|
296
332
|
const mine = message.from === this.profileId;
|
|
@@ -323,12 +359,16 @@ export class ProfileMemoryStore {
|
|
|
323
359
|
for (const threadId of affected) {
|
|
324
360
|
const blocks = this.directories.get(threadId)?.blocks ?? [];
|
|
325
361
|
const previous = this.windowIds.get(threadId);
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
if (!previous ||
|
|
329
|
-
|
|
330
|
-
|
|
362
|
+
// Durable empty blocks keep their IDs and routing boundaries, but are
|
|
363
|
+
// omitted from the display directory. Entity-only updates keep its array.
|
|
364
|
+
if (!previous || this.dirtyWindowLists.has(threadId)) {
|
|
365
|
+
const ids = blocks.filter(window => window.count > 0).map(window => window.windowId);
|
|
366
|
+
if (!previous || ids.length !== previous.length || ids.some((id, index) => id !== previous[index])) {
|
|
367
|
+
this.windowIds.set(threadId, ids);
|
|
368
|
+
changedLists.add(threadId);
|
|
369
|
+
}
|
|
331
370
|
}
|
|
371
|
+
this.dirtyWindowLists.delete(threadId);
|
|
332
372
|
const available = this.isThreadAvailable(threadId);
|
|
333
373
|
if (this.windowAccess.get(threadId) !== available) {
|
|
334
374
|
this.windowAccess.set(threadId, available);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sourceCursor } from "./sourceCursor.js";
|
|
1
2
|
import { voiceUploader } from "./voiceUpload.js";
|
|
2
3
|
import { profileDiscussionId } from "./profileProjection.js";
|
|
3
4
|
/** Reads committed commands from owner memory. All status/ACK transitions return
|
|
@@ -121,14 +122,16 @@ export class ProfileOutboxDispatcher {
|
|
|
121
122
|
}
|
|
122
123
|
async reading(command) {
|
|
123
124
|
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/reading`, {
|
|
124
|
-
method: "POST", headers: { authorization: `Bearer ${await this.options.getToken()}`, "content-type": "application/json" },
|
|
125
|
+
method: "POST", headers: { authorization: `Bearer ${await this.options.getToken()}`, "content-type": "application/json", "x-pmate-stream-protocol": "seq-v1" },
|
|
125
126
|
body: JSON.stringify({ ...command.payload, operationId: command.commandId }),
|
|
126
127
|
signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(10000)]), cache: "no-store", redirect: "error",
|
|
127
128
|
});
|
|
128
129
|
if (!response.ok)
|
|
129
130
|
throw Error(`READ_SYNC_HTTP_${response.status}`);
|
|
130
131
|
const result = await response.json();
|
|
131
|
-
if (result.success !== true || result.data?.operationId !== command.commandId || result.data.accepted !== true
|
|
132
|
+
if (result.success !== true || result.data?.operationId !== command.commandId || result.data.accepted !== true)
|
|
133
|
+
throw Error("INVALID_READING_RECEIPT");
|
|
134
|
+
if (sourceCursor(result.data).seq === "0")
|
|
132
135
|
throw Error("INVALID_READING_RECEIPT");
|
|
133
136
|
}
|
|
134
137
|
async close() {
|
|
@@ -11,6 +11,8 @@ export type ProfileOwnerOptions = {
|
|
|
11
11
|
onError?: (error: unknown) => void;
|
|
12
12
|
windowMs?: number;
|
|
13
13
|
readingWindowMs?: number;
|
|
14
|
+
/** Worker authority needs raw committed rows; its UI consumer prepares presentation. */
|
|
15
|
+
preparePresentation?: boolean;
|
|
14
16
|
retryMs?: number;
|
|
15
17
|
};
|
|
16
18
|
/** The durable owner publishes only after commit. Network requests belong to
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProfileCommitQueue } from "./profileCommitQueue.js";
|
|
2
2
|
import { ProfileDatabase } from "./profileDatabase.js";
|
|
3
|
-
import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
|
|
3
|
+
import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
4
4
|
import { ProfileProjection } from "./profileProjection.js";
|
|
5
5
|
import { ProfileGenerationBuilder } from "./profileGenerationBuilder.js";
|
|
6
6
|
/** The durable owner publishes only after commit. Network requests belong to
|
|
@@ -21,13 +21,13 @@ export class ProfileOwner {
|
|
|
21
21
|
credentialUpdater = () => { throw Error("PROFILE_NETWORK_UNAVAILABLE"); };
|
|
22
22
|
constructor(options) {
|
|
23
23
|
this.options = options;
|
|
24
|
-
this.memory = new ProfileMemoryStore(options.onError, options.database.identity.profileId);
|
|
24
|
+
this.memory = new ProfileMemoryStore(options.onError, options.database.identity.profileId, options.preparePresentation);
|
|
25
25
|
}
|
|
26
26
|
static async open(options) {
|
|
27
27
|
const owner = new ProfileOwner(options);
|
|
28
28
|
try {
|
|
29
29
|
await options.database.initialize({ activeGeneration: crypto.randomUUID(), epoch: options.epoch,
|
|
30
|
-
committedSeq: "0", projectionVersion:
|
|
30
|
+
committedSeq: "0", projectionVersion: PROFILE_PROJECTION_VERSION, windowStart: options.windowStart });
|
|
31
31
|
const restored = await options.database.restore();
|
|
32
32
|
if (!restored.current || restored.current.epoch !== options.epoch)
|
|
33
33
|
throw Error("PROFILE_EPOCH_REBUILD_REQUIRED");
|
|
@@ -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();
|
|
@@ -186,6 +184,12 @@ export class ProfileOwner {
|
|
|
186
184
|
}
|
|
187
185
|
const fromRevision = this.projection.current.commitRevision;
|
|
188
186
|
const prepared = this.projection.prepare(events);
|
|
187
|
+
// A replayed cursor or already-observed reading candidate must not even
|
|
188
|
+
// open a readwrite transaction. Only small sync metadata is compared here.
|
|
189
|
+
const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteOutbox].some(rows => rows.length) &&
|
|
190
|
+
JSON.stringify({ ...prepared.current, commitRevision: fromRevision }) === JSON.stringify(this.current);
|
|
191
|
+
if (unchanged)
|
|
192
|
+
return prepared.rejected;
|
|
189
193
|
const committed = await this.options.database.commit({ ...prepared,
|
|
190
194
|
generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
|
|
191
195
|
committedSeq: prepared.current.committedSeq, windowStart: prepared.current.windowStart, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
|
|
@@ -2,10 +2,18 @@ import { type InboxEvent, type InboxMessage, type InboxBootstrap } from "./inbox
|
|
|
2
2
|
import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
3
3
|
import { ProfileWindowDirectory } from "./profileWindows.js";
|
|
4
4
|
import type { ProfileSnapshot } from "./profileMemoryStore.js";
|
|
5
|
-
import type { ProfileCurrentState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
5
|
+
import type { ProfileCurrentState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileReadingSource, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
6
6
|
import type { ChatRuntimeMessage } from "./protocol.js";
|
|
7
7
|
export declare const profileDiscussionId: (parent: string, root: string) => string;
|
|
8
8
|
export type ProfileLocalOperation = {
|
|
9
|
+
type: "restoreReadingSources";
|
|
10
|
+
threadId: string;
|
|
11
|
+
sources: ProfileReadingSource[];
|
|
12
|
+
} | {
|
|
13
|
+
type: "restoreMessageReadingFacts";
|
|
14
|
+
messageId: string;
|
|
15
|
+
facts: ProfileMessage["explicitReadingFacts"];
|
|
16
|
+
} | {
|
|
9
17
|
type: "migrationCompleted";
|
|
10
18
|
id: string;
|
|
11
19
|
} | {
|
|
@@ -35,6 +43,16 @@ export type ProfileLocalOperation = {
|
|
|
35
43
|
targetId: string;
|
|
36
44
|
teamId: string;
|
|
37
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;
|
|
38
56
|
} | {
|
|
39
57
|
type: "teamAccess";
|
|
40
58
|
teamId: string;
|
|
@@ -7,7 +7,13 @@ 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
|
-
|
|
10
|
+
function mergeAssignedLists(source, destination) {
|
|
11
|
+
const merged = { ...source };
|
|
12
|
+
for (const [key, values] of Object.entries(destination ?? {}))
|
|
13
|
+
merged[key] = [...new Map([...(merged[key] ?? []), ...values].map(value => [JSON.stringify(value), value])).values()];
|
|
14
|
+
return merged;
|
|
15
|
+
}
|
|
16
|
+
const supportedLocalOperations = new Set(["restoreReadingSources", "restoreMessageReadingFacts", "migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "groupSnapshot", "groupDenied", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
|
|
11
17
|
/** Committed authority for the replay reducer. Drafts contain only changed rows;
|
|
12
18
|
* failure discards the draft, leaving both entities and indexes untouched. */
|
|
13
19
|
export class ProfileProjection {
|
|
@@ -140,6 +146,10 @@ class ProfileProjectionDraft {
|
|
|
140
146
|
return Error("PROFILE_OPERATION_UNSUPPORTED");
|
|
141
147
|
if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
|
|
142
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");
|
|
143
153
|
if (operation.type !== "send" && operation.type !== "observe")
|
|
144
154
|
return;
|
|
145
155
|
const thread = this.thread(operation.threadId);
|
|
@@ -354,6 +364,18 @@ class ProfileProjectionDraft {
|
|
|
354
364
|
this.seq = seq;
|
|
355
365
|
}
|
|
356
366
|
local(operation) {
|
|
367
|
+
if (operation.type === "restoreReadingSources") {
|
|
368
|
+
if (this.thread(operation.threadId))
|
|
369
|
+
this.mergeAssignedReading(operation.threadId, operation.sources);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (operation.type === "restoreMessageReadingFacts") {
|
|
373
|
+
const message = this.message(operation.messageId);
|
|
374
|
+
if (message)
|
|
375
|
+
this.setMessage({ ...message, explicitReadingFacts: [...new Map([...message.explicitReadingFacts, ...operation.facts.filter(fact => fact.profileId === this.base.identity.profileId)]
|
|
376
|
+
.map(fact => [JSON.stringify(fact), fact])).values()] });
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
357
379
|
if (operation.type === "restoreInvitation") {
|
|
358
380
|
const wire = operation.message, body = wire.body;
|
|
359
381
|
if (wire.appId !== this.base.identity.appId || wire.seq || body?.kind !== "contact" || body.action !== "friendRequest" || ![wire.from, wire.to].includes(this.base.identity.profileId))
|
|
@@ -414,6 +436,30 @@ class ProfileProjectionDraft {
|
|
|
414
436
|
recipients: message.recipients, body: operation.message.body, threadKind: this.thread(message.threadId)?.kind === "dm" ? "dm" : "group" }) });
|
|
415
437
|
return;
|
|
416
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
|
+
}
|
|
417
463
|
if (operation.type === "register") {
|
|
418
464
|
this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
|
|
419
465
|
return;
|
|
@@ -492,7 +538,7 @@ class ProfileProjectionDraft {
|
|
|
492
538
|
}
|
|
493
539
|
if (operation.type === "commandResult") {
|
|
494
540
|
const command = this.outbox.get(operation.commandId) ?? this.base.outbox.get(operation.commandId);
|
|
495
|
-
if (!command)
|
|
541
|
+
if (!command || operation.state === command.state && operation.state !== "sending")
|
|
496
542
|
return;
|
|
497
543
|
if (operation.state === "confirmed")
|
|
498
544
|
this.deleteOutbox.add(command.commandId);
|
|
@@ -516,9 +562,9 @@ class ProfileProjectionDraft {
|
|
|
516
562
|
if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
|
|
517
563
|
continue;
|
|
518
564
|
if (!message.sourceSeq) {
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
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 });
|
|
522
568
|
continue;
|
|
523
569
|
}
|
|
524
570
|
const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
|
|
@@ -563,9 +609,14 @@ class ProfileProjectionDraft {
|
|
|
563
609
|
const parent = canonical ? this.ensure(canonical, wire.threadKind, { teamId: source.teamId }) : source;
|
|
564
610
|
const body = wire.body;
|
|
565
611
|
if (body?.kind === "group") {
|
|
566
|
-
const
|
|
567
|
-
const
|
|
568
|
-
|
|
612
|
+
const control = canonical ? { ...wire, threadId: parent.threadId, teamId: parent.teamId } : wire;
|
|
613
|
+
const controls = { ...parent.internal?.groupControls, [wire.messageId]: control };
|
|
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 },
|
|
569
620
|
...(group ? { group, title: group.title, avatar: group.avatar ?? undefined,
|
|
570
621
|
status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}) });
|
|
571
622
|
return;
|
|
@@ -638,6 +689,14 @@ class ProfileProjectionDraft {
|
|
|
638
689
|
delete intents[operation.messageId];
|
|
639
690
|
this.putThread({ ...source, internal: { ...source.internal, pendingReadingIntents: intents } });
|
|
640
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
|
+
}
|
|
641
700
|
if (!known || message.from === this.base.identity.profileId || message.recalled || message.readPolicy === "discussion" ||
|
|
642
701
|
(operation.policy === "played") !== (message.readPolicy === "explicit"))
|
|
643
702
|
return;
|
|
@@ -746,7 +805,9 @@ class ProfileProjectionDraft {
|
|
|
746
805
|
const data = event.fact;
|
|
747
806
|
if (!data.threadId || !data.rootMessageId || !Array.isArray(data.messageIds) || !Number.isSafeInteger(data.revision))
|
|
748
807
|
throw Error("INVALID_INBOX_ORGANIZATION");
|
|
749
|
-
const
|
|
808
|
+
const source = this.ensure(data.threadId);
|
|
809
|
+
const parent = source.internal?.assignments?.[source.threadId] ? this.ensure(source.internal.assignments[source.threadId]) : source;
|
|
810
|
+
const old = parent.internal?.organizationRevisions?.[data.rootMessageId] ?? -1;
|
|
750
811
|
if (old >= data.revision)
|
|
751
812
|
return;
|
|
752
813
|
const messageRoots = { ...parent.internal?.messageRoots };
|
|
@@ -754,8 +815,9 @@ class ProfileProjectionDraft {
|
|
|
754
815
|
if (messageId !== data.rootMessageId)
|
|
755
816
|
messageRoots[messageId] = data.rootMessageId;
|
|
756
817
|
this.putThread({ ...parent, internal: { ...parent.internal, messageRoots, organizationRevisions: { ...parent.internal?.organizationRevisions, [data.rootMessageId]: data.revision } } });
|
|
757
|
-
const id = profileDiscussionId(
|
|
758
|
-
this.ensure(id, "discussion", { parentThreadId:
|
|
818
|
+
const id = profileDiscussionId(parent.threadId, data.rootMessageId);
|
|
819
|
+
const discussion = this.ensure(id, "discussion", { parentThreadId: parent.threadId, rootMessageId: data.rootMessageId, teamId: parent.teamId });
|
|
820
|
+
this.putThread({ ...discussion, ownerAgentId: typeof data.ownerAgentId === "string" ? data.ownerAgentId : undefined });
|
|
759
821
|
const root = this.message(data.rootMessageId);
|
|
760
822
|
if (root)
|
|
761
823
|
this.setMessage({ ...root, readPolicy: "discussion", discussionThreadId: id });
|
|
@@ -771,14 +833,73 @@ class ProfileProjectionDraft {
|
|
|
771
833
|
const data = event.fact;
|
|
772
834
|
if (!data.sourceThreadId || !data.threadId || !data.teamId)
|
|
773
835
|
throw Error("INVALID_INBOX_ASSIGNMENT");
|
|
774
|
-
|
|
836
|
+
if (data.sourceThreadId === data.threadId)
|
|
837
|
+
return;
|
|
775
838
|
const source = this.ensure(data.sourceThreadId);
|
|
776
|
-
this.
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
839
|
+
const destination = this.ensure(data.threadId, source.kind === "dm" ? "dm" : "group", { teamId: data.teamId });
|
|
840
|
+
const targetId = destination.internal?.targetId ?? source.internal?.targetId;
|
|
841
|
+
const groupControls = Object.fromEntries(Object.entries({ ...source.internal?.groupControls, ...destination.internal?.groupControls })
|
|
842
|
+
.map(([id, value]) => [id, { ...value, threadId: destination.threadId, teamId: data.teamId }]));
|
|
843
|
+
const group = destination.internal?.groupSource === "api" ? destination.group : targetId ? projectInboxGroup(this.base.identity.appId, targetId, data.teamId, Object.values(groupControls)) : undefined;
|
|
844
|
+
const organizationRevisions = { ...source.internal?.organizationRevisions };
|
|
845
|
+
for (const [root, revision] of Object.entries(destination.internal?.organizationRevisions ?? {}))
|
|
846
|
+
organizationRevisions[root] = Math.max(organizationRevisions[root] ?? -1, revision);
|
|
847
|
+
this.putThread({ ...destination, teamId: data.teamId, title: group?.title ?? (destination.title || source.title), avatar: group?.avatar ?? destination.avatar ?? source.avatar,
|
|
848
|
+
group: group ?? destination.group ?? (source.group ? { ...source.group, teamId: data.teamId } : undefined),
|
|
849
|
+
...(group ? { status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}),
|
|
850
|
+
internal: { ...source.internal, ...destination.internal, targetId, groupControls, organizationRevisions,
|
|
851
|
+
messageRoots: { ...source.internal?.messageRoots, ...destination.internal?.messageRoots },
|
|
852
|
+
pendingControls: mergeAssignedLists(source.internal?.pendingControls, destination.internal?.pendingControls),
|
|
853
|
+
pendingReceipts: mergeAssignedLists(source.internal?.pendingReceipts, destination.internal?.pendingReceipts),
|
|
854
|
+
pendingReadingIntents: mergeAssignedLists(source.internal?.pendingReadingIntents, destination.internal?.pendingReadingIntents),
|
|
855
|
+
participantCounts: destination.internal?.participantCounts, unknownReadingCount: destination.internal?.unknownReadingCount } });
|
|
856
|
+
this.mergeAssignedReading(destination.threadId, source.readingSources);
|
|
857
|
+
const children = new Set(this.base.children.get(source.threadId));
|
|
858
|
+
for (const row of this.threads.values())
|
|
859
|
+
if (row.parentThreadId === source.threadId)
|
|
860
|
+
children.add(row.threadId);
|
|
861
|
+
for (const childId of children) {
|
|
862
|
+
const child = this.thread(childId);
|
|
863
|
+
if (!child.rootMessageId)
|
|
864
|
+
continue;
|
|
865
|
+
const id = profileDiscussionId(destination.threadId, child.rootMessageId);
|
|
866
|
+
this.ensure(id, "discussion", { parentThreadId: destination.threadId, rootMessageId: child.rootMessageId, teamId: data.teamId,
|
|
867
|
+
title: child.title, ownerAgentId: child.ownerAgentId });
|
|
868
|
+
this.mergeAssignedReading(id, child.readingSources);
|
|
869
|
+
const root = this.message(child.rootMessageId);
|
|
870
|
+
if (root)
|
|
871
|
+
this.setMessage({ ...root, discussionThreadId: id });
|
|
872
|
+
for (const ref of this.directory(childId).blocks.flatMap(window => window.refs))
|
|
873
|
+
this.move(this.message(ref.messageId), id);
|
|
874
|
+
this.putThread({ ...this.thread(childId), status: "unavailable" });
|
|
875
|
+
}
|
|
876
|
+
for (const ref of this.directory(source.threadId).blocks.flatMap(window => window.refs))
|
|
877
|
+
this.move(this.message(ref.messageId), destination.threadId);
|
|
878
|
+
this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...this.thread(source.threadId)?.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
|
|
879
|
+
}
|
|
880
|
+
mergeAssignedReading(id, incoming) {
|
|
881
|
+
const thread = this.thread(id), sources = new Map(thread.readingSources.map(source => [source.sourceThreadId, source]));
|
|
882
|
+
for (const source of incoming) {
|
|
883
|
+
const previous = sources.get(source.sourceThreadId);
|
|
884
|
+
if (!previous) {
|
|
885
|
+
sources.set(source.sourceThreadId, source);
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
sources.set(source.sourceThreadId, { ...previous, readThroughSeq: Math.max(previous.readThroughSeq, source.readThroughSeq),
|
|
889
|
+
pendingReadThroughSeq: Math.max(previous.pendingReadThroughSeq ?? 0, source.pendingReadThroughSeq ?? 0),
|
|
890
|
+
explicitReadMessageIds: [...new Set([...previous.explicitReadMessageIds, ...source.explicitReadMessageIds])],
|
|
891
|
+
pendingExplicitReadMessageIds: [...new Set([...(previous.pendingExplicitReadMessageIds ?? []), ...(source.pendingExplicitReadMessageIds ?? [])])],
|
|
892
|
+
preservedReadMessageIds: [...new Set([...previous.preservedReadMessageIds, ...source.preservedReadMessageIds])] });
|
|
893
|
+
}
|
|
894
|
+
const index = this.readingIndex(id), before = index.summary(thread.readingSources), next = { ...thread, readingSources: [...sources.values()] };
|
|
895
|
+
this.putThread(next);
|
|
896
|
+
for (const window of this.directory(id).blocks)
|
|
897
|
+
for (const ref of window.refs) {
|
|
898
|
+
const message = this.message(ref.messageId);
|
|
899
|
+
index.upsert(message, this.base.identity.profileId, sources.get(message.sourceThreadId));
|
|
900
|
+
}
|
|
901
|
+
const after = index.summary(next.readingSources);
|
|
902
|
+
this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions);
|
|
782
903
|
}
|
|
783
904
|
relationship(event, basis = false) {
|
|
784
905
|
const data = event.fact;
|
|
@@ -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>;
|
|
@@ -15,6 +15,8 @@ export declare class ProfileWindowDirectory {
|
|
|
15
15
|
private baseLookup?;
|
|
16
16
|
private removed;
|
|
17
17
|
private offsets;
|
|
18
|
+
private pageWindows;
|
|
19
|
+
private pageOffsets;
|
|
18
20
|
private size;
|
|
19
21
|
constructor(generation: string, threadId: string, windows?: readonly ProfileWindow[]);
|
|
20
22
|
get count(): number;
|
|
@@ -28,6 +28,8 @@ export class ProfileWindowDirectory {
|
|
|
28
28
|
baseLookup;
|
|
29
29
|
removed = new Set();
|
|
30
30
|
offsets = [];
|
|
31
|
+
pageWindows = [];
|
|
32
|
+
pageOffsets = [];
|
|
31
33
|
size = 0;
|
|
32
34
|
constructor(generation, threadId, windows = []) {
|
|
33
35
|
this.generation = generation;
|
|
@@ -138,8 +140,14 @@ export class ProfileWindowDirectory {
|
|
|
138
140
|
reindex() {
|
|
139
141
|
this.size = 0;
|
|
140
142
|
this.offsets = [];
|
|
143
|
+
this.pageWindows = [];
|
|
144
|
+
this.pageOffsets = [];
|
|
141
145
|
for (const window of this.windows) {
|
|
142
146
|
this.offsets.push(this.size);
|
|
147
|
+
if (window.refs.length) {
|
|
148
|
+
this.pageWindows.push(window);
|
|
149
|
+
this.pageOffsets.push(this.size);
|
|
150
|
+
}
|
|
143
151
|
this.size += window.refs.length;
|
|
144
152
|
}
|
|
145
153
|
}
|
|
@@ -163,10 +171,12 @@ export class ProfileWindowDirectory {
|
|
|
163
171
|
const end = direction === "older" ? position : Math.min(this.size, start + limit);
|
|
164
172
|
if (start >= end)
|
|
165
173
|
return [];
|
|
166
|
-
|
|
174
|
+
// Empty sealed blocks keep historical routing boundaries, but must not
|
|
175
|
+
// turn a small page into a scan across all previously organized windows.
|
|
176
|
+
let block = Math.max(0, lowerBound(this.pageOffsets, offset => offset - (start + 1)) - 1);
|
|
167
177
|
const result = [];
|
|
168
|
-
while (block < this.
|
|
169
|
-
const offset = this.
|
|
178
|
+
while (block < this.pageWindows.length && this.pageOffsets[block] < end) {
|
|
179
|
+
const offset = this.pageOffsets[block], refs = this.pageWindows[block].refs;
|
|
170
180
|
result.push(...refs.slice(Math.max(0, start - offset), Math.min(refs.length, end - offset)));
|
|
171
181
|
block++;
|
|
172
182
|
}
|
|
@@ -64,7 +64,7 @@ export function installProfileWorker(port, options = {}) {
|
|
|
64
64
|
throw Error("PROFILE_LOCKS_UNAVAILABLE");
|
|
65
65
|
database = options.database?.(config.identity) ?? new ProfileDatabase(config.identity);
|
|
66
66
|
const stored = await database.inboxState.get("current");
|
|
67
|
-
owner = await ProfileOwner.open({ database, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
|
|
67
|
+
owner = await ProfileOwner.open({ database, preparePresentation: false, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
|
|
68
68
|
onError: error => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_OWNER_FAILED" }) });
|
|
69
69
|
disposers.push(serveProfileWorker(owner, port, nextScope));
|
|
70
70
|
if (network) {
|
package/lib/runtime/readSync.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { sourceCursor } from "./sourceCursor.js";
|
|
1
2
|
import { readingMetadata, resolveObservedReads, assertReadIndexVersions, applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
|
|
2
3
|
/** Keeps local operations until an authoritative projection covers them. */
|
|
3
4
|
export class ReadSyncClient {
|
|
4
5
|
options;
|
|
5
6
|
controller = new AbortController();
|
|
6
7
|
inFlight;
|
|
7
|
-
readAfter
|
|
8
|
+
readAfter;
|
|
8
9
|
inboxApplying;
|
|
9
10
|
inboxDirty = false;
|
|
10
11
|
constructor(options) {
|
|
@@ -151,7 +152,7 @@ export class ReadSyncClient {
|
|
|
151
152
|
let receipt;
|
|
152
153
|
try {
|
|
153
154
|
receipt = await this.request("/api/social/reading", {
|
|
154
|
-
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
|
|
155
|
+
method: "POST", headers: { "content-type": "application/json", "x-pmate-stream-protocol": "seq-v1" }, body: JSON.stringify({ ...operation, appId, profileId }),
|
|
155
156
|
});
|
|
156
157
|
}
|
|
157
158
|
catch (error) {
|
|
@@ -161,10 +162,13 @@ export class ReadSyncClient {
|
|
|
161
162
|
return this.run(true);
|
|
162
163
|
throw error;
|
|
163
164
|
}
|
|
164
|
-
if (receipt.operationId !== operation.operationId || receipt.accepted !== true
|
|
165
|
-
|| !Number.isSafeInteger(receipt.acceptedAt) || receipt.acceptedAt <= 0)
|
|
165
|
+
if (receipt.operationId !== operation.operationId || receipt.accepted !== true)
|
|
166
166
|
throw new Error("INVALID_READING_RECEIPT");
|
|
167
|
-
|
|
167
|
+
const cursor = sourceCursor(receipt);
|
|
168
|
+
if (cursor.seq === "0" || this.readAfter && this.readAfter.streamId !== cursor.streamId)
|
|
169
|
+
throw new Error("INVALID_READING_RECEIPT");
|
|
170
|
+
if (!this.readAfter || BigInt(cursor.seq) > BigInt(this.readAfter.seq))
|
|
171
|
+
this.readAfter = cursor;
|
|
168
172
|
}
|
|
169
173
|
if (this.options.inbox) {
|
|
170
174
|
await this.options.inbox.synchronize();
|
|
@@ -200,7 +204,7 @@ export class ReadSyncClient {
|
|
|
200
204
|
}
|
|
201
205
|
}
|
|
202
206
|
const snapshot = await this.request(`/api/social/reading/snapshot?${query}`, {
|
|
203
|
-
headers: this.readAfter ? { "x-pmate-read-after-
|
|
207
|
+
headers: this.readAfter ? { "x-pmate-read-after-seq": this.readAfter.seq, "x-pmate-stream-id": this.readAfter.streamId } : {},
|
|
204
208
|
});
|
|
205
209
|
if (this.controller.signal.aborted)
|
|
206
210
|
throw new Error("READ_SYNC_STOPPED");
|
|
@@ -210,7 +214,7 @@ export class ReadSyncClient {
|
|
|
210
214
|
return installReadSnapshot(state, this.options.metadataOnly ? readingMetadata(snapshot) : snapshot);
|
|
211
215
|
});
|
|
212
216
|
if (!next.pending.length)
|
|
213
|
-
this.readAfter =
|
|
217
|
+
this.readAfter = undefined;
|
|
214
218
|
if (!this.controller.signal.aborted)
|
|
215
219
|
this.options.onChange?.(next);
|
|
216
220
|
return next;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function sourceCursor(value) {
|
|
2
|
+
const cursor = value;
|
|
3
|
+
if (!cursor || typeof cursor.streamId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(cursor.streamId)
|
|
4
|
+
|| typeof cursor.seq !== "string" || cursor.seq.length > 20 || !/^(0|[1-9][0-9]*)$/.test(cursor.seq) || BigInt(cursor.seq) > 18446744073709551615n)
|
|
5
|
+
throw Error("INVALID_SOURCE_CURSOR");
|
|
6
|
+
return { streamId: cursor.streamId, seq: cursor.seq };
|
|
7
|
+
}
|
package/package.json
CHANGED