@pmate/chat-sdk 0.12.0-next.96 → 0.13.0-profile.0
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/framework.d.ts +2 -0
- package/lib/framework.js +2 -0
- package/lib/messageView.d.ts +5 -0
- package/lib/messageView.js +2 -2
- package/lib/profile.d.ts +14 -0
- package/lib/profile.js +10 -0
- package/lib/profileWorker.d.ts +1 -0
- package/lib/profileWorker.js +3 -0
- package/lib/runtime/profileChat.d.ts +135 -0
- package/lib/runtime/profileChat.js +299 -0
- package/lib/runtime/profileCommitQueue.d.ts +38 -0
- package/lib/runtime/profileCommitQueue.js +101 -0
- package/lib/runtime/profileCoordinator.d.ts +46 -0
- package/lib/runtime/profileCoordinator.js +135 -0
- package/lib/runtime/profileDatabase.d.ts +42 -0
- package/lib/runtime/profileDatabase.js +164 -0
- package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
- package/lib/runtime/profileGenerationBuilder.js +112 -0
- package/lib/runtime/profileInboxFeed.d.ts +38 -0
- package/lib/runtime/profileInboxFeed.js +240 -0
- package/lib/runtime/profileMemoryStore.d.ts +113 -0
- package/lib/runtime/profileMemoryStore.js +259 -0
- package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
- package/lib/runtime/profileOutboxDispatcher.js +106 -0
- package/lib/runtime/profileOwner.d.ts +57 -0
- package/lib/runtime/profileOwner.js +202 -0
- package/lib/runtime/profileProjection.d.ts +77 -0
- package/lib/runtime/profileProjection.js +625 -0
- package/lib/runtime/profileReadingIndex.d.ts +17 -0
- package/lib/runtime/profileReadingIndex.js +99 -0
- package/lib/runtime/profileReplica.d.ts +59 -0
- package/lib/runtime/profileReplica.js +236 -0
- package/lib/runtime/profileStoreTypes.d.ts +163 -0
- package/lib/runtime/profileStoreTypes.js +1 -0
- package/lib/runtime/profileWindows.d.ts +38 -0
- package/lib/runtime/profileWindows.js +175 -0
- package/lib/runtime/profileWorkerHost.d.ts +33 -0
- package/lib/runtime/profileWorkerHost.js +156 -0
- package/package.json +11 -1
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
2
|
+
/** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
|
|
3
|
+
* backpressured by durable owner commits; long requests never hold its queue. */
|
|
4
|
+
export class ProfileInboxFeed {
|
|
5
|
+
options;
|
|
6
|
+
controller = new AbortController();
|
|
7
|
+
streamController;
|
|
8
|
+
running;
|
|
9
|
+
liveTask;
|
|
10
|
+
timer;
|
|
11
|
+
closed = false;
|
|
12
|
+
building;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = options;
|
|
15
|
+
}
|
|
16
|
+
report(error) { if (!this.closed) {
|
|
17
|
+
try {
|
|
18
|
+
this.options.onError?.(error);
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
} }
|
|
22
|
+
progress(stage, processed = "0", total = "0") {
|
|
23
|
+
const count = inboxSequence(total), done = inboxSequence(processed);
|
|
24
|
+
try {
|
|
25
|
+
this.options.onProgress?.({ stage, processed, total, percent: stage === "ready" ? 100 : count ? Number(done * 9900n / count) / 100 : 0 });
|
|
26
|
+
}
|
|
27
|
+
catch { }
|
|
28
|
+
}
|
|
29
|
+
async request(action, params = {}) {
|
|
30
|
+
const identity = this.options.owner.identity;
|
|
31
|
+
const query = new URLSearchParams({ appId: identity.appId, profileId: identity.profileId, ...params });
|
|
32
|
+
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, {
|
|
33
|
+
headers: { authorization: `Bearer ${await this.options.getToken()}` }, cache: "no-store", redirect: "error",
|
|
34
|
+
signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(20000)]),
|
|
35
|
+
});
|
|
36
|
+
const result = await response.json();
|
|
37
|
+
if (!response.ok || result.success !== true || !result.data)
|
|
38
|
+
throw Object.assign(Error(`INBOX_HTTP_${response.status}`), { status: response.status });
|
|
39
|
+
return result.data;
|
|
40
|
+
}
|
|
41
|
+
async start() {
|
|
42
|
+
if (!this.timer)
|
|
43
|
+
this.timer = setInterval(() => { void this.tick().catch(error => this.report(error)); }, 10000);
|
|
44
|
+
await this.tick();
|
|
45
|
+
}
|
|
46
|
+
synchronize() {
|
|
47
|
+
if (this.closed)
|
|
48
|
+
return Promise.reject(Error("INBOX_CLIENT_CLOSED"));
|
|
49
|
+
if (this.running)
|
|
50
|
+
return this.running;
|
|
51
|
+
const task = this.catchUp().catch(error => { this.progress("error"); throw error; });
|
|
52
|
+
this.running = task;
|
|
53
|
+
void task.finally(() => { if (this.running === task)
|
|
54
|
+
this.running = undefined; }).catch(() => { });
|
|
55
|
+
return task;
|
|
56
|
+
}
|
|
57
|
+
validate(page, epoch) {
|
|
58
|
+
const identity = this.options.owner.identity;
|
|
59
|
+
if (page.appId !== identity.appId || page.profileId !== identity.profileId || page.epoch !== epoch)
|
|
60
|
+
throw Error("INBOX_IDENTITY_MISMATCH");
|
|
61
|
+
inboxSequence(page.nextSeq);
|
|
62
|
+
inboxSequence(page.headSeq);
|
|
63
|
+
if (!Array.isArray(page.events) || inboxSequence(page.nextSeq) > inboxSequence(page.headSeq))
|
|
64
|
+
throw Error("INVALID_INBOX_PAGE");
|
|
65
|
+
}
|
|
66
|
+
async commit(events, generation) {
|
|
67
|
+
let chunk = [], bytes = 0;
|
|
68
|
+
const flush = async () => {
|
|
69
|
+
if (!chunk.length)
|
|
70
|
+
return;
|
|
71
|
+
const batch = chunk;
|
|
72
|
+
chunk = [];
|
|
73
|
+
bytes = 0;
|
|
74
|
+
if (generation)
|
|
75
|
+
await this.options.owner.appendGeneration(generation, batch);
|
|
76
|
+
else
|
|
77
|
+
await Promise.all(batch.map(event => this.options.owner.enqueue(event, new TextEncoder().encode(JSON.stringify(event)).byteLength)));
|
|
78
|
+
};
|
|
79
|
+
for (const event of events) {
|
|
80
|
+
const size = new TextEncoder().encode(JSON.stringify(event)).byteLength;
|
|
81
|
+
if (chunk.length && (chunk.length >= 200 || bytes + size > 512 * 1024))
|
|
82
|
+
await flush();
|
|
83
|
+
chunk.push(event);
|
|
84
|
+
bytes += size;
|
|
85
|
+
}
|
|
86
|
+
await flush();
|
|
87
|
+
}
|
|
88
|
+
async completeReceipts(generation) {
|
|
89
|
+
if (generation ? (await this.options.owner.generationProgress(generation)).receiptsReady : this.options.owner.current.receiptsReady)
|
|
90
|
+
return;
|
|
91
|
+
let afterSeq = "0", throughSeq;
|
|
92
|
+
for (;;) {
|
|
93
|
+
const page = await this.request("bootstrap", { projection: "receipts", afterSeq, limit: "500", ...(throughSeq ? { throughSeq } : {}) });
|
|
94
|
+
const identity = this.options.owner.identity;
|
|
95
|
+
const epoch = generation ? (await this.options.owner.generationProgress(generation)).epoch : this.options.owner.current.epoch;
|
|
96
|
+
if (page.appId !== identity.appId || page.profileId !== identity.profileId || page.epoch !== epoch || page.projection !== "receipts" || page.version !== 1 || !Array.isArray(page.events))
|
|
97
|
+
throw Error("INVALID_INBOX_RECEIPT_BASELINE");
|
|
98
|
+
if (throughSeq && throughSeq !== page.throughSeq)
|
|
99
|
+
throw Error("INBOX_RECEIPT_BASELINE_CHANGED");
|
|
100
|
+
throughSeq = page.throughSeq;
|
|
101
|
+
await this.commit(page.events.map(event => ({ type: "restoreReceipt", data: event.fact })), generation);
|
|
102
|
+
if (!page.hasMore) {
|
|
103
|
+
await this.commit([{ type: "receiptsReady" }], generation);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (inboxSequence(page.nextSeq) <= inboxSequence(afterSeq))
|
|
107
|
+
throw Error("INBOX_SYNC_NO_PROGRESS");
|
|
108
|
+
afterSeq = page.nextSeq;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async rebuild() {
|
|
112
|
+
const bootstrap = await this.request("bootstrap");
|
|
113
|
+
const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch);
|
|
114
|
+
const generation = pending?.generation ?? await this.options.owner.beginGeneration(bootstrap);
|
|
115
|
+
const build = await this.options.owner.generationProgress(generation);
|
|
116
|
+
this.building = { generation, epoch: build.epoch, target: build.throughSeq ?? bootstrap.headSeq };
|
|
117
|
+
await this.resumeBuild();
|
|
118
|
+
}
|
|
119
|
+
async resumeBuild() {
|
|
120
|
+
const { generation, epoch, target } = this.building;
|
|
121
|
+
let build = await this.options.owner.generationProgress(generation);
|
|
122
|
+
const start = inboxSequence(build.committedSeq), head = inboxSequence(target);
|
|
123
|
+
while (inboxSequence(build.committedSeq) < head) {
|
|
124
|
+
const before = build.committedSeq;
|
|
125
|
+
const page = await this.request("events", { afterSeq: before, throughSeq: target, epoch, limit: "200" });
|
|
126
|
+
if (page.resetRequired || page.epoch !== epoch) {
|
|
127
|
+
this.building = undefined;
|
|
128
|
+
throw Error("INBOX_RESET_REQUIRED");
|
|
129
|
+
}
|
|
130
|
+
this.validate(page, epoch);
|
|
131
|
+
await this.commit(page.events, generation);
|
|
132
|
+
build = await this.options.owner.generationProgress(generation);
|
|
133
|
+
if (inboxSequence(build.committedSeq) <= inboxSequence(before))
|
|
134
|
+
throw Error("INBOX_SYNC_NO_PROGRESS");
|
|
135
|
+
this.progress("syncing", (inboxSequence(build.committedSeq) - start).toString(), (head - start).toString());
|
|
136
|
+
}
|
|
137
|
+
await this.completeReceipts(generation);
|
|
138
|
+
await this.options.owner.activateGeneration(generation);
|
|
139
|
+
this.building = undefined;
|
|
140
|
+
}
|
|
141
|
+
async catchUp() {
|
|
142
|
+
if (this.building)
|
|
143
|
+
await this.resumeBuild();
|
|
144
|
+
if (this.options.owner.current.epoch === "uninitialized")
|
|
145
|
+
await this.rebuild();
|
|
146
|
+
let current = this.options.owner.current;
|
|
147
|
+
let page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
|
|
148
|
+
if (page.resetRequired) {
|
|
149
|
+
await this.rebuild();
|
|
150
|
+
current = this.options.owner.current;
|
|
151
|
+
page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
|
|
152
|
+
}
|
|
153
|
+
this.validate(page, current.epoch);
|
|
154
|
+
const target = page.headSeq, start = inboxSequence(current.committedSeq);
|
|
155
|
+
for (;;) {
|
|
156
|
+
const before = this.options.owner.current.committedSeq;
|
|
157
|
+
if (page.resetRequired)
|
|
158
|
+
throw Error("INBOX_RESET_REQUIRED");
|
|
159
|
+
await this.commit(page.events);
|
|
160
|
+
const after = this.options.owner.current.committedSeq;
|
|
161
|
+
if (inboxSequence(after) >= inboxSequence(target))
|
|
162
|
+
break;
|
|
163
|
+
if (inboxSequence(after) <= inboxSequence(before))
|
|
164
|
+
throw Error("INBOX_SYNC_NO_PROGRESS");
|
|
165
|
+
this.progress("syncing", (inboxSequence(after) - start).toString(), (inboxSequence(target) - start).toString());
|
|
166
|
+
page = await this.request("events", { afterSeq: after, throughSeq: target, epoch: current.epoch, limit: "200" });
|
|
167
|
+
this.validate(page, current.epoch);
|
|
168
|
+
}
|
|
169
|
+
await this.completeReceipts();
|
|
170
|
+
this.progress("ready");
|
|
171
|
+
}
|
|
172
|
+
async tick() {
|
|
173
|
+
if (this.closed)
|
|
174
|
+
return;
|
|
175
|
+
await this.synchronize();
|
|
176
|
+
if (this.options.live === false || this.liveTask)
|
|
177
|
+
return;
|
|
178
|
+
const task = this.listen().catch(error => { if (error?.name !== "AbortError")
|
|
179
|
+
this.report(error); });
|
|
180
|
+
this.liveTask = task;
|
|
181
|
+
void task.finally(() => { if (this.liveTask === task)
|
|
182
|
+
this.liveTask = undefined; }).catch(() => { });
|
|
183
|
+
}
|
|
184
|
+
async listen() {
|
|
185
|
+
const { current, identity } = this.options.owner;
|
|
186
|
+
const controller = this.streamController = new AbortController();
|
|
187
|
+
const query = new URLSearchParams({ appId: identity.appId, profileId: identity.profileId, epoch: current.epoch, afterSeq: current.committedSeq });
|
|
188
|
+
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/live?${query}`, {
|
|
189
|
+
headers: { authorization: `Bearer ${await this.options.getToken()}` }, cache: "no-store", redirect: "error", signal: AbortSignal.any([this.controller.signal, controller.signal]),
|
|
190
|
+
});
|
|
191
|
+
if (!response.ok || !response.body)
|
|
192
|
+
throw Error(`INBOX_LIVE_HTTP_${response.status}`);
|
|
193
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
194
|
+
let buffer = "";
|
|
195
|
+
try {
|
|
196
|
+
for (;;) {
|
|
197
|
+
const part = await reader.read();
|
|
198
|
+
if (part.done)
|
|
199
|
+
break;
|
|
200
|
+
buffer += decoder.decode(part.value, { stream: true });
|
|
201
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
202
|
+
if (buffer.length > 16 * 1024 * 1024)
|
|
203
|
+
throw Error("INBOX_LIVE_TOO_LARGE");
|
|
204
|
+
let boundary;
|
|
205
|
+
while ((boundary = buffer.indexOf("\n\n")) >= 0) {
|
|
206
|
+
const frame = buffer.slice(0, boundary);
|
|
207
|
+
buffer = buffer.slice(boundary + 2);
|
|
208
|
+
const type = frame.split("\n").find(line => line.startsWith("event:"))?.slice(6).trim();
|
|
209
|
+
if (type === "error")
|
|
210
|
+
throw Error("INBOX_LIVE_UNAVAILABLE");
|
|
211
|
+
if (type !== "inbox")
|
|
212
|
+
continue;
|
|
213
|
+
const data = frame.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
214
|
+
if (!data)
|
|
215
|
+
continue;
|
|
216
|
+
const page = JSON.parse(data);
|
|
217
|
+
if (page.resetRequired) {
|
|
218
|
+
await this.synchronize();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
this.validate(page, this.options.owner.current.epoch);
|
|
222
|
+
await this.commit(page.events);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
await reader.cancel().catch(() => { });
|
|
228
|
+
reader.releaseLock();
|
|
229
|
+
if (this.streamController === controller)
|
|
230
|
+
this.streamController = undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async close() {
|
|
234
|
+
this.closed = true;
|
|
235
|
+
clearInterval(this.timer);
|
|
236
|
+
this.controller.abort();
|
|
237
|
+
this.streamController?.abort();
|
|
238
|
+
await Promise.allSettled([this.running, this.liveTask]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { ProfileCurrentState, ProfileMessage, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
2
|
+
import type { ChatMessage } from "../chatTypes.js";
|
|
3
|
+
export declare const PROFILE_PROTOCOL_VERSION = 1;
|
|
4
|
+
export declare const PROFILE_PROJECTION_VERSION = 1;
|
|
5
|
+
export type ProfileSnapshot = {
|
|
6
|
+
current: ProfileCurrentState;
|
|
7
|
+
threads: ProfileThread[];
|
|
8
|
+
windows: ProfileWindow[];
|
|
9
|
+
messages: ProfileMessage[];
|
|
10
|
+
};
|
|
11
|
+
export type ProfileDelta = {
|
|
12
|
+
protocolVersion: number;
|
|
13
|
+
generation: string;
|
|
14
|
+
fromRevision: number;
|
|
15
|
+
toRevision: number;
|
|
16
|
+
current: ProfileCurrentState;
|
|
17
|
+
threads: ProfileThread[];
|
|
18
|
+
windows: ProfileWindow[];
|
|
19
|
+
messages: ProfileMessage[];
|
|
20
|
+
deleteMessages?: string[];
|
|
21
|
+
};
|
|
22
|
+
/** Storage-free consumer shared by the owner, page adapters and WebView replicas.
|
|
23
|
+
* Only committed snapshots/deltas enter here; reads cannot initiate I/O. */
|
|
24
|
+
export declare class ProfileMemoryStore {
|
|
25
|
+
private onError;
|
|
26
|
+
private profileId;
|
|
27
|
+
private current?;
|
|
28
|
+
private entities;
|
|
29
|
+
private threads;
|
|
30
|
+
private directories;
|
|
31
|
+
private listeners;
|
|
32
|
+
private listListeners;
|
|
33
|
+
private list;
|
|
34
|
+
private pageCache;
|
|
35
|
+
private epochs;
|
|
36
|
+
private phase;
|
|
37
|
+
private presented;
|
|
38
|
+
private readingIndices;
|
|
39
|
+
private presentedPages;
|
|
40
|
+
constructor(onError?: (error: unknown) => void, profileId?: string);
|
|
41
|
+
private notify;
|
|
42
|
+
getStatus(): {
|
|
43
|
+
phase: "ready" | "restoring";
|
|
44
|
+
generation: string | undefined;
|
|
45
|
+
revision: number | undefined;
|
|
46
|
+
};
|
|
47
|
+
getThread(threadId: string): ProfileThread | undefined;
|
|
48
|
+
getMessage(messageId: string): ProfileMessage | undefined;
|
|
49
|
+
getPresentedMessage(messageId: string): Readonly<{
|
|
50
|
+
id: string;
|
|
51
|
+
threadId: string;
|
|
52
|
+
threadRootId?: string;
|
|
53
|
+
timestamp: number;
|
|
54
|
+
from?: string;
|
|
55
|
+
mine: boolean;
|
|
56
|
+
status: "sending" | "sent" | "failed" | "read";
|
|
57
|
+
recalled: boolean;
|
|
58
|
+
unread?: boolean;
|
|
59
|
+
attentionEligible?: boolean;
|
|
60
|
+
reading?: Readonly<{
|
|
61
|
+
seq?: number;
|
|
62
|
+
read: boolean;
|
|
63
|
+
readPolicy: "visible" | "explicit";
|
|
64
|
+
}>;
|
|
65
|
+
reactions: readonly Readonly<{
|
|
66
|
+
emojiId: string;
|
|
67
|
+
userIds: string[];
|
|
68
|
+
mine: boolean;
|
|
69
|
+
}>[];
|
|
70
|
+
kind: "text" | "image" | "voice" | "emoji" | "quote" | "invitation" | "system" | "attachment";
|
|
71
|
+
text: string;
|
|
72
|
+
senderName?: string;
|
|
73
|
+
senderAvatar?: string;
|
|
74
|
+
timeLabel?: string;
|
|
75
|
+
file?: import("../fileMetadata.js").ChatFile;
|
|
76
|
+
image?: Readonly<{
|
|
77
|
+
url: string;
|
|
78
|
+
name?: string;
|
|
79
|
+
}>;
|
|
80
|
+
voice?: Readonly<{
|
|
81
|
+
url: string;
|
|
82
|
+
durationMs: number;
|
|
83
|
+
transcript?: string;
|
|
84
|
+
}>;
|
|
85
|
+
quote?: Readonly<{
|
|
86
|
+
messageId?: string;
|
|
87
|
+
senderName: string;
|
|
88
|
+
content: string;
|
|
89
|
+
recalled?: boolean;
|
|
90
|
+
}>;
|
|
91
|
+
attachment?: Readonly<{
|
|
92
|
+
name?: string;
|
|
93
|
+
size?: string;
|
|
94
|
+
}>;
|
|
95
|
+
richContent?: unknown;
|
|
96
|
+
mentions?: readonly import("../index.js").ChatMention[];
|
|
97
|
+
recipientCount?: number;
|
|
98
|
+
system?: Readonly<{
|
|
99
|
+
type: "group-created" | "group-updated" | "group-dissolved" | "contact-updated";
|
|
100
|
+
title?: string;
|
|
101
|
+
}>;
|
|
102
|
+
}> | undefined;
|
|
103
|
+
getThreadList: () => readonly ProfileThread[];
|
|
104
|
+
subscribeThreadList: (listener: () => void) => () => void;
|
|
105
|
+
subscribeThread(threadId: string, listener: () => void): () => void;
|
|
106
|
+
restore(snapshot: ProfileSnapshot): void;
|
|
107
|
+
apply(delta: ProfileDelta): void;
|
|
108
|
+
private indexMessage;
|
|
109
|
+
private prepareMessageView;
|
|
110
|
+
private publish;
|
|
111
|
+
readPage(threadId: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly ProfileMessage[];
|
|
112
|
+
readPresentedPage(threadId: string, anchor: string | undefined, limit: number, direction?: "older" | "newer"): readonly ChatMessage[];
|
|
113
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { ProfileWindowDirectory } from "./profileWindows.js";
|
|
2
|
+
import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
3
|
+
import { projectMessageContent } from "../messageView.js";
|
|
4
|
+
export const PROFILE_PROTOCOL_VERSION = 1;
|
|
5
|
+
export const PROFILE_PROJECTION_VERSION = 1;
|
|
6
|
+
/** Storage-free consumer shared by the owner, page adapters and WebView replicas.
|
|
7
|
+
* Only committed snapshots/deltas enter here; reads cannot initiate I/O. */
|
|
8
|
+
export class ProfileMemoryStore {
|
|
9
|
+
onError;
|
|
10
|
+
profileId;
|
|
11
|
+
current;
|
|
12
|
+
entities = new Map();
|
|
13
|
+
threads = new Map();
|
|
14
|
+
directories = new Map();
|
|
15
|
+
listeners = new Map();
|
|
16
|
+
listListeners = new Set();
|
|
17
|
+
list = [];
|
|
18
|
+
pageCache = new Map();
|
|
19
|
+
epochs = new Map();
|
|
20
|
+
phase = "restoring";
|
|
21
|
+
presented = new Map();
|
|
22
|
+
readingIndices = new Map();
|
|
23
|
+
presentedPages = new WeakMap();
|
|
24
|
+
constructor(onError = () => { }, profileId = "") {
|
|
25
|
+
this.onError = onError;
|
|
26
|
+
this.profileId = profileId;
|
|
27
|
+
}
|
|
28
|
+
notify(listener) { try {
|
|
29
|
+
listener();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
try {
|
|
33
|
+
this.onError(error);
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
} }
|
|
37
|
+
getStatus() { return { phase: this.phase, generation: this.current?.activeGeneration, revision: this.current?.commitRevision }; }
|
|
38
|
+
getThread(threadId) { return this.threads.get(threadId); }
|
|
39
|
+
getMessage(messageId) { return this.entities.get(messageId); }
|
|
40
|
+
getPresentedMessage(messageId) { return this.presented.get(messageId); }
|
|
41
|
+
getThreadList = () => this.list;
|
|
42
|
+
subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
|
|
43
|
+
subscribeThread(threadId, listener) {
|
|
44
|
+
let listeners = this.listeners.get(threadId);
|
|
45
|
+
if (!listeners) {
|
|
46
|
+
listeners = new Set();
|
|
47
|
+
this.listeners.set(threadId, listeners);
|
|
48
|
+
}
|
|
49
|
+
listeners.add(listener);
|
|
50
|
+
return () => { listeners.delete(listener); if (!listeners.size)
|
|
51
|
+
this.listeners.delete(threadId); };
|
|
52
|
+
}
|
|
53
|
+
restore(snapshot) {
|
|
54
|
+
const generation = snapshot.current.activeGeneration;
|
|
55
|
+
if (snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
|
|
56
|
+
throw Error("PROFILE_PROJECTION_INCOMPATIBLE");
|
|
57
|
+
for (const row of [...snapshot.threads, ...snapshot.windows, ...snapshot.messages])
|
|
58
|
+
if (row.generation !== generation)
|
|
59
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
60
|
+
const entities = new Map(snapshot.messages.map(row => [row.messageId, row]));
|
|
61
|
+
const threads = new Map(snapshot.threads.map(row => [row.threadId, row]));
|
|
62
|
+
const grouped = new Map();
|
|
63
|
+
for (const window of snapshot.windows) {
|
|
64
|
+
if (!threads.has(window.threadId) || window.refs.some(ref => entities.get(ref.messageId)?.threadId !== window.threadId))
|
|
65
|
+
throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
|
|
66
|
+
const rows = grouped.get(window.threadId) ?? [];
|
|
67
|
+
rows.push(window);
|
|
68
|
+
grouped.set(window.threadId, rows);
|
|
69
|
+
}
|
|
70
|
+
const directories = new Map();
|
|
71
|
+
for (const [id, thread] of threads) {
|
|
72
|
+
const directory = new ProfileWindowDirectory(generation, id, grouped.get(id));
|
|
73
|
+
if (thread.messageCount !== directory.count || thread.windowCount !== directory.blocks.length)
|
|
74
|
+
throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
|
|
75
|
+
directories.set(id, directory);
|
|
76
|
+
}
|
|
77
|
+
// Install only after complete validation: a bad handoff retains the old view.
|
|
78
|
+
const affected = new Set([...this.threads.keys(), ...threads.keys()]);
|
|
79
|
+
this.entities = entities;
|
|
80
|
+
this.threads = threads;
|
|
81
|
+
this.directories = directories;
|
|
82
|
+
this.readingIndices.clear();
|
|
83
|
+
this.presented.clear();
|
|
84
|
+
this.presentedPages = new WeakMap();
|
|
85
|
+
for (const row of entities.values()) {
|
|
86
|
+
this.indexMessage(row);
|
|
87
|
+
this.prepareMessageView(row);
|
|
88
|
+
}
|
|
89
|
+
this.current = snapshot.current;
|
|
90
|
+
this.phase = snapshot.current.epoch === "uninitialized" ? "restoring" : "ready";
|
|
91
|
+
this.pageCache.clear();
|
|
92
|
+
this.epochs.clear();
|
|
93
|
+
this.publish(affected, true);
|
|
94
|
+
}
|
|
95
|
+
apply(delta) {
|
|
96
|
+
if (delta.protocolVersion !== PROFILE_PROTOCOL_VERSION)
|
|
97
|
+
throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
|
|
98
|
+
if (!this.current || delta.generation !== this.current.activeGeneration || delta.current.activeGeneration !== delta.generation)
|
|
99
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
100
|
+
if (delta.toRevision <= this.current.commitRevision)
|
|
101
|
+
return;
|
|
102
|
+
if (delta.fromRevision !== this.current.commitRevision || delta.toRevision !== delta.current.commitRevision || delta.toRevision <= delta.fromRevision)
|
|
103
|
+
throw Error("PROFILE_REVISION_GAP");
|
|
104
|
+
if (delta.current.projectionVersion !== this.current.projectionVersion)
|
|
105
|
+
throw Error("PROFILE_PROJECTION_INCOMPATIBLE");
|
|
106
|
+
for (const row of [...delta.threads, ...delta.windows, ...delta.messages])
|
|
107
|
+
if (row.generation !== delta.generation)
|
|
108
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
109
|
+
const incomingThreads = new Map(delta.threads.map(row => [row.threadId, row]));
|
|
110
|
+
const incomingMessages = new Map(delta.messages.map(row => [row.messageId, row]));
|
|
111
|
+
const deleted = new Set(delta.deleteMessages);
|
|
112
|
+
for (const window of delta.windows) {
|
|
113
|
+
if (!(incomingThreads.has(window.threadId) || this.threads.has(window.threadId)))
|
|
114
|
+
throw Error("PROFILE_DELTA_INCOMPLETE");
|
|
115
|
+
for (const ref of window.refs) {
|
|
116
|
+
const entity = incomingMessages.get(ref.messageId) ?? this.entities.get(ref.messageId);
|
|
117
|
+
if (deleted.has(ref.messageId) || entity?.threadId !== window.threadId)
|
|
118
|
+
throw Error("PROFILE_DELTA_INCOMPLETE");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const affected = new Set(delta.threads.map(row => row.threadId));
|
|
122
|
+
const previousThreads = new Map(delta.threads.map(row => [row.threadId, this.threads.get(row.threadId)]));
|
|
123
|
+
for (const message of delta.messages) {
|
|
124
|
+
const previous = this.entities.get(message.messageId);
|
|
125
|
+
if (previous)
|
|
126
|
+
this.readingIndices.get(previous.threadId)?.remove(previous);
|
|
127
|
+
if (previous)
|
|
128
|
+
affected.add(previous.threadId);
|
|
129
|
+
affected.add(message.threadId);
|
|
130
|
+
this.entities.set(message.messageId, message);
|
|
131
|
+
}
|
|
132
|
+
for (const id of deleted) {
|
|
133
|
+
const previous = this.entities.get(id);
|
|
134
|
+
if (previous)
|
|
135
|
+
affected.add(previous.threadId);
|
|
136
|
+
this.entities.delete(id);
|
|
137
|
+
this.presented.delete(id);
|
|
138
|
+
if (previous)
|
|
139
|
+
this.readingIndices.get(previous.threadId)?.remove(previous);
|
|
140
|
+
}
|
|
141
|
+
for (const thread of delta.threads)
|
|
142
|
+
this.threads.set(thread.threadId, thread);
|
|
143
|
+
for (const window of delta.windows) {
|
|
144
|
+
let directory = this.directories.get(window.threadId);
|
|
145
|
+
if (!directory) {
|
|
146
|
+
directory = new ProfileWindowDirectory(delta.generation, window.threadId);
|
|
147
|
+
this.directories.set(window.threadId, directory);
|
|
148
|
+
}
|
|
149
|
+
directory.accept({ windows: [window], windowCount: 0 });
|
|
150
|
+
affected.add(window.threadId);
|
|
151
|
+
}
|
|
152
|
+
this.current = delta.current;
|
|
153
|
+
for (const message of delta.messages) {
|
|
154
|
+
this.indexMessage(message);
|
|
155
|
+
this.prepareMessageView(message);
|
|
156
|
+
}
|
|
157
|
+
for (const thread of delta.threads) {
|
|
158
|
+
const previous = previousThreads.get(thread.threadId);
|
|
159
|
+
const index = this.readingIndices.get(thread.threadId);
|
|
160
|
+
for (const source of thread.readingSources) {
|
|
161
|
+
const before = previous?.readingSources.find(row => row.sourceThreadId === source.sourceThreadId);
|
|
162
|
+
const low = Math.max(before?.readThroughSeq ?? 0, before?.pendingReadThroughSeq ?? 0);
|
|
163
|
+
const high = Math.max(source.readThroughSeq, source.pendingReadThroughSeq ?? 0);
|
|
164
|
+
if (low !== high)
|
|
165
|
+
for (const ref of index?.visibleBetween(source.sourceThreadId, Math.min(low, high), Math.max(low, high)) ?? []) {
|
|
166
|
+
const message = this.entities.get(ref.messageId);
|
|
167
|
+
if (message)
|
|
168
|
+
this.prepareMessageView(message);
|
|
169
|
+
}
|
|
170
|
+
const oldExplicit = new Set([...(before?.explicitReadMessageIds ?? []), ...(before?.pendingExplicitReadMessageIds ?? [])]);
|
|
171
|
+
for (const id of [...source.explicitReadMessageIds, ...source.pendingExplicitReadMessageIds ?? []]) {
|
|
172
|
+
const message = this.entities.get(id);
|
|
173
|
+
if (!oldExplicit.has(id) && message?.threadId === thread.threadId)
|
|
174
|
+
this.prepareMessageView(message);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (thread.rootMessageId) {
|
|
178
|
+
const root = this.entities.get(thread.rootMessageId);
|
|
179
|
+
if (root) {
|
|
180
|
+
this.prepareMessageView(root);
|
|
181
|
+
affected.add(root.threadId);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
this.publish(affected, delta.threads.length > 0);
|
|
186
|
+
}
|
|
187
|
+
indexMessage(message) {
|
|
188
|
+
const index = this.readingIndices.get(message.threadId) ?? new ProfileReadingIndex();
|
|
189
|
+
index.upsert(message, this.profileId, this.threads.get(message.threadId)?.readingSources.find(source => source.sourceThreadId === message.sourceThreadId));
|
|
190
|
+
this.readingIndices.set(message.threadId, index);
|
|
191
|
+
}
|
|
192
|
+
prepareMessageView(message) {
|
|
193
|
+
const thread = this.threads.get(message.threadId);
|
|
194
|
+
const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
|
|
195
|
+
const mine = message.from === this.profileId;
|
|
196
|
+
const policy = message.readPolicy ?? "visible";
|
|
197
|
+
const read = mine || message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
|
|
198
|
+
message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
|
|
199
|
+
source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
|
|
200
|
+
policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
|
|
201
|
+
const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
|
|
202
|
+
from: message.from, recipients: message.recipients, body: message.content, threadKind: thread?.kind === "dm" ? "dm" : "group", teamId: thread?.teamId });
|
|
203
|
+
const visibleContent = message.recalled ? { kind: "system", text: "" } : content;
|
|
204
|
+
const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
|
|
205
|
+
...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
|
|
206
|
+
status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
|
|
207
|
+
recalled: message.recalled ?? false, unread: thread?.readingStatus === "unknown" ? undefined : !read,
|
|
208
|
+
attentionEligible: message.mention, reading: thread?.readingStatus === "unknown" ? undefined : { seq: message.sourceSeq, read,
|
|
209
|
+
readPolicy: policy === "visible" ? "visible" : "explicit" },
|
|
210
|
+
reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
|
|
211
|
+
this.presented.set(message.messageId, value);
|
|
212
|
+
}
|
|
213
|
+
publish(affected, directoryChanged) {
|
|
214
|
+
for (const thread of affected)
|
|
215
|
+
this.epochs.set(thread, (this.epochs.get(thread) ?? 0) + 1);
|
|
216
|
+
// Cached pages live only until that thread changes; no unbounded scroll cache.
|
|
217
|
+
for (const key of this.pageCache.keys())
|
|
218
|
+
if (affected.has(JSON.parse(key)[0]))
|
|
219
|
+
this.pageCache.delete(key);
|
|
220
|
+
if (directoryChanged) {
|
|
221
|
+
this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion")
|
|
222
|
+
.sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.threadId.localeCompare(b.threadId));
|
|
223
|
+
}
|
|
224
|
+
for (const thread of affected)
|
|
225
|
+
for (const listener of this.listeners.get(thread) ?? [])
|
|
226
|
+
this.notify(listener);
|
|
227
|
+
if (directoryChanged)
|
|
228
|
+
for (const listener of this.listListeners)
|
|
229
|
+
this.notify(listener);
|
|
230
|
+
}
|
|
231
|
+
readPage(threadId, anchor, limit, direction = "older") {
|
|
232
|
+
if (this.phase !== "ready" || this.threads.get(threadId)?.status !== "ready")
|
|
233
|
+
throw Error("PROFILE_THREAD_NOT_READY");
|
|
234
|
+
const key = JSON.stringify([threadId, anchor ?? null, limit, direction]), epoch = this.epochs.get(threadId) ?? 0;
|
|
235
|
+
const cached = this.pageCache.get(key);
|
|
236
|
+
if (cached?.epoch === epoch)
|
|
237
|
+
return cached.rows;
|
|
238
|
+
const directory = this.directories.get(threadId);
|
|
239
|
+
const rows = directory?.readPage(anchor, limit, direction).map(ref => {
|
|
240
|
+
const row = this.entities.get(ref.messageId);
|
|
241
|
+
if (!row)
|
|
242
|
+
throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
|
|
243
|
+
return row;
|
|
244
|
+
}) ?? [];
|
|
245
|
+
if (this.pageCache.size >= 128)
|
|
246
|
+
this.pageCache.delete(this.pageCache.keys().next().value);
|
|
247
|
+
this.pageCache.set(key, { epoch, rows });
|
|
248
|
+
return rows;
|
|
249
|
+
}
|
|
250
|
+
readPresentedPage(threadId, anchor, limit, direction = "older") {
|
|
251
|
+
const raw = this.readPage(threadId, anchor, limit, direction);
|
|
252
|
+
let page = this.presentedPages.get(raw);
|
|
253
|
+
if (!page) {
|
|
254
|
+
page = raw.map(row => this.presented.get(row.messageId));
|
|
255
|
+
this.presentedPages.set(raw, page);
|
|
256
|
+
}
|
|
257
|
+
return page;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ProfileOwner } from "./profileOwner.js";
|
|
2
|
+
import type { ChatRuntimeMessage } from "./protocol.js";
|
|
3
|
+
export type ProfileOutboxDispatcherOptions = {
|
|
4
|
+
owner: ProfileOwner;
|
|
5
|
+
sendMessage: (message: ChatRuntimeMessage) => Promise<unknown>;
|
|
6
|
+
hubHttpUrl: string;
|
|
7
|
+
getToken: () => string | Promise<string>;
|
|
8
|
+
fetch?: typeof fetch;
|
|
9
|
+
uploadEndpoint?: string;
|
|
10
|
+
onError?: (error: unknown) => void;
|
|
11
|
+
};
|
|
12
|
+
/** Reads committed commands from owner memory. All status/ACK transitions return
|
|
13
|
+
* to the same durable queue; network waits never block local event processing. */
|
|
14
|
+
export declare class ProfileOutboxDispatcher {
|
|
15
|
+
private options;
|
|
16
|
+
private running?;
|
|
17
|
+
private timer?;
|
|
18
|
+
private scheduled?;
|
|
19
|
+
private off?;
|
|
20
|
+
private closed;
|
|
21
|
+
private controller;
|
|
22
|
+
constructor(options: ProfileOutboxDispatcherOptions);
|
|
23
|
+
start(): void;
|
|
24
|
+
private report;
|
|
25
|
+
private schedule;
|
|
26
|
+
drain(): Promise<void>;
|
|
27
|
+
private transition;
|
|
28
|
+
private run;
|
|
29
|
+
private reading;
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
}
|