@pmate/chat-sdk 0.12.0-next.88 → 0.12.0-next.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/runtime/chatSession.d.ts +2 -0
- package/lib/runtime/chatSession.js +17 -1
- package/lib/runtime/createChat.d.ts +2 -0
- package/lib/runtime/createChat.js +17 -4
- package/lib/runtime/groupClient.d.ts +1 -0
- package/lib/runtime/groupClient.js +3 -3
- package/lib/runtime/inboxClient.d.ts +63 -0
- package/lib/runtime/inboxClient.js +259 -0
- package/lib/runtime/inboxGroup.d.ts +4 -0
- package/lib/runtime/inboxGroup.js +51 -0
- package/lib/runtime/inboxStore.d.ts +178 -0
- package/lib/runtime/inboxStore.js +307 -0
- package/lib/runtime/inboxTransport.d.ts +6 -0
- package/lib/runtime/inboxTransport.js +67 -0
- package/lib/runtime/index.d.ts +2 -0
- package/lib/runtime/index.js +2 -0
- package/lib/runtime/messageClient.d.ts +2 -0
- package/lib/runtime/messageClient.js +3 -3
- package/lib/runtime/readSync.d.ts +6 -0
- package/lib/runtime/readSync.js +42 -1
- package/lib/runtime/readingClient.d.ts +3 -0
- package/lib/runtime/readingClient.js +11 -2
- package/package.json +1 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { Dexie, type Table } from "dexie";
|
|
2
|
+
import { type ReadSnapshot } from "./readIndex.js";
|
|
3
|
+
import type { MessageThreadSummary } from "./socialReadClient.js";
|
|
4
|
+
import type { ChatReaderSocialMessage } from "./readerClient.js";
|
|
5
|
+
export type InboxScope = {
|
|
6
|
+
appId: string;
|
|
7
|
+
accountId: string;
|
|
8
|
+
profileId: string;
|
|
9
|
+
};
|
|
10
|
+
export type InboxEvent = {
|
|
11
|
+
inboxSeq: string;
|
|
12
|
+
sourceId: string;
|
|
13
|
+
acceptedAt: number;
|
|
14
|
+
kind: string;
|
|
15
|
+
fact: Record<string, any>;
|
|
16
|
+
};
|
|
17
|
+
export type InboxPage = {
|
|
18
|
+
epoch: string;
|
|
19
|
+
appId: string;
|
|
20
|
+
profileId: string;
|
|
21
|
+
startSeq: string;
|
|
22
|
+
nextSeq: string;
|
|
23
|
+
headSeq: string;
|
|
24
|
+
hasMore: boolean;
|
|
25
|
+
resetRequired: boolean;
|
|
26
|
+
events: InboxEvent[];
|
|
27
|
+
};
|
|
28
|
+
export type InboxBootstrap = {
|
|
29
|
+
epoch: string;
|
|
30
|
+
appId: string;
|
|
31
|
+
profileId: string;
|
|
32
|
+
startSeq: string;
|
|
33
|
+
headSeq: string;
|
|
34
|
+
windowStart: number;
|
|
35
|
+
basis: {
|
|
36
|
+
id: string;
|
|
37
|
+
kind: string;
|
|
38
|
+
fact: Record<string, any>;
|
|
39
|
+
inboxSeq: string;
|
|
40
|
+
}[];
|
|
41
|
+
};
|
|
42
|
+
export type InboxCursor = {
|
|
43
|
+
owner: string;
|
|
44
|
+
epoch: string;
|
|
45
|
+
seq: string;
|
|
46
|
+
windowStart: number;
|
|
47
|
+
initialized: boolean;
|
|
48
|
+
};
|
|
49
|
+
type InboxLease = {
|
|
50
|
+
owner: string;
|
|
51
|
+
token: string;
|
|
52
|
+
expiresAt: number;
|
|
53
|
+
};
|
|
54
|
+
export type InboxMessage = ChatReaderSocialMessage & {
|
|
55
|
+
seq: number;
|
|
56
|
+
recalled?: boolean;
|
|
57
|
+
};
|
|
58
|
+
type MessageRow = {
|
|
59
|
+
owner: string;
|
|
60
|
+
thread: string;
|
|
61
|
+
id: string;
|
|
62
|
+
acceptedAt: number;
|
|
63
|
+
time: number;
|
|
64
|
+
seq: number;
|
|
65
|
+
changeSeq: string;
|
|
66
|
+
root: string;
|
|
67
|
+
recalled: boolean;
|
|
68
|
+
value: InboxMessage;
|
|
69
|
+
};
|
|
70
|
+
type FactRow = {
|
|
71
|
+
owner: string;
|
|
72
|
+
kind: string;
|
|
73
|
+
id: string;
|
|
74
|
+
thread: string;
|
|
75
|
+
value: Record<string, any>;
|
|
76
|
+
};
|
|
77
|
+
type PositionRow = {
|
|
78
|
+
owner: string;
|
|
79
|
+
thread: string;
|
|
80
|
+
root: string;
|
|
81
|
+
seq: number;
|
|
82
|
+
messageId?: string;
|
|
83
|
+
};
|
|
84
|
+
type ExplicitRow = {
|
|
85
|
+
owner: string;
|
|
86
|
+
thread: string;
|
|
87
|
+
id: string;
|
|
88
|
+
preserved?: boolean;
|
|
89
|
+
};
|
|
90
|
+
type ThreadRow = {
|
|
91
|
+
owner: string;
|
|
92
|
+
id: string;
|
|
93
|
+
kind: "dm" | "group";
|
|
94
|
+
teamId?: string;
|
|
95
|
+
targetId: string;
|
|
96
|
+
};
|
|
97
|
+
export declare function inboxSequence(value: string): bigint;
|
|
98
|
+
/** Normalized facts and derived positions commit with their Inbox cursor. No
|
|
99
|
+
* serialized full-history snapshot is persisted after each message. */
|
|
100
|
+
export declare class IndexedDbInbox {
|
|
101
|
+
readonly scope: InboxScope;
|
|
102
|
+
readonly db: Dexie;
|
|
103
|
+
readonly owner: string;
|
|
104
|
+
readonly cursors: Table<InboxCursor, string>;
|
|
105
|
+
readonly messages: Table<MessageRow, [string, string, string]>;
|
|
106
|
+
readonly facts: Table<FactRow, [string, string, string]>;
|
|
107
|
+
readonly positions: Table<PositionRow, [string, string, string]>;
|
|
108
|
+
readonly explicit: Table<ExplicitRow, [string, string, string]>;
|
|
109
|
+
readonly threads: Table<ThreadRow, [string, string]>;
|
|
110
|
+
readonly leases: Table<InboxLease, string>;
|
|
111
|
+
constructor(scope: InboxScope, options?: {
|
|
112
|
+
indexedDB?: IDBFactory;
|
|
113
|
+
name?: string;
|
|
114
|
+
});
|
|
115
|
+
private tables;
|
|
116
|
+
cursor(): import("dexie").PromiseExtended<InboxCursor | undefined>;
|
|
117
|
+
claimLease(token: string, now?: number): import("dexie").PromiseExtended<boolean>;
|
|
118
|
+
releaseLease(token: string): import("dexie").PromiseExtended<void>;
|
|
119
|
+
private identity;
|
|
120
|
+
bootstrap(input: InboxBootstrap): Promise<InboxCursor>;
|
|
121
|
+
apply(page: InboxPage): Promise<{
|
|
122
|
+
cursor: {
|
|
123
|
+
seq: string;
|
|
124
|
+
initialized: boolean;
|
|
125
|
+
owner: string;
|
|
126
|
+
epoch: string;
|
|
127
|
+
windowStart: number;
|
|
128
|
+
};
|
|
129
|
+
threads: string[];
|
|
130
|
+
}>;
|
|
131
|
+
private applyFact;
|
|
132
|
+
readingSnapshot(): Promise<ReadSnapshot>;
|
|
133
|
+
threadMessages(thread: string): Promise<{
|
|
134
|
+
recalled: boolean;
|
|
135
|
+
body: any;
|
|
136
|
+
teamId?: string;
|
|
137
|
+
sourceThreadId?: string;
|
|
138
|
+
appId: string;
|
|
139
|
+
threadId: string;
|
|
140
|
+
threadKind: "dm" | "group";
|
|
141
|
+
messageId: string;
|
|
142
|
+
from: string;
|
|
143
|
+
to: string;
|
|
144
|
+
recipients?: string[];
|
|
145
|
+
clientCreatedAt?: number;
|
|
146
|
+
serverCreatedAt: number;
|
|
147
|
+
seq: number;
|
|
148
|
+
}[]>;
|
|
149
|
+
conversationMessages(thread: string, teamId: string): Promise<{
|
|
150
|
+
recalled: boolean;
|
|
151
|
+
body: any;
|
|
152
|
+
teamId?: string;
|
|
153
|
+
sourceThreadId?: string;
|
|
154
|
+
appId: string;
|
|
155
|
+
threadId: string;
|
|
156
|
+
threadKind: "dm" | "group";
|
|
157
|
+
messageId: string;
|
|
158
|
+
from: string;
|
|
159
|
+
to: string;
|
|
160
|
+
recipients?: string[];
|
|
161
|
+
clientCreatedAt?: number;
|
|
162
|
+
serverCreatedAt: number;
|
|
163
|
+
seq: number;
|
|
164
|
+
}[]>;
|
|
165
|
+
conversationChanges(thread: string, teamId: string, afterSeq: string, afterId?: string): Promise<{
|
|
166
|
+
changeSeq: string;
|
|
167
|
+
id: string;
|
|
168
|
+
}[]>;
|
|
169
|
+
structureSequence(thread: string): Promise<bigint>;
|
|
170
|
+
discussionSummaries(thread: string, team: string, roots: readonly string[]): Promise<{
|
|
171
|
+
items: MessageThreadSummary[];
|
|
172
|
+
revision: number;
|
|
173
|
+
}>;
|
|
174
|
+
group(groupId: string, teamId: string): Promise<import("./socialReadClient.js").SocialGroup | undefined>;
|
|
175
|
+
private annotatedBody;
|
|
176
|
+
close(): void;
|
|
177
|
+
}
|
|
178
|
+
export {};
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { Dexie } from "dexie";
|
|
2
|
+
import { messageRequiresPlayback, isReadingControl } from "./readingContent.js";
|
|
3
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
4
|
+
import { projectInboxGroup } from "./inboxGroup.js";
|
|
5
|
+
import { readingCursor, sourcesInConversation } from "./readIndex.js";
|
|
6
|
+
export function inboxSequence(value) {
|
|
7
|
+
if (typeof value !== "string" || !/^(0|[1-9]\d{0,18})$/.test(value))
|
|
8
|
+
throw new Error("INVALID_INBOX_SEQUENCE");
|
|
9
|
+
const number = BigInt(value);
|
|
10
|
+
if (number > 9223372036854775807n)
|
|
11
|
+
throw new Error("INVALID_INBOX_SEQUENCE");
|
|
12
|
+
return number;
|
|
13
|
+
}
|
|
14
|
+
/** Normalized facts and derived positions commit with their Inbox cursor. No
|
|
15
|
+
* serialized full-history snapshot is persisted after each message. */
|
|
16
|
+
export class IndexedDbInbox {
|
|
17
|
+
scope;
|
|
18
|
+
db;
|
|
19
|
+
owner;
|
|
20
|
+
cursors;
|
|
21
|
+
messages;
|
|
22
|
+
facts;
|
|
23
|
+
positions;
|
|
24
|
+
explicit;
|
|
25
|
+
threads;
|
|
26
|
+
leases;
|
|
27
|
+
constructor(scope, options = {}) {
|
|
28
|
+
this.scope = scope;
|
|
29
|
+
this.owner = JSON.stringify([scope.accountId, scope.appId, scope.profileId]);
|
|
30
|
+
this.db = new Dexie(options.name ?? "pmate-chat-inbox-v1", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
|
|
31
|
+
this.db.version(1).stores({ cursors: "owner", messages: "[owner+thread+id],[owner+thread+seq],[owner+thread+time+id],[owner+thread],owner", facts: "[owner+kind+id],[owner+kind],[owner+thread],owner", positions: "[owner+thread+root],[owner+thread],owner", explicit: "[owner+thread+id],[owner+thread],owner", threads: "[owner+id],owner" });
|
|
32
|
+
this.db.version(2).stores({ leases: "owner" });
|
|
33
|
+
this.db.version(3).stores({ messages: "[owner+thread+id],[owner+thread+seq],[owner+thread+time+id],[owner+thread+changeSeq+id],[owner+thread],owner" });
|
|
34
|
+
this.cursors = this.db.table("cursors");
|
|
35
|
+
this.messages = this.db.table("messages");
|
|
36
|
+
this.facts = this.db.table("facts");
|
|
37
|
+
this.positions = this.db.table("positions");
|
|
38
|
+
this.explicit = this.db.table("explicit");
|
|
39
|
+
this.threads = this.db.table("threads");
|
|
40
|
+
this.leases = this.db.table("leases");
|
|
41
|
+
}
|
|
42
|
+
tables() { return [this.cursors, this.messages, this.facts, this.positions, this.explicit, this.threads]; }
|
|
43
|
+
cursor() { return this.cursors.get(this.owner); }
|
|
44
|
+
claimLease(token, now = Date.now()) {
|
|
45
|
+
return this.db.transaction("rw", this.leases, async () => {
|
|
46
|
+
const old = await this.leases.get(this.owner);
|
|
47
|
+
if (old && old.token !== token && old.expiresAt > now)
|
|
48
|
+
return false;
|
|
49
|
+
await this.leases.put({ owner: this.owner, token, expiresAt: now + 30000 });
|
|
50
|
+
return true;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
releaseLease(token) { return this.db.transaction("rw", this.leases, async () => { if ((await this.leases.get(this.owner))?.token === token)
|
|
54
|
+
await this.leases.delete(this.owner); }); }
|
|
55
|
+
identity(data) { if (data.appId !== this.scope.appId || data.profileId !== this.scope.profileId)
|
|
56
|
+
throw new Error("INBOX_IDENTITY_MISMATCH"); }
|
|
57
|
+
async bootstrap(input) {
|
|
58
|
+
this.identity(input);
|
|
59
|
+
const start = inboxSequence(input.startSeq), head = inboxSequence(input.headSeq);
|
|
60
|
+
if (!input.epoch || start < 1n || start > head + 1n || !Number.isSafeInteger(input.windowStart) || !Array.isArray(input.basis))
|
|
61
|
+
throw new Error("INVALID_INBOX_BOOTSTRAP");
|
|
62
|
+
return this.db.transaction("rw", this.tables(), async () => {
|
|
63
|
+
// A reset rebuilds current state, while older message cache stays available.
|
|
64
|
+
const old = await this.messages.where("owner").equals(this.owner).toArray();
|
|
65
|
+
await this.messages.bulkDelete(old.filter(row => row.acceptedAt >= input.windowStart).map(row => [row.owner, row.thread, row.id]));
|
|
66
|
+
for (const table of [this.facts, this.positions, this.explicit, this.threads])
|
|
67
|
+
await table.where("owner").equals(this.owner).delete();
|
|
68
|
+
for (const item of [...input.basis].sort((a, b) => inboxSequence(a.inboxSeq) < inboxSequence(b.inboxSeq) ? -1 : 1)) {
|
|
69
|
+
if (inboxSequence(item.inboxSeq) >= start)
|
|
70
|
+
throw new Error("INVALID_INBOX_BASIS_SEQUENCE");
|
|
71
|
+
await this.applyFact({ inboxSeq: item.inboxSeq, sourceId: item.id, acceptedAt: input.windowStart - 1, kind: item.kind, fact: item.fact }, input.windowStart, true);
|
|
72
|
+
}
|
|
73
|
+
const cursor = { owner: this.owner, epoch: input.epoch, seq: (start - 1n).toString(), windowStart: input.windowStart, initialized: false };
|
|
74
|
+
await this.cursors.put(cursor);
|
|
75
|
+
return cursor;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async apply(page) {
|
|
79
|
+
this.identity(page);
|
|
80
|
+
inboxSequence(page.startSeq);
|
|
81
|
+
const next = inboxSequence(page.nextSeq), head = inboxSequence(page.headSeq);
|
|
82
|
+
if (page.resetRequired)
|
|
83
|
+
throw new Error("INBOX_RESET_REQUIRED");
|
|
84
|
+
if (next > head || !Array.isArray(page.events))
|
|
85
|
+
throw new Error("INVALID_INBOX_PAGE");
|
|
86
|
+
return this.db.transaction("rw", this.tables(), async () => {
|
|
87
|
+
const cursor = await this.cursor();
|
|
88
|
+
if (!cursor || cursor.epoch !== page.epoch)
|
|
89
|
+
throw new Error("INBOX_RESET_REQUIRED");
|
|
90
|
+
let sequence = inboxSequence(cursor.seq);
|
|
91
|
+
const changed = new Set();
|
|
92
|
+
for (const event of page.events) {
|
|
93
|
+
const incoming = inboxSequence(event.inboxSeq);
|
|
94
|
+
if (incoming <= sequence)
|
|
95
|
+
continue;
|
|
96
|
+
if (incoming !== sequence + 1n || incoming > head)
|
|
97
|
+
throw new Error("INBOX_SEQUENCE_GAP");
|
|
98
|
+
if (!Number.isSafeInteger(event.acceptedAt) || event.acceptedAt < 0 || !event.sourceId)
|
|
99
|
+
throw new Error("INVALID_INBOX_EVENT");
|
|
100
|
+
const thread = await this.applyFact(event, cursor.windowStart, false);
|
|
101
|
+
if (thread)
|
|
102
|
+
changed.add(thread);
|
|
103
|
+
sequence = incoming;
|
|
104
|
+
}
|
|
105
|
+
if (next > sequence)
|
|
106
|
+
throw new Error("INBOX_SEQUENCE_GAP");
|
|
107
|
+
const updated = { ...cursor, seq: sequence.toString(), initialized: cursor.initialized || sequence >= head };
|
|
108
|
+
await this.cursors.put(updated);
|
|
109
|
+
return { cursor: updated, threads: [...changed] };
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async applyFact(event, windowStart, basis) {
|
|
113
|
+
const data = event.fact, owner = this.owner;
|
|
114
|
+
if (!data || data.appId !== this.scope.appId)
|
|
115
|
+
throw new Error("INBOX_FACT_IDENTITY_MISMATCH");
|
|
116
|
+
switch (event.kind) {
|
|
117
|
+
case "messageAdded": {
|
|
118
|
+
const message = data, thread = message.threadId;
|
|
119
|
+
if (!thread || !message.messageId || !message.from || !Number.isSafeInteger(message.seq) || message.seq < 1 || !["dm", "group"].includes(message.threadKind))
|
|
120
|
+
throw new Error("INVALID_INBOX_MESSAGE");
|
|
121
|
+
if (message.from !== this.scope.profileId && !message.recipients?.includes(this.scope.profileId) && !(message.threadKind === "dm" && message.to === this.scope.profileId))
|
|
122
|
+
throw new Error("INBOX_MESSAGE_INACCESSIBLE");
|
|
123
|
+
await this.threads.put({ owner, id: thread, kind: message.threadKind, teamId: message.teamId, targetId: message.to });
|
|
124
|
+
const body = message.body;
|
|
125
|
+
if (body?.kind === "group") {
|
|
126
|
+
await this.facts.put({ owner, kind: "groupControl", id: message.messageId, thread, value: data });
|
|
127
|
+
await this.facts.put({ owner, kind: "structure", id: thread, thread, value: { seq: event.inboxSeq } });
|
|
128
|
+
return thread;
|
|
129
|
+
}
|
|
130
|
+
if (basis || event.acceptedAt < windowStart)
|
|
131
|
+
return thread;
|
|
132
|
+
const root = messageThreadRoot(message.body) ?? "";
|
|
133
|
+
const recalls = await this.facts.get([owner, "recall", JSON.stringify([thread, message.messageId])]);
|
|
134
|
+
await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: event.acceptedAt, time: message.serverCreatedAt, seq: message.seq, changeSeq: event.inboxSeq.padStart(19, "0"), root, recalled: recalls?.value.from === message.from, value: message });
|
|
135
|
+
const target = body?.kind === "recall" ? body.targetMessageId : body?.kind === "message" && body.content?.appId === this.scope.appId ? body.content?.recall?.messageId : undefined;
|
|
136
|
+
if (typeof target === "string") {
|
|
137
|
+
const key = JSON.stringify([thread, target]);
|
|
138
|
+
await this.facts.put({ owner, kind: "recall", id: key, thread, value: { from: message.from, target } });
|
|
139
|
+
const old = await this.messages.get([owner, thread, target]);
|
|
140
|
+
if (old && old.value.from === message.from)
|
|
141
|
+
await this.messages.update([owner, thread, target], { recalled: true, changeSeq: event.inboxSeq.padStart(19, "0") });
|
|
142
|
+
}
|
|
143
|
+
return thread;
|
|
144
|
+
}
|
|
145
|
+
case "readingUpdated": {
|
|
146
|
+
if (data.profileId !== this.scope.profileId || !data.threadId || !Number.isSafeInteger(data.readThroughSeq) || data.readThroughSeq < 0 || !Array.isArray(data.explicitReadMessageIds))
|
|
147
|
+
throw new Error("INVALID_INBOX_READING");
|
|
148
|
+
const thread = data.threadId, root = data.threadRootId ?? "", old = await this.positions.get([owner, thread, root]);
|
|
149
|
+
if (!old || data.readThroughSeq > old.seq)
|
|
150
|
+
await this.positions.put({ owner, thread, root, seq: data.readThroughSeq, messageId: data.readThroughMessageId });
|
|
151
|
+
if (data.explicitReadMessageIds.length)
|
|
152
|
+
await this.explicit.bulkPut(data.explicitReadMessageIds.map((id) => ({ owner, thread, id })));
|
|
153
|
+
return thread;
|
|
154
|
+
}
|
|
155
|
+
case "threadAssigned": {
|
|
156
|
+
if (!data.sourceThreadId || !data.threadId || !data.teamId)
|
|
157
|
+
throw new Error("INVALID_INBOX_ASSIGNMENT");
|
|
158
|
+
await this.facts.put({ owner, kind: event.kind, id: data.sourceThreadId, thread: data.sourceThreadId, value: data });
|
|
159
|
+
await this.facts.put({ owner, kind: "structure", id: data.sourceThreadId, thread: data.sourceThreadId, value: { seq: event.inboxSeq } });
|
|
160
|
+
return data.threadId;
|
|
161
|
+
}
|
|
162
|
+
case "threadOrganized": {
|
|
163
|
+
if (!data.threadId || !data.rootMessageId || !Array.isArray(data.messageIds) || !Number.isSafeInteger(data.revision))
|
|
164
|
+
throw new Error("INVALID_INBOX_ORGANIZATION");
|
|
165
|
+
const thread = data.threadId, key = JSON.stringify([thread, data.rootMessageId]), old = await this.facts.get([owner, event.kind, key]);
|
|
166
|
+
if (old && old.value.revision >= data.revision)
|
|
167
|
+
return thread;
|
|
168
|
+
const selected = await this.messages.bulkGet(data.messageIds.map((id) => [owner, thread, id]));
|
|
169
|
+
for (const message of selected) {
|
|
170
|
+
if (!message)
|
|
171
|
+
continue;
|
|
172
|
+
const position = await this.positions.get([owner, thread, message.root]);
|
|
173
|
+
if (!messageRequiresPlayback(message.value.body) && message.seq <= (position?.seq ?? 0))
|
|
174
|
+
await this.explicit.put({ owner, thread, id: message.id, preserved: true });
|
|
175
|
+
await this.messages.update([owner, thread, message.id], { root: data.rootMessageId, changeSeq: event.inboxSeq.padStart(19, "0") });
|
|
176
|
+
}
|
|
177
|
+
await this.facts.put({ owner, kind: event.kind, id: key, thread, value: data });
|
|
178
|
+
await this.facts.put({ owner, kind: "structure", id: thread, thread, value: { seq: event.inboxSeq } });
|
|
179
|
+
return thread;
|
|
180
|
+
}
|
|
181
|
+
case "relationshipUpdated": {
|
|
182
|
+
if (!data.pairId || ![data.actorId, data.targetId].includes(this.scope.profileId))
|
|
183
|
+
throw new Error("INVALID_INBOX_RELATIONSHIP");
|
|
184
|
+
await this.facts.put({ owner, kind: event.kind, id: data.pairId, thread: data.threadId, value: data });
|
|
185
|
+
return data.threadId;
|
|
186
|
+
}
|
|
187
|
+
default: throw new Error(`UNSUPPORTED_INBOX_EVENT:${event.kind}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async readingSnapshot() {
|
|
191
|
+
return this.db.transaction("r", this.tables(), async () => {
|
|
192
|
+
const cursor = await this.cursor(), owner = this.owner;
|
|
193
|
+
const [threads, rows, positions, explicit, facts] = await Promise.all([this.threads.where("owner").equals(owner).toArray(), this.messages.where("owner").equals(owner).toArray(), this.positions.where("owner").equals(owner).toArray(), this.explicit.where("owner").equals(owner).toArray(), this.facts.where("owner").equals(owner).toArray()]);
|
|
194
|
+
const byThread = new Map(threads.map(thread => [thread.id, { id: thread.id, kind: thread.kind, teamId: thread.teamId, messages: [], readThroughSeq: 0, explicitReadMessageIds: [], preservedReadMessageIds: [], messageThreadReadThrough: {} }]));
|
|
195
|
+
for (const position of positions) {
|
|
196
|
+
const thread = byThread.get(position.thread);
|
|
197
|
+
if (!thread)
|
|
198
|
+
continue;
|
|
199
|
+
if (position.root)
|
|
200
|
+
thread.messageThreadReadThrough[position.root] = position.seq;
|
|
201
|
+
else
|
|
202
|
+
thread.readThroughSeq = position.seq;
|
|
203
|
+
}
|
|
204
|
+
for (const item of explicit) {
|
|
205
|
+
const thread = byThread.get(item.thread);
|
|
206
|
+
if (thread)
|
|
207
|
+
(item.preserved ? thread.preservedReadMessageIds : thread.explicitReadMessageIds).push(item.id);
|
|
208
|
+
}
|
|
209
|
+
for (const fact of facts)
|
|
210
|
+
if (fact.kind === "threadAssigned") {
|
|
211
|
+
const thread = byThread.get(fact.value.sourceThreadId);
|
|
212
|
+
if (thread) {
|
|
213
|
+
thread.conversationId = fact.value.threadId;
|
|
214
|
+
thread.teamId = fact.value.teamId;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const row of rows) {
|
|
218
|
+
if (row.acceptedAt < (cursor?.windowStart ?? 0))
|
|
219
|
+
continue;
|
|
220
|
+
const thread = byThread.get(row.thread);
|
|
221
|
+
if (!thread)
|
|
222
|
+
continue;
|
|
223
|
+
const message = row.value, body = message.body;
|
|
224
|
+
const mentions = body?.content?.mentions ?? body?.content?.content?.mentions ?? [];
|
|
225
|
+
const visible = body?.kind === undefined || ["message", "quote"].includes(body.kind) || body.kind === "contact" && ["friendRequest", "requestFriend"].includes(body.action);
|
|
226
|
+
thread.messages.push({ id: row.id, seq: row.seq, from: message.from, recipients: message.recipients ?? [], threadRootId: row.root || undefined, mentions: [...new Set(Array.isArray(mentions) ? mentions.filter(item => item && typeof item.id === "string" && (this.scope.appId !== "pmate:merry" || !["all", "所有人"].includes(item.name))).map(item => item.id) : [])].sort(), readPolicy: messageRequiresPlayback(message.body) ? "explicit" : "visible", recalled: row.recalled || !visible || body?.kind === "recall" || Boolean(body?.content?.recall), payload: null, readingControl: isReadingControl(message.body, this.scope.appId) });
|
|
227
|
+
}
|
|
228
|
+
for (const thread of byThread.values()) {
|
|
229
|
+
const canonical = thread.conversationId ?? thread.id;
|
|
230
|
+
const controls = facts.filter(fact => fact.kind === "groupControl" && (byThread.get(fact.thread)?.conversationId ?? fact.thread) === canonical).map(fact => ({ ...fact.value, teamId: thread.teamId }));
|
|
231
|
+
const group = thread.kind === "group" ? projectInboxGroup(this.scope.appId, threads.find(row => row.id === thread.id)?.targetId ?? "", thread.teamId, controls) : undefined;
|
|
232
|
+
if (group?.status === "dissolved") {
|
|
233
|
+
thread.messages = [];
|
|
234
|
+
thread.readThroughSeq = 0;
|
|
235
|
+
thread.explicitReadMessageIds = [];
|
|
236
|
+
delete thread.messageThreadReadThrough;
|
|
237
|
+
delete thread.preservedReadMessageIds;
|
|
238
|
+
}
|
|
239
|
+
else
|
|
240
|
+
thread.messages.sort((a, b) => a.seq - b.seq);
|
|
241
|
+
}
|
|
242
|
+
return { schemaVersion: 1, appId: this.scope.appId, profileId: this.scope.profileId, syncCursor: `inbox:${cursor?.epoch ?? "none"}:${cursor?.seq ?? "0"}`, threads: [...byThread.values()] };
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
async threadMessages(thread) { return (await this.messages.where("[owner+thread]").equals([this.owner, thread]).sortBy("seq")).map(row => ({ ...row.value, recalled: row.recalled, body: this.annotatedBody(row) })); }
|
|
246
|
+
async conversationMessages(thread, teamId) {
|
|
247
|
+
const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
|
|
248
|
+
const sources = [thread, ...assignments.map(row => row.value.sourceThreadId)];
|
|
249
|
+
const messages = (await Promise.all(sources.map(source => this.threadMessages(source)))).flatMap(rows => rows.map(row => {
|
|
250
|
+
const assignment = assignments.find(item => item.value.sourceThreadId === row.threadId);
|
|
251
|
+
return assignment ? { ...row, sourceThreadId: row.threadId, threadId: thread, teamId: assignment.value.teamId } : row;
|
|
252
|
+
})).filter(row => row.teamId === teamId);
|
|
253
|
+
return messages.sort((a, b) => a.serverCreatedAt - b.serverCreatedAt || (a.messageId < b.messageId ? -1 : a.messageId > b.messageId ? 1 : 0));
|
|
254
|
+
}
|
|
255
|
+
async conversationChanges(thread, teamId, afterSeq, afterId = "") {
|
|
256
|
+
const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
|
|
257
|
+
const sources = [thread, ...assignments.map(row => row.value.sourceThreadId)];
|
|
258
|
+
const rows = (await Promise.all(sources.map(source => this.messages.where("[owner+thread+changeSeq+id]").between([this.owner, source, afterSeq.padStart(19, "0"), afterId], [this.owner, source, Dexie.maxKey, Dexie.maxKey], false, true).limit(101).toArray()))).flat();
|
|
259
|
+
return rows.filter(row => (assignments.find(item => item.value.sourceThreadId === row.thread)?.value.teamId ?? row.value.teamId) === teamId).sort((a, b) => a.changeSeq.localeCompare(b.changeSeq) || a.id.localeCompare(b.id)).map(row => ({ changeSeq: row.changeSeq, id: row.id }));
|
|
260
|
+
}
|
|
261
|
+
async structureSequence(thread) {
|
|
262
|
+
const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
|
|
263
|
+
const sources = [thread, ...assignments.map(row => row.value.sourceThreadId)];
|
|
264
|
+
const rows = await this.facts.bulkGet(sources.map(source => [this.owner, "structure", source]));
|
|
265
|
+
return rows.reduce((seq, row) => row && inboxSequence(row.value.seq) > seq ? inboxSequence(row.value.seq) : seq, 0n);
|
|
266
|
+
}
|
|
267
|
+
async discussionSummaries(thread, team, roots) {
|
|
268
|
+
return this.db.transaction("r", this.tables(), async () => {
|
|
269
|
+
const snapshot = await this.readingSnapshot(), messages = await this.conversationMessages(thread, team);
|
|
270
|
+
const sources = sourcesInConversation({ ...snapshot, pending: [] }, thread);
|
|
271
|
+
const reading = new Map(sources.flatMap(source => source.messages.map(message => [message.id, { message, source }])));
|
|
272
|
+
const organizations = await this.facts.where("[owner+kind]").equals([this.owner, "threadOrganized"]).toArray();
|
|
273
|
+
const items = [...new Set(roots)].sort().map(root => {
|
|
274
|
+
const original = reading.get(root);
|
|
275
|
+
if (!original || original.message.threadRootId || original.message.readingControl)
|
|
276
|
+
throw new Error("MESSAGE_THREAD_ROOT_NOT_FOUND");
|
|
277
|
+
const replies = messages.filter(message => messageThreadRoot(message.body) === root).filter(message => { const entry = reading.get(message.messageId); return entry && !entry.message.recalled && !entry.message.readingControl; });
|
|
278
|
+
const last = replies.at(-1);
|
|
279
|
+
const unread = replies.filter(message => {
|
|
280
|
+
if (message.from === this.scope.profileId)
|
|
281
|
+
return false;
|
|
282
|
+
const entry = reading.get(message.messageId);
|
|
283
|
+
return !entry.source.preservedReadMessageIds?.includes(message.messageId) && (entry.message.readPolicy === "explicit" ? !entry.source.explicitReadMessageIds.includes(message.messageId) : entry.message.seq > readingCursor(entry.source, root));
|
|
284
|
+
}).length;
|
|
285
|
+
const organization = organizations.find(row => row.value.threadId === thread && row.value.rootMessageId === root);
|
|
286
|
+
return { rootMessageId: root, replyCount: replies.length, unreadCount: unread, lastReplyId: last?.messageId ?? null, lastReplyAt: last?.serverCreatedAt ?? null, participantProfileIds: [...new Set(replies.map(message => message.from))].sort().slice(0, 3), ...(organization ? { ownerAgentId: organization.value.ownerAgentId } : {}) };
|
|
287
|
+
});
|
|
288
|
+
const cursor = await this.cursor();
|
|
289
|
+
return { items, revision: Number(cursor?.seq ?? "0") };
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
async group(groupId, teamId) {
|
|
293
|
+
const assignments = await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray();
|
|
294
|
+
const controls = (await this.facts.where("[owner+kind]").equals([this.owner, "groupControl"]).toArray()).map(row => {
|
|
295
|
+
const assignment = assignments.find(item => item.value.sourceThreadId === row.thread);
|
|
296
|
+
return assignment ? { ...row.value, teamId: assignment.value.teamId } : row.value;
|
|
297
|
+
});
|
|
298
|
+
return projectInboxGroup(this.scope.appId, groupId, teamId, controls);
|
|
299
|
+
}
|
|
300
|
+
annotatedBody(row) {
|
|
301
|
+
if (!row.root)
|
|
302
|
+
return row.value.body;
|
|
303
|
+
const body = row.value.body;
|
|
304
|
+
return { ...body, content: { ...body?.content, threadRootId: row.root } };
|
|
305
|
+
}
|
|
306
|
+
close() { this.db.close(); }
|
|
307
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { InboxClient } from "./inboxClient.js";
|
|
2
|
+
import type { CachedChatMessage } from "./cachedMessage.js";
|
|
3
|
+
import type { MessageTransport } from "./messageClient.js";
|
|
4
|
+
/** Existing message consumers page the local Inbox materialization. No history
|
|
5
|
+
* request or reading snapshot endpoint is used by this transport. */
|
|
6
|
+
export declare function inboxMessageTransport(inbox: InboxClient, team: string, root?: string): MessageTransport<CachedChatMessage>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
2
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
3
|
+
const encode = (cursor) => `ib1:${encodeURIComponent(JSON.stringify(cursor))}`;
|
|
4
|
+
function decode(token) {
|
|
5
|
+
try {
|
|
6
|
+
if (!token.startsWith("ib1:"))
|
|
7
|
+
return;
|
|
8
|
+
const cursor = JSON.parse(decodeURIComponent(token.slice(4)));
|
|
9
|
+
inboxSequence(cursor.seq);
|
|
10
|
+
return cursor;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const cached = (message) => ({ ...message, id: message.messageId, timestamp: message.serverCreatedAt });
|
|
17
|
+
/** Existing message consumers page the local Inbox materialization. No history
|
|
18
|
+
* request or reading snapshot endpoint is used by this transport. */
|
|
19
|
+
export function inboxMessageTransport(inbox, team, root) {
|
|
20
|
+
const db = inbox.store;
|
|
21
|
+
const read = (run) => db.db.transaction("r", [db.cursors, db.messages, db.facts, db.threads], run);
|
|
22
|
+
const rows = async (thread) => {
|
|
23
|
+
const messages = await db.conversationMessages(thread, team);
|
|
24
|
+
const byId = new Map(messages.map(message => [message.messageId, message]));
|
|
25
|
+
return messages.filter(message => {
|
|
26
|
+
const body = message.body, content = body?.content;
|
|
27
|
+
const target = content?.reaction?.messageId ?? content?.recall?.messageId;
|
|
28
|
+
const selected = messageThreadRoot(message.body) ?? (typeof target === "string" ? messageThreadRoot(byId.get(target)?.body) : undefined);
|
|
29
|
+
return selected === root;
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
const metadata = async (thread) => {
|
|
33
|
+
const cursor = await db.cursor();
|
|
34
|
+
if (!cursor)
|
|
35
|
+
throw new Error("INBOX_NOT_INITIALIZED");
|
|
36
|
+
return { epoch: cursor.epoch, thread, team, root, seq: cursor.seq, id: "\uffff" };
|
|
37
|
+
};
|
|
38
|
+
const valid = (cursor, wanted) => cursor && cursor.epoch === wanted.epoch && cursor.thread === wanted.thread && cursor.team === wanted.team && cursor.root === wanted.root;
|
|
39
|
+
const load = (thread, signal) => read(async () => {
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
const current = await metadata(thread), all = await rows(thread), selected = all.slice(-100);
|
|
42
|
+
return { messages: selected.map(cached), checkpoint: encode(current), nextBefore: all.length > selected.length ? encode({ ...current, before: { time: selected[0].serverCreatedAt, id: selected[0].messageId } }) : null, hasMoreChanges: false, resetRequired: false };
|
|
43
|
+
});
|
|
44
|
+
return {
|
|
45
|
+
local: true,
|
|
46
|
+
load,
|
|
47
|
+
changes: (thread, after, signal) => read(async () => {
|
|
48
|
+
signal.throwIfAborted();
|
|
49
|
+
const current = await metadata(thread), cursor = decode(after);
|
|
50
|
+
if (!valid(cursor, current) || await db.structureSequence(thread) > inboxSequence(cursor.seq))
|
|
51
|
+
return { messages: [], checkpoint: encode(current), resetRequired: true };
|
|
52
|
+
const changed = await db.conversationChanges(thread, team, cursor.seq, cursor.id ?? "\uffff");
|
|
53
|
+
const selected = changed.slice(0, 100), hasMore = changed.length > selected.length, all = await rows(thread), byId = new Map(all.map(row => [row.messageId, row]));
|
|
54
|
+
const last = selected.at(-1);
|
|
55
|
+
return { messages: selected.flatMap(item => { const message = byId.get(item.id); return message ? [cached(message)] : []; }), checkpoint: encode(hasMore && last ? { ...current, seq: BigInt(last.changeSeq).toString(), id: last.id } : current), hasMoreChanges: hasMore, resetRequired: false };
|
|
56
|
+
}),
|
|
57
|
+
older: (thread, before, signal) => read(async () => {
|
|
58
|
+
signal.throwIfAborted();
|
|
59
|
+
const current = await metadata(thread), cursor = decode(before);
|
|
60
|
+
if (!valid(cursor, current) || !cursor?.before || await db.structureSequence(thread) > inboxSequence(cursor.seq))
|
|
61
|
+
return { messages: [], checkpoint: encode(current), resetRequired: true };
|
|
62
|
+
const boundary = cursor.before, all = (await rows(thread)).filter(row => row.serverCreatedAt < boundary.time || row.serverCreatedAt === boundary.time && row.messageId < boundary.id);
|
|
63
|
+
const selected = all.slice(-100);
|
|
64
|
+
return { messages: selected.map(cached), checkpoint: encode(current), nextBefore: all.length > selected.length ? encode({ ...current, before: { time: selected[0].serverCreatedAt, id: selected[0].messageId } }) : null, hasMoreChanges: false, resetRequired: false };
|
|
65
|
+
}),
|
|
66
|
+
};
|
|
67
|
+
}
|
package/lib/runtime/index.d.ts
CHANGED
|
@@ -37,3 +37,5 @@ export * from "./outgoingContent.js";
|
|
|
37
37
|
export type { ChatGroup } from "./groupClient.js";
|
|
38
38
|
export type { ConversationTarget } from "./conversationDirectory.js";
|
|
39
39
|
export * from "./messageThread.js";
|
|
40
|
+
export * from "./inboxStore.js";
|
|
41
|
+
export * from "./inboxClient.js";
|
package/lib/runtime/index.js
CHANGED
|
@@ -7,6 +7,8 @@ export type MessagePage<T> = {
|
|
|
7
7
|
resetRequired?: boolean;
|
|
8
8
|
};
|
|
9
9
|
export type MessageTransport<T> = {
|
|
10
|
+
/** A durable local source can fill windows while the network is unavailable. */
|
|
11
|
+
local?: boolean;
|
|
10
12
|
/** Optional team-scoped authorization for fresh instances recovering a revoked cache. */
|
|
11
13
|
authorizeScope?: (signal: AbortSignal) => Promise<void>;
|
|
12
14
|
/** Authoritative history. Must include control state needed to merge old rows. */
|
|
@@ -189,8 +189,8 @@ export class MessageClient {
|
|
|
189
189
|
this.denyScope();
|
|
190
190
|
throw new Error("MESSAGE_SCOPE_CHANGED");
|
|
191
191
|
}
|
|
192
|
-
if (refresh || !local.coverage?.complete || local.coverage.revoked || this.revoked.has(thread)) {
|
|
193
|
-
if (typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
192
|
+
if (refresh || this.options.transport.local || !local.coverage?.complete || local.coverage.revoked || this.revoked.has(thread)) {
|
|
193
|
+
if (!this.options.transport.local && typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
194
194
|
if (!refresh && !local.coverage?.revoked) {
|
|
195
195
|
const fallback = await this.fallback(thread, limit);
|
|
196
196
|
if (fallback.messages.length)
|
|
@@ -483,7 +483,7 @@ export class MessageClient {
|
|
|
483
483
|
assertNetworkAvailable(thread) {
|
|
484
484
|
if (this.closed || this.closing || this.scopeDenied || this.revoked.has(thread))
|
|
485
485
|
throw new Error("MESSAGE_CLIENT_UNAVAILABLE");
|
|
486
|
-
if (isOffline())
|
|
486
|
+
if (!this.options.transport.local && isOffline())
|
|
487
487
|
throw new TypeError("MESSAGE_OFFLINE_UNAVAILABLE");
|
|
488
488
|
}
|
|
489
489
|
synchronize(thread) {
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
|
|
2
|
+
import type { InboxClient } from "./inboxClient.js";
|
|
2
3
|
export type ReadSyncOptions = {
|
|
4
|
+
inbox?: InboxClient;
|
|
3
5
|
appId: string;
|
|
4
6
|
profileId: string;
|
|
5
7
|
sessionToken: string;
|
|
@@ -15,9 +17,13 @@ export declare class ReadSyncClient {
|
|
|
15
17
|
private readonly controller;
|
|
16
18
|
private inFlight?;
|
|
17
19
|
private readAfter;
|
|
20
|
+
private inboxApplying?;
|
|
21
|
+
private inboxDirty;
|
|
18
22
|
constructor(options: ReadSyncOptions);
|
|
19
23
|
loadLocal(): Promise<ReadIndexState>;
|
|
20
24
|
stop(): void;
|
|
25
|
+
applyInboxLocal(): Promise<ReadIndexState>;
|
|
26
|
+
private installInboxLocal;
|
|
21
27
|
synchronize(): Promise<ReadIndexState>;
|
|
22
28
|
private request;
|
|
23
29
|
private repairLegacyDiscussion;
|