@pmate/chat-sdk 0.13.0-profile.0 → 0.13.0-profile.10

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.
Files changed (37) hide show
  1. package/README.md +26 -0
  2. package/lib/profile.d.ts +5 -2
  3. package/lib/profile.js +5 -2
  4. package/lib/runtime/profileChat.d.ts +121 -1
  5. package/lib/runtime/profileChat.js +126 -33
  6. package/lib/runtime/profileCommitQueue.d.ts +2 -1
  7. package/lib/runtime/profileCommitQueue.js +26 -7
  8. package/lib/runtime/profileCoordinator.d.ts +19 -19
  9. package/lib/runtime/profileCoordinator.js +127 -94
  10. package/lib/runtime/profileDatabase.d.ts +7 -7
  11. package/lib/runtime/profileDatabase.js +57 -42
  12. package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
  13. package/lib/runtime/profileGenerationBuilder.js +60 -26
  14. package/lib/runtime/profileInboxFeed.d.ts +1 -0
  15. package/lib/runtime/profileInboxFeed.js +12 -2
  16. package/lib/runtime/profileLegacyInbox.d.ts +8 -0
  17. package/lib/runtime/profileLegacyInbox.js +114 -0
  18. package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
  19. package/lib/runtime/profileLegacyOutbox.js +106 -0
  20. package/lib/runtime/profileLegacyReading.d.ts +7 -0
  21. package/lib/runtime/profileLegacyReading.js +110 -0
  22. package/lib/runtime/profileMemoryStore.d.ts +24 -2
  23. package/lib/runtime/profileMemoryStore.js +146 -12
  24. package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
  25. package/lib/runtime/profileOutboxDispatcher.js +41 -5
  26. package/lib/runtime/profileOwner.d.ts +11 -6
  27. package/lib/runtime/profileOwner.js +71 -46
  28. package/lib/runtime/profileProjection.d.ts +54 -5
  29. package/lib/runtime/profileProjection.js +336 -51
  30. package/lib/runtime/profileReadingIndex.d.ts +1 -0
  31. package/lib/runtime/profileReadingIndex.js +17 -1
  32. package/lib/runtime/profileStoreTypes.d.ts +15 -9
  33. package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
  34. package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +55 -102
  35. package/lib/runtime/profileWorkerHost.d.ts +4 -6
  36. package/lib/runtime/profileWorkerHost.js +58 -21
  37. package/package.json +2 -2
@@ -1,22 +1,19 @@
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. */
7
7
  export class ProfileGenerationBuilder {
8
8
  database;
9
- lease;
10
9
  cache = new Map();
11
- constructor(database, lease) {
10
+ constructor(database) {
12
11
  this.database = database;
13
- this.lease = lease;
14
12
  }
15
13
  async persist(build, projection, events) {
16
14
  const prepared = projection.prepare(events);
17
15
  const next = { ...build, committedSeq: prepared.current.committedSeq, buildRevision: prepared.current.commitRevision, receiptsReady: prepared.current.receiptsReady };
18
- const lease = this.lease();
19
- await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
16
+ await this.database.saveGeneration(next, prepared);
20
17
  projection.accept(prepared);
21
18
  this.cache.set(build.generation, { build: next, projection });
22
19
  return { build: next, projection };
@@ -41,18 +38,20 @@ export class ProfileGenerationBuilder {
41
38
  throw Error("INVALID_INBOX_BOOTSTRAP");
42
39
  const saved = await this.database.restoreGeneration(generation);
43
40
  if (saved.build) {
41
+ if (saved.build.projectionVersion !== PROFILE_PROJECTION_VERSION)
42
+ throw Error("PROFILE_BUILD_INCOMPATIBLE");
44
43
  if (saved.build.epoch !== bootstrap.epoch || saved.build.throughSeq !== bootstrap.headSeq || saved.build.windowStart !== bootstrap.windowStart)
45
44
  throw Error("PROFILE_BUILD_ID_COLLISION");
46
45
  return;
47
46
  }
48
47
  const build = { key: `build:${generation}`, generation, epoch: bootstrap.epoch,
49
- committedSeq: (start - 1n).toString(), projectionVersion: 1, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
48
+ committedSeq: (start - 1n).toString(), projectionVersion: PROFILE_PROJECTION_VERSION, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
50
49
  windowStart: bootstrap.windowStart, buildRevision: 0 };
51
50
  const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
52
- epoch: build.epoch, committedSeq: build.committedSeq, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
53
- const prepared = projection.prepareBasis(bootstrap), lease = this.lease();
51
+ epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: PROFILE_PROJECTION_VERSION, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
52
+ const prepared = projection.prepareBasis(bootstrap);
54
53
  const next = { ...build, buildRevision: prepared.current.commitRevision };
55
- await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
54
+ await this.database.saveGeneration(next, prepared);
56
55
  projection.accept(prepared);
57
56
  this.cache.set(generation, { build: next, projection });
58
57
  }
@@ -68,43 +67,78 @@ export class ProfileGenerationBuilder {
68
67
  if (inboxSequence(build.committedSeq) < inboxSequence(build.throughSeq ?? "0"))
69
68
  throw Error("PROFILE_BUILD_INCOMPLETE");
70
69
  const operations = [];
70
+ const registered = new Set();
71
71
  // Keep locally accepted work that arrived while the replacement was built.
72
72
  // Already-replayed server messages win by their stable message identity.
73
73
  for (const message of active.messages.values()) {
74
74
  if (message.sourceSeq || projection.messages.has(message.messageId))
75
75
  continue;
76
- const thread = projection.threads.get(message.threadId);
76
+ const thread = projection.threads.get(message.threadId) ?? active.threads.get(message.threadId);
77
77
  if (thread?.status !== "ready")
78
78
  continue;
79
+ const parent = thread.parentThreadId ? active.threads.get(thread.parentThreadId) : thread;
80
+ if (!parent || parent.status !== "ready")
81
+ continue;
82
+ if (!projection.threads.has(parent.threadId) && !registered.has(parent.threadId)) {
83
+ if (!parent.teamId || !parent.internal?.targetId)
84
+ continue;
85
+ operations.push({ type: "register", threadId: parent.threadId, kind: parent.kind === "dm" ? "dm" : "group",
86
+ targetId: parent.internal.targetId, teamId: parent.teamId, title: parent.title });
87
+ registered.add(parent.threadId);
88
+ }
79
89
  const pending = active.outbox.get(message.messageId);
80
90
  const pendingPayload = pending?.payload;
81
91
  const wire = pendingPayload?.message ?? pending?.payload ?? { hash: message.messageId, t: message.orderKey[0],
82
92
  from: message.from, to: thread.internal?.targetId ?? "", opcode: 1, kind: 1, body: message.content, recipients: message.recipients };
83
93
  const command = pending ?? { commandId: message.messageId, messageId: message.messageId, kind: "message",
84
94
  threadId: message.threadId, createdAt: wire.t, payload: wire, state: "pending", attempts: 0 };
85
- operations.push({ type: "send", threadId: message.threadId, message: wire, command });
95
+ operations.push({ type: "send", threadId: message.threadId, parentThreadId: thread.parentThreadId, message: wire, command, preserveWire: true });
86
96
  if (!pending)
87
97
  operations.push({ type: "commandResult", commandId: message.messageId, state: "confirmed" });
88
98
  }
89
99
  for (const thread of active.threads.values()) {
90
- if (!projection.threads.has(thread.threadId))
91
- continue;
92
- for (const source of thread.readingSources) {
93
- if (!source.pendingReadThroughSeq && !source.pendingExplicitReadMessageIds?.length)
94
- continue;
95
- operations.push({ type: "restoreReading", data: { appId: this.database.identity.appId, profileId: this.database.identity.profileId,
96
- threadId: source.sourceThreadId, threadRootId: thread.rootMessageId,
97
- readThroughSeq: source.pendingReadThroughSeq ?? 0, explicitReadMessageIds: source.pendingExplicitReadMessageIds ?? [] } });
100
+ for (const [messageId, intents] of Object.entries(thread.internal?.pendingReadingIntents ?? {})) {
101
+ for (const intent of intents)
102
+ operations.push({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent, defer: true });
98
103
  }
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 });
115
+ }
116
+ for (const command of active.outbox.values())
117
+ if (command.kind !== "message")
118
+ operations.push({ type: "restoreReadingCommand", command });
119
+ let batch = [], bytes = 0;
120
+ const flush = async () => {
121
+ if (!batch.length)
122
+ return;
123
+ const saved = await this.persist(build, projection, batch);
124
+ build = saved.build;
125
+ projection = saved.projection;
126
+ batch = [];
127
+ bytes = 0;
128
+ };
129
+ for (const operation of operations) {
130
+ const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
131
+ if (batch.length && (batch.length >= 200 || bytes + size > 512 * 1024))
132
+ await flush();
133
+ batch.push(operation);
134
+ bytes += size;
99
135
  }
100
- if (operations.length)
101
- ({ build, projection } = await this.persist(build, projection, operations));
136
+ await flush();
102
137
  const snapshot = projection.snapshot();
103
138
  new ProfileMemoryStore().restore(snapshot);
104
- const lease = this.lease();
105
139
  const validated = { ...build, status: "validated", sourceRevision: active.current.commitRevision };
106
- await this.database.saveGeneration(lease.ownerId, lease.fence, validated, {});
107
- const current = await this.database.activateGeneration(lease.ownerId, lease.fence, generation, active.current.commitRevision);
140
+ await this.database.saveGeneration(validated, {});
141
+ const current = await this.database.activateGeneration(generation, active.current.commitRevision);
108
142
  const result = new ProfileProjection(this.database.identity, { ...snapshot, current, outbox: [...active.outbox.values()] }, build.windowStart ?? 0);
109
143
  this.cache.delete(generation);
110
144
  return result;
@@ -8,6 +8,7 @@ export type ProfileInboxFeedOptions = {
8
8
  onError?: (error: unknown) => void;
9
9
  onProgress?: (progress: InboxProgress) => void;
10
10
  live?: boolean;
11
+ prepare?: () => Promise<unknown>;
11
12
  };
12
13
  /** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
13
14
  * backpressured by durable owner commits; long requests never hold its queue. */
@@ -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. */
@@ -27,6 +28,8 @@ export class ProfileInboxFeed {
27
28
  catch { }
28
29
  }
29
30
  async request(action, params = {}) {
31
+ if (!this.options.owner.active)
32
+ throw Error("PROFILE_OWNER_UNAVAILABLE");
30
33
  const identity = this.options.owner.identity;
31
34
  const query = new URLSearchParams({ appId: identity.appId, profileId: identity.profileId, ...params });
32
35
  const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, {
@@ -46,6 +49,8 @@ export class ProfileInboxFeed {
46
49
  synchronize() {
47
50
  if (this.closed)
48
51
  return Promise.reject(Error("INBOX_CLIENT_CLOSED"));
52
+ if (!this.options.owner.active)
53
+ return Promise.reject(Error("PROFILE_OWNER_UNAVAILABLE"));
49
54
  if (this.running)
50
55
  return this.running;
51
56
  const task = this.catchUp().catch(error => { this.progress("error"); throw error; });
@@ -110,7 +115,7 @@ export class ProfileInboxFeed {
110
115
  }
111
116
  async rebuild() {
112
117
  const bootstrap = await this.request("bootstrap");
113
- 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);
114
119
  const generation = pending?.generation ?? await this.options.owner.beginGeneration(bootstrap);
115
120
  const build = await this.options.owner.generationProgress(generation);
116
121
  this.building = { generation, epoch: build.epoch, target: build.throughSeq ?? bootstrap.headSeq };
@@ -139,9 +144,10 @@ export class ProfileInboxFeed {
139
144
  this.building = undefined;
140
145
  }
141
146
  async catchUp() {
147
+ await this.options.prepare?.();
142
148
  if (this.building)
143
149
  await this.resumeBuild();
144
- if (this.options.owner.current.epoch === "uninitialized")
150
+ if (this.options.owner.current.epoch === "uninitialized" || this.options.owner.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
145
151
  await this.rebuild();
146
152
  let current = this.options.owner.current;
147
153
  let page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
@@ -172,6 +178,10 @@ export class ProfileInboxFeed {
172
178
  async tick() {
173
179
  if (this.closed)
174
180
  return;
181
+ if (!this.options.owner.active) {
182
+ this.streamController?.abort();
183
+ return;
184
+ }
175
185
  await this.synchronize();
176
186
  if (this.options.live === false || this.liveTask)
177
187
  return;
@@ -0,0 +1,8 @@
1
+ import type { ProfileOwner } from "./profileOwner.js";
2
+ export declare function openLegacyDatabase(factory: IDBFactory, name: string): Promise<IDBDatabase | undefined>;
3
+ /** One-time materialization migration. Source data is read consistently and
4
+ * retained; the old cursor becomes active only with the complete new view. */
5
+ export declare function migrateLegacyInbox(owner: ProfileOwner, options?: {
6
+ indexedDB?: IDBFactory;
7
+ name?: string;
8
+ }): Promise<boolean>;
@@ -0,0 +1,114 @@
1
+ import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
2
+ import { inboxSequence } from "./inboxStore.js";
3
+ export async function openLegacyDatabase(factory, name) {
4
+ return new Promise((resolve, reject) => {
5
+ let fresh = false;
6
+ const request = factory.open(name);
7
+ request.onupgradeneeded = event => {
8
+ if (event.oldVersion === 0) {
9
+ fresh = true;
10
+ request.transaction.abort();
11
+ }
12
+ };
13
+ request.onerror = event => { event.preventDefault(); fresh ? resolve(undefined) : reject(request.error); };
14
+ request.onsuccess = () => resolve(request.result);
15
+ });
16
+ }
17
+ async function capture(database, owner) {
18
+ const names = ["cursors", "messages", "facts", "positions", "explicit", "receipts", "projections"].filter(name => database.objectStoreNames.contains(name));
19
+ if (!names.includes("cursors"))
20
+ return { messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [] };
21
+ return new Promise((resolve, reject) => {
22
+ const transaction = database.transaction(names, "readonly");
23
+ const result = {};
24
+ transaction.oncomplete = () => resolve({ messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [], ...result });
25
+ transaction.onerror = () => reject(transaction.error);
26
+ transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_INBOX_CAPTURE_ABORTED"));
27
+ for (const name of names) {
28
+ const store = transaction.objectStore(name);
29
+ const request = name === "cursors" ? store.get(owner) : store.index("owner").getAll(IDBKeyRange.only(owner));
30
+ request.onsuccess = () => { result[name === "cursors" ? "cursor" : name] = request.result; };
31
+ }
32
+ });
33
+ }
34
+ /** One-time materialization migration. Source data is read consistently and
35
+ * retained; the old cursor becomes active only with the complete new view. */
36
+ export async function migrateLegacyInbox(owner, options = {}) {
37
+ if (owner.current.epoch !== "uninitialized")
38
+ return false;
39
+ const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-chat-inbox-v1");
40
+ if (!database)
41
+ return false;
42
+ const identity = owner.identity, key = JSON.stringify([identity.accountId, identity.appId, identity.profileId]);
43
+ let rows;
44
+ try {
45
+ rows = await capture(database, key);
46
+ }
47
+ finally {
48
+ database.close();
49
+ }
50
+ const cursor = rows.cursor;
51
+ if (!cursor?.initialized || !cursor.epoch)
52
+ return false;
53
+ const seq = inboxSequence(cursor.seq);
54
+ const generation = `legacy-inbox:v${PROFILE_PROJECTION_VERSION}:${JSON.stringify([cursor.epoch, cursor.seq])}`;
55
+ await owner.beginGeneration({ ...identity, epoch: cursor.epoch, startSeq: (seq + 1n).toString(), headSeq: cursor.seq,
56
+ windowStart: cursor.windowStart, basis: [] }, generation);
57
+ if ((await owner.generationProgress(generation)).status === "validated") {
58
+ await owner.activateGeneration(generation);
59
+ return true;
60
+ }
61
+ let pending = [], bytes = 0;
62
+ const flush = async () => { if (pending.length) {
63
+ await owner.appendGeneration(generation, pending);
64
+ pending = [];
65
+ bytes = 0;
66
+ } };
67
+ const push = async (operation) => {
68
+ const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
69
+ if (pending.length && (pending.length >= 200 || bytes + size > 512 * 1024))
70
+ await flush();
71
+ pending.push(operation);
72
+ bytes += size;
73
+ };
74
+ const restore = (kind, fact, sourceId, acceptedAt = cursor.windowStart) => ({ type: "restoreEvent", event: { inboxSeq: "0", sourceId, acceptedAt, kind, fact: { appId: identity.appId, ...fact } } });
75
+ // Set readiness before importing messages: each new own message receives its
76
+ // already-known receipt status without a final whole-history rewrite.
77
+ const receiptsReady = rows.projections.some(row => row.name === "receipts" && row.epoch === cursor.epoch && row.status === "ready" && inboxSequence(row.appliedInboxSeq) >= seq);
78
+ if (receiptsReady)
79
+ await push({ type: "receiptsReady" });
80
+ for (const row of rows.facts)
81
+ if (row.kind === "groupControl")
82
+ await push(restore("messageAdded", row.value, row.id));
83
+ rows.messages.sort((a, b) => a.value.serverCreatedAt - b.value.serverCreatedAt || a.value.threadId.localeCompare(b.value.threadId) || (a.value.seq ?? 0) - (b.value.seq ?? 0) || a.id.localeCompare(b.id));
84
+ for (const row of rows.messages) {
85
+ if (!row.value.seq) {
86
+ const body = row.value.body;
87
+ if (body?.kind === "contact" && body.action === "friendRequest")
88
+ await push({ type: "restoreInvitation", message: row.value, acceptedAt: row.acceptedAt, recalled: row.recalled });
89
+ continue;
90
+ }
91
+ const body = row.value.body;
92
+ const value = row.root ? { ...row.value, body: { ...body, content: { ...body?.content, threadRootId: row.root } } } : row.value;
93
+ await push({ ...restore("messageAdded", { ...value, sourceAcceptedAt: row.acceptedAt }, row.id, row.acceptedAt), recalled: row.recalled });
94
+ }
95
+ for (const row of rows.positions)
96
+ await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread,
97
+ ...(row.root ? { threadRootId: row.root } : {}), readThroughSeq: row.seq, readThroughMessageId: row.messageId, explicitReadMessageIds: [] }, `position:${row.thread}:${row.root}`));
98
+ const roots = new Map(rows.messages.map(row => [JSON.stringify([row.value.threadId, row.id]), row.root]));
99
+ for (const row of rows.explicit) {
100
+ const root = roots.get(JSON.stringify([row.thread, row.id]));
101
+ await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread, ...(root ? { threadRootId: root } : {}),
102
+ readThroughSeq: 0, explicitReadMessageIds: [row.id] }, `explicit:${row.id}`));
103
+ }
104
+ for (const row of rows.facts)
105
+ if (["threadOrganized", "threadAssigned", "relationshipUpdated"].includes(row.kind))
106
+ await push(restore(row.kind, row.value, row.id));
107
+ for (const row of rows.receipts)
108
+ await push({ type: "restoreReceipt", data: { appId: identity.appId, profileId: identity.profileId,
109
+ threadId: row.thread, readThroughSeq: 0, explicitReadMessageIds: [], receipt: { version: 1, authorProfileId: identity.profileId,
110
+ readerProfileId: row.readerId, threadId: row.thread, messageIds: [row.messageId], sourceId: `legacy-receipt:${row.messageId}:${row.readerId}`, sourceAcceptedAt: 0 } } });
111
+ await flush();
112
+ await owner.activateGeneration(generation);
113
+ return true;
114
+ }
@@ -0,0 +1,7 @@
1
+ import type { ProfileOwner } from "./profileOwner.js";
2
+ /** Imports exact durable wires; no sender or legacy database upgrade is opened.
3
+ * The completion marker is committed after every admitted command is durable. */
4
+ export declare function migrateLegacyOutbox(owner: ProfileOwner, options?: {
5
+ indexedDB?: IDBFactory;
6
+ name?: string;
7
+ }): Promise<boolean>;
@@ -0,0 +1,106 @@
1
+ import { openLegacyDatabase } from "./profileLegacyInbox.js";
2
+ import { profileDiscussionId } from "./profileProjection.js";
3
+ import { messageThreadRoot } from "./messageThread.js";
4
+ import { dmThreadId, groupThreadId } from "./thread.js";
5
+ const migration = "legacy-outbox-v1";
6
+ async function capture(database, prefix) {
7
+ const messages = database.objectStoreNames.contains("outgoingMessages") ? "outgoingMessages" : "outbox";
8
+ if (!database.objectStoreNames.contains(messages))
9
+ return { messages: [], attachments: [], epochs: [] };
10
+ const names = [messages, "outgoingAttachments", "scopeEpochs"].filter(name => database.objectStoreNames.contains(name));
11
+ return new Promise((resolve, reject) => {
12
+ const transaction = database.transaction(names, "readonly"), range = IDBKeyRange.bound(prefix, `${prefix}\uffff`);
13
+ const result = { messages: [], attachments: [], epochs: [] };
14
+ transaction.oncomplete = () => resolve(result);
15
+ transaction.onerror = () => reject(transaction.error);
16
+ transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_OUTBOX_CAPTURE_ABORTED"));
17
+ for (const name of names) {
18
+ const store = transaction.objectStore(name);
19
+ if (name !== "scopeEpochs" && !store.indexNames.contains("scope")) {
20
+ transaction.abort();
21
+ return;
22
+ }
23
+ const request = (name === "scopeEpochs" ? store : store.index("scope")).getAll(range);
24
+ request.onsuccess = () => {
25
+ if (name === messages)
26
+ result.messages = request.result;
27
+ else if (name === "scopeEpochs")
28
+ result.epochs = request.result;
29
+ else
30
+ result.attachments = request.result;
31
+ };
32
+ }
33
+ });
34
+ }
35
+ /** Imports exact durable wires; no sender or legacy database upgrade is opened.
36
+ * The completion marker is committed after every admitted command is durable. */
37
+ export async function migrateLegacyOutbox(owner, options = {}) {
38
+ if (owner.current.localMigrations?.includes(migration))
39
+ return false;
40
+ const identity = owner.identity;
41
+ const prefix = `${JSON.stringify([identity.appId, identity.accountId, identity.profileId]).slice(0, -1)},`;
42
+ const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-chat-outbox");
43
+ let rows = { messages: [], attachments: [], epochs: [] };
44
+ if (database) {
45
+ try {
46
+ rows = await capture(database, prefix);
47
+ }
48
+ finally {
49
+ database.close();
50
+ }
51
+ }
52
+ const epochs = new Map(rows.epochs.map(row => [row.scope, row.version]));
53
+ const attachments = new Map(rows.attachments.map(row => [JSON.stringify([row.scope, row.hash]), row]));
54
+ const operations = [];
55
+ const add = (operation, bytes = 0) => operations.push({ operation, bytes: bytes + new TextEncoder().encode(JSON.stringify(operation)).byteLength });
56
+ for (const row of rows.messages) {
57
+ if (row.confirmed || (row.accessVersion ?? 0) !== (epochs.get(row.scope) ?? 0))
58
+ continue;
59
+ const scope = JSON.parse(row.scope);
60
+ if (scope.length !== 4 || scope[0] !== identity.appId || scope[1] !== identity.accountId || scope[2] !== identity.profileId || typeof scope[3] !== "string" || !scope[3])
61
+ throw Error("LEGACY_OUTBOX_SCOPE_MISMATCH");
62
+ const teamId = scope[3], wire = row.message;
63
+ if (!wire || wire.hash !== row.hash || wire.from !== identity.profileId || !wire.to || !Number.isSafeInteger(wire.t))
64
+ throw Error("LEGACY_OUTBOX_MESSAGE_MISMATCH");
65
+ const body = wire.body;
66
+ const content = body.content ?? body.payload;
67
+ if (content?.appId !== identity.appId || content.teamId !== teamId)
68
+ throw Error("LEGACY_OUTBOX_SCOPE_MISMATCH");
69
+ const kind = body.threadKind === "group" || body.kind === "group" || body.content?.groupId ? "group" : "dm";
70
+ const parent = kind === "group" ? groupThreadId(identity.appId, wire.to, teamId) : dmThreadId(identity.appId, identity.profileId, wire.to, teamId);
71
+ if (row.threadId !== parent)
72
+ throw Error("LEGACY_OUTBOX_THREAD_MISMATCH");
73
+ if (owner.memory.getThread(parent)?.status === "unavailable")
74
+ continue;
75
+ const root = messageThreadRoot(wire.body), threadId = root ? profileDiscussionId(parent, root) : parent;
76
+ let voiceBlob = row.voiceBlob ?? (row.voiceData ? new Blob([row.voiceData.bytes], { type: row.voiceData.type }) : undefined);
77
+ if (row.voiceAttachment) {
78
+ const attachment = attachments.get(JSON.stringify([row.scope, row.hash]));
79
+ if (!attachment || attachment.accessVersion !== (row.accessVersion ?? 0) || attachment.size !== row.voiceAttachment.size || attachment.type !== row.voiceAttachment.type ||
80
+ (attachment.bytes?.byteLength ?? attachment.blob?.size) !== attachment.size)
81
+ throw Error("LEGACY_VOICE_ATTACHMENT_UNAVAILABLE");
82
+ voiceBlob = attachment.blob ?? new Blob([attachment.bytes], { type: attachment.type });
83
+ }
84
+ add({ type: "register", threadId: parent, kind, targetId: wire.to, teamId });
85
+ add({ type: "send", threadId, ...(root ? { parentThreadId: parent } : {}), message: wire, preserveWire: true,
86
+ command: { commandId: row.hash, messageId: row.hash, kind: "message", threadId, createdAt: wire.t,
87
+ payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: row.status === "failed" ? "failed" : "pending", attempts: 0 } }, voiceBlob?.size);
88
+ }
89
+ // Await bounded groups so a large old queue cannot bypass owner backpressure.
90
+ let pending = [], bytes = 0;
91
+ const flush = async () => { if (pending.length) {
92
+ owner.flush();
93
+ await Promise.all(pending);
94
+ pending = [];
95
+ bytes = 0;
96
+ } };
97
+ for (const item of operations) {
98
+ if (pending.length && (pending.length >= 200 || bytes + item.bytes > 512 * 1024))
99
+ await flush();
100
+ pending.push(owner.enqueue(item.operation, item.bytes));
101
+ bytes += item.bytes;
102
+ }
103
+ await flush();
104
+ await owner.enqueue({ type: "migrationCompleted", id: migration }, 100, true);
105
+ return rows.messages.length > 0;
106
+ }
@@ -0,0 +1,7 @@
1
+ import type { ProfileOwner } from "./profileOwner.js";
2
+ /** Pending operations preserve their server idempotency keys. Unresolved
3
+ * observations remain durable Thread facts until a source message arrives. */
4
+ export declare function migrateLegacyReading(owner: ProfileOwner, options?: {
5
+ indexedDB?: IDBFactory;
6
+ name?: string;
7
+ }): Promise<boolean>;
@@ -0,0 +1,110 @@
1
+ import { openLegacyDatabase } from "./profileLegacyInbox.js";
2
+ const migration = "legacy-reading-v1";
3
+ async function capture(database, appId, profileId, accountId) {
4
+ const name = database.objectStoreNames.contains("readingProfiles") ? "readingProfiles" : "profiles";
5
+ if (!database.objectStoreNames.contains(name))
6
+ return;
7
+ const names = [name, ...(database.objectStoreNames.contains("readBatches") ? ["readBatches"] : [])];
8
+ return new Promise((resolve, reject) => {
9
+ const transaction = database.transaction(names, "readonly"), store = transaction.objectStore(name);
10
+ let state;
11
+ transaction.oncomplete = () => resolve(state);
12
+ transaction.onerror = () => reject(transaction.error);
13
+ transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_READING_CAPTURE_ABORTED"));
14
+ const storageScope = JSON.stringify([accountId]), key = [appId, profileId, storageScope];
15
+ const accept = (value, sourceKey) => {
16
+ state = value;
17
+ if (!value || !names.includes("readBatches"))
18
+ return;
19
+ const owner = JSON.stringify(sourceKey), journal = transaction.objectStore("readBatches");
20
+ const active = journal.get([owner, "active"]);
21
+ active.onsuccess = () => {
22
+ if (!active.result?.active)
23
+ return;
24
+ const progress = active.result.active;
25
+ if (typeof progress.id !== "string" || !Number.isSafeInteger(progress.total) || progress.total < 1 || !Number.isSafeInteger(progress.next) || progress.next < 0 || progress.next > progress.total) {
26
+ transaction.abort();
27
+ return;
28
+ }
29
+ const plan = journal.get([owner, `${progress.id}:plan`]);
30
+ plan.onsuccess = () => {
31
+ if (!plan.result?.plan?.header || JSON.stringify(plan.result.plan.profileKey) !== JSON.stringify(sourceKey)) {
32
+ transaction.abort();
33
+ return;
34
+ }
35
+ state = plan.result.plan.header;
36
+ };
37
+ };
38
+ };
39
+ const scoped = store.get(key);
40
+ scoped.onsuccess = () => {
41
+ if (scoped.result) {
42
+ accept(scoped.result, key);
43
+ return;
44
+ }
45
+ const marker = store.get([appId, profileId, "legacy-owner-v1"]);
46
+ marker.onsuccess = () => {
47
+ // An unscoped legacy record is usable only with its existing account claim.
48
+ if (marker.result?.legacyOwner !== storageScope)
49
+ return;
50
+ const legacy = store.get([appId, profileId]);
51
+ legacy.onsuccess = () => accept(legacy.result, [appId, profileId]);
52
+ };
53
+ };
54
+ });
55
+ }
56
+ /** Pending operations preserve their server idempotency keys. Unresolved
57
+ * observations remain durable Thread facts until a source message arrives. */
58
+ export async function migrateLegacyReading(owner, options = {}) {
59
+ if (owner.current.localMigrations?.includes(migration))
60
+ return false;
61
+ const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-social-read-index");
62
+ let state;
63
+ if (database) {
64
+ try {
65
+ state = await capture(database, owner.identity.appId, owner.identity.profileId, owner.identity.accountId);
66
+ }
67
+ finally {
68
+ database.close();
69
+ }
70
+ }
71
+ const operations = [];
72
+ if (state) {
73
+ if (state.schemaVersion !== 1 || state.appId !== owner.identity.appId || state.profileId !== owner.identity.profileId || !Array.isArray(state.pending))
74
+ throw Error("LEGACY_READING_IDENTITY_MISMATCH");
75
+ for (const operation of state.pending) {
76
+ if (!operation.operationId || !operation.threadId || !Number.isSafeInteger(operation.readThroughSeq) || operation.readThroughSeq < 0 ||
77
+ !Array.isArray(operation.explicitReadMessageIds) || operation.explicitReadMessageIds.some(id => typeof id !== "string" || !id))
78
+ throw Error("INVALID_LEGACY_READING_COMMAND");
79
+ if (owner.memory.getThread(operation.threadId)?.status === "unavailable")
80
+ continue;
81
+ operations.push({ type: "restoreReadingCommand", command: { commandId: operation.operationId, kind: operation.explicitReadMessageIds.length ? "played" : "reading",
82
+ threadId: operation.threadId, createdAt: Date.now(), payload: { ...operation, appId: owner.identity.appId, profileId: owner.identity.profileId }, state: "pending", attempts: 0 } });
83
+ }
84
+ for (const intent of state.observedReadIntents ?? []) {
85
+ if (!intent.operationId || !intent.threadId || !intent.messageId || !["visible", "explicit"].includes(intent.readPolicy))
86
+ throw Error("INVALID_LEGACY_READING_INTENT");
87
+ if (owner.memory.getThread(intent.threadId)?.status === "unavailable")
88
+ continue;
89
+ operations.push({ type: "restoreReadingIntent", threadId: intent.threadId, messageId: intent.messageId, commandId: intent.operationId,
90
+ policy: intent.readPolicy === "explicit" ? "played" : "visible", createdAt: Date.now() });
91
+ }
92
+ }
93
+ let pending = [], bytes = 0;
94
+ const flush = async () => { if (pending.length) {
95
+ owner.flush();
96
+ await Promise.all(pending);
97
+ pending = [];
98
+ bytes = 0;
99
+ } };
100
+ for (const operation of operations) {
101
+ const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
102
+ if (pending.length && (pending.length >= 200 || bytes + size > 512 * 1024))
103
+ await flush();
104
+ pending.push(owner.enqueue(operation, size));
105
+ bytes += size;
106
+ }
107
+ await flush();
108
+ await owner.enqueue({ type: "migrationCompleted", id: migration }, 100, true);
109
+ return Boolean(state);
110
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ProfileCurrentState, ProfileMessage, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
2
2
  import type { ChatMessage } from "../chatTypes.js";
3
- export declare const PROFILE_PROTOCOL_VERSION = 1;
4
- export declare const PROFILE_PROJECTION_VERSION = 1;
3
+ export declare const PROFILE_PROTOCOL_VERSION = 2;
4
+ export declare const PROFILE_PROJECTION_VERSION = 2;
5
5
  export type ProfileSnapshot = {
6
6
  current: ProfileCurrentState;
7
7
  threads: ProfileThread[];
@@ -24,12 +24,22 @@ export type ProfileDelta = {
24
24
  export declare class ProfileMemoryStore {
25
25
  private onError;
26
26
  private profileId;
27
+ private windowRows;
28
+ private messageWindows;
29
+ private windowPages;
30
+ private windowAccess;
31
+ private windowIds;
32
+ private windowListeners;
33
+ private windowListListeners;
34
+ private dirtyWindows;
35
+ private readonly emptyWindowIds;
27
36
  private current?;
28
37
  private entities;
29
38
  private threads;
30
39
  private directories;
31
40
  private listeners;
32
41
  private listListeners;
42
+ private messageListeners;
33
43
  private list;
34
44
  private pageCache;
35
45
  private epochs;
@@ -46,6 +56,9 @@ export declare class ProfileMemoryStore {
46
56
  };
47
57
  getThread(threadId: string): ProfileThread | undefined;
48
58
  getMessage(messageId: string): ProfileMessage | undefined;
59
+ getAccessRevision(): number;
60
+ isTeamAvailable(teamId: string | undefined): boolean;
61
+ isThreadAvailable(threadId: string): boolean;
49
62
  getPresentedMessage(messageId: string): Readonly<{
50
63
  id: string;
51
64
  threadId: string;
@@ -102,7 +115,16 @@ export declare class ProfileMemoryStore {
102
115
  }> | undefined;
103
116
  getThreadList: () => readonly ProfileThread[];
104
117
  subscribeThreadList: (listener: () => void) => () => void;
118
+ subscribeMessages(listener: (messages: readonly ProfileMessage[]) => void): () => void;
105
119
  subscribeThread(threadId: string, listener: () => void): () => void;
120
+ private windowKey;
121
+ private installWindow;
122
+ getWindowIds(threadId: string): readonly string[];
123
+ findMessageWindow(threadId: string, messageId: string): string | undefined;
124
+ readPresentedWindow(threadId: string, windowId: string): readonly ChatMessage[];
125
+ subscribeWindow(threadId: string, windowId: string, listener: () => void): () => void;
126
+ subscribeWindowList(threadId: string, listener: () => void): () => void;
127
+ private subscribeKey;
106
128
  restore(snapshot: ProfileSnapshot): void;
107
129
  apply(delta: ProfileDelta): void;
108
130
  private indexMessage;