@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.11

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 +38 -0
  2. package/lib/profile.d.ts +4 -1
  3. package/lib/profile.js +4 -1
  4. package/lib/runtime/profileChat.d.ts +118 -1
  5. package/lib/runtime/profileChat.js +98 -30
  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 +128 -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 +26 -2
  23. package/lib/runtime/profileMemoryStore.js +167 -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} +56 -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,135 +1,169 @@
1
- import { ProfileReplica } from "./profileReplica.js";
1
+ import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
+ import { ProfileWorkerClient } from "./profileWorkerClient.js";
2
3
  import { openProfileWorker, profileChannelName } from "./profileWorkerHost.js";
3
- /** A WebView owns a stable memory replica, not necessarily the writer Worker.
4
- * Every context may acquire an expired lease; fencing decides the sole writer. */
4
+ /** One application document, one dedicated Worker and one stable UI memory store.
5
+ * A failed Worker is terminated before its replacement is created. */
5
6
  export class ProfileCoordinator {
6
7
  options;
7
- replica;
8
- channel;
8
+ memory;
9
9
  worker;
10
+ connection;
10
11
  host;
11
- acquiring;
12
- timer;
13
- closed = false;
14
- needsOwner = false;
15
12
  starting;
13
+ restarting;
14
+ openingAbort;
15
+ closed = false;
16
16
  get identity() { return this.options.configuration.identity; }
17
- get memory() { return this.replica.memory; }
18
- submit(operation, immediate = false) { return this.replica.submit(operation, immediate); }
19
- synchronize() { return this.replica.synchronize(); }
20
- waitForCommand(id) { return this.replica.waitForCommand(id); }
21
- voiceAttachment(id) { return this.replica.voiceAttachment(id); }
17
+ get client() { if (!this.connection)
18
+ throw Error("PROFILE_WORKER_NOT_STARTED"); return this.connection; }
22
19
  constructor(options) {
23
20
  this.options = options;
24
- const scope = profileChannelName(options.configuration.identity);
25
- this.channel = options.channel?.(scope) ?? new BroadcastChannel(scope);
26
- this.channel.addEventListener("message", this.workerMessage);
27
- this.replica = new ProfileReplica(this.channel, scope, error => {
28
- this.report(error);
29
- if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
30
- this.needsOwner = true;
31
- void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
32
- }
33
- }, options.requestTimeoutMs ?? 5000, options.configuration.identity.profileId);
21
+ this.memory = new ProfileMemoryStore(error => this.report(error), this.identity.profileId);
34
22
  }
35
23
  report(error) { try {
36
24
  this.options.onError?.(error);
37
25
  }
38
26
  catch { } }
39
27
  workerMessage = (event) => {
40
- if (event.data?.profileControl === "progress") {
28
+ const data = event.data;
29
+ if (data?.profileControl === "credentials" && typeof data.token === "string" && data.token && data.token.length <= 65536 && this.options.configuration.network)
30
+ this.options.configuration.network = { ...this.options.configuration.network, token: data.token };
31
+ if (data?.profileControl === "progress") {
41
32
  try {
42
- this.options.onProgress?.(event.data.progress);
33
+ this.options.onProgress?.(data.progress);
43
34
  }
44
35
  catch { }
45
36
  }
46
- if (event.data?.profileControl === "error")
47
- this.report(Error(event.data.error));
37
+ if (data?.profileControl === "error") {
38
+ this.report(Error(data.error));
39
+ if (["PROFILE_REVISION_CONFLICT", "PROFILE_GENERATION_MISMATCH"].includes(data.error))
40
+ this.workerFailed();
41
+ }
48
42
  };
43
+ workerFailed = () => { void this.restart().catch(error => this.report(error)); };
44
+ listenFailure(worker, add) {
45
+ // Dedicated Workers have error/messageerror; structural test ports may omit them.
46
+ const target = worker;
47
+ const method = add ? "addEventListener" : "removeEventListener";
48
+ target[method]("error", this.workerFailed);
49
+ target[method]("messageerror", this.workerFailed);
50
+ }
49
51
  start() {
52
+ if (this.closed)
53
+ return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
54
+ if (this.restarting)
55
+ return this.restarting;
50
56
  if (this.starting)
51
57
  return this.starting;
52
- const task = this.initialize().catch(error => { this.starting = undefined; throw error; });
58
+ if (this.connection)
59
+ return Promise.resolve();
60
+ const task = this.initialize().catch(error => {
61
+ if (this.starting === task)
62
+ this.starting = undefined;
63
+ if (!this.closed)
64
+ this.report(error);
65
+ throw error;
66
+ });
53
67
  this.starting = task;
54
68
  return task;
55
69
  }
56
70
  async initialize() {
57
- await this.acquire();
58
- await this.replica.start(false);
59
- if (!this.timer)
60
- this.timer = setInterval(() => {
61
- void this.replica.check().catch(error => {
62
- this.report(error);
63
- if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
64
- this.needsOwner = true;
65
- void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
66
- }
67
- });
68
- }, this.options.retryMs ?? 10000);
71
+ const worker = this.options.createWorker();
72
+ this.worker = worker;
73
+ const abort = new AbortController();
74
+ this.openingAbort = abort;
75
+ worker.addEventListener("message", this.workerMessage);
76
+ this.listenFailure(worker, true);
77
+ try {
78
+ const host = await openProfileWorker(worker, this.options.configuration, this.options.requestTimeoutMs, abort.signal);
79
+ if (this.closed || this.worker !== worker)
80
+ throw Error("PROFILE_COORDINATOR_CLOSED");
81
+ this.host = host;
82
+ const client = new ProfileWorkerClient(worker, profileChannelName(this.identity), error => {
83
+ this.report(error);
84
+ this.workerFailed();
85
+ }, this.options.requestTimeoutMs, this.identity.profileId, this.memory);
86
+ this.connection = client;
87
+ await client.start();
88
+ if (this.closed || this.worker !== worker)
89
+ throw Error("PROFILE_COORDINATOR_CLOSED");
90
+ }
91
+ catch (error) {
92
+ if (this.worker === worker)
93
+ this.disposeWorker();
94
+ throw error;
95
+ }
69
96
  }
70
- acquire() {
97
+ disposeWorker() {
98
+ this.openingAbort?.abort(Error("PROFILE_WORKER_CLIENT_CLOSED"));
99
+ this.openingAbort = undefined;
100
+ this.connection?.close();
101
+ this.connection = undefined;
102
+ this.host = undefined;
103
+ const worker = this.worker;
104
+ this.worker = undefined;
105
+ if (worker) {
106
+ worker.removeEventListener("message", this.workerMessage);
107
+ this.listenFailure(worker, false);
108
+ worker.terminate();
109
+ }
110
+ }
111
+ restart() {
71
112
  if (this.closed)
72
113
  return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
73
- if (this.acquiring)
74
- return this.acquiring;
75
- if (this.host && !this.needsOwner)
76
- return Promise.resolve();
114
+ if (this.restarting)
115
+ return this.restarting;
116
+ const previous = this.starting;
117
+ this.disposeWorker();
118
+ this.starting = undefined;
77
119
  const task = (async () => {
78
- if (this.worker) {
79
- this.worker.removeEventListener("message", this.workerMessage);
80
- this.worker.terminate();
81
- this.worker = undefined;
82
- this.host = undefined;
83
- }
84
- const worker = this.options.createWorker();
85
- worker.addEventListener("message", this.workerMessage);
86
- try {
87
- const host = await openProfileWorker(worker, this.options.configuration);
88
- if (this.closed) {
89
- await host.close();
90
- worker.terminate();
91
- return;
92
- }
93
- this.worker = worker;
94
- this.host = host;
95
- this.needsOwner = false;
96
- }
97
- catch (error) {
98
- worker.removeEventListener("message", this.workerMessage);
99
- worker.terminate();
100
- if (error?.message !== "PROFILE_OWNER_UNAVAILABLE")
101
- throw error;
102
- // Another healthy writer serves this replica through the shared channel.
103
- this.needsOwner = false;
104
- }
120
+ await previous?.catch(() => { });
121
+ if (this.closed)
122
+ throw Error("PROFILE_COORDINATOR_CLOSED");
123
+ await this.initialize();
105
124
  })();
106
- this.acquiring = task;
107
- void task.finally(() => { if (this.acquiring === task)
108
- this.acquiring = undefined; }).catch(() => { });
125
+ this.restarting = task;
126
+ void task.finally(() => {
127
+ if (this.restarting === task) {
128
+ this.restarting = undefined;
129
+ this.starting = undefined;
130
+ }
131
+ }).catch(() => { });
109
132
  return task;
110
133
  }
134
+ async invoke(call) {
135
+ await this.start();
136
+ try {
137
+ return await call(this.client);
138
+ }
139
+ catch (error) {
140
+ if (!["PROFILE_WORKER_TIMEOUT", "PROFILE_WORKER_CLIENT_CLOSED"].includes(error?.message) || this.closed)
141
+ throw error;
142
+ await this.restart();
143
+ // Commands retain their original message/command IDs, making replay safe
144
+ // when the old Worker committed before its response was interrupted.
145
+ return call(this.client);
146
+ }
147
+ }
148
+ submit(operation, immediate = false) { return this.invoke(client => client.submit(operation, immediate)); }
149
+ synchronize() { return this.invoke(client => client.synchronize()); }
150
+ waitForCommand(id) { return this.invoke(client => client.waitForCommand(id)); }
151
+ voiceAttachment(id) { return this.invoke(client => client.voiceAttachment(id)); }
111
152
  async updateToken(token) {
112
- const configuration = this.options.configuration;
113
- if (!configuration.network)
153
+ if (!this.options.configuration.network)
114
154
  return;
115
- configuration.network = { ...configuration.network, token };
116
- await this.host?.update(configuration);
155
+ this.options.configuration.network = { ...this.options.configuration.network, token };
156
+ if (this.starting || this.connection)
157
+ await this.invoke(client => client.updateCredentials(token));
117
158
  }
118
159
  async close() {
160
+ if (this.closed)
161
+ return;
119
162
  this.closed = true;
120
- clearInterval(this.timer);
121
- this.replica.close();
122
- this.channel.removeEventListener("message", this.workerMessage);
123
- this.channel.close();
124
- await this.acquiring;
125
- try {
126
- await this.host?.close();
127
- }
128
- finally {
129
- this.worker?.removeEventListener("message", this.workerMessage);
130
- this.worker?.terminate();
131
- this.worker = undefined;
132
- this.host = undefined;
133
- }
163
+ // Stop the port immediately so requests cannot outlive the Profile.
164
+ this.disposeWorker();
165
+ await this.starting?.catch(() => { });
166
+ await this.restarting?.catch(() => { });
167
+ this.memory.dispose();
134
168
  }
135
169
  }
@@ -1,5 +1,5 @@
1
1
  import Dexie, { type Table } from "dexie";
2
- import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch, ProfileWriterLease } from "./profileStoreTypes.js";
2
+ import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch } from "./profileStoreTypes.js";
3
3
  export declare function profileDatabaseName(identity: ProfileIdentity): string;
4
4
  /** One Profile, five stores, one transaction boundary. No page-facing read API:
5
5
  * restoration is explicit and normal queries belong to the in-memory view. */
@@ -14,10 +14,7 @@ export declare class ProfileDatabase extends Dexie {
14
14
  indexedDB?: IDBFactory;
15
15
  name?: string;
16
16
  });
17
- claimWriter(ownerId: string, now?: number, ttlMs?: number): Promise<ProfileWriterLease | undefined>;
18
- private assertWriter;
19
- releaseWriter(ownerId: string, fence: number): Promise<void>;
20
- initialize(ownerId: string, fence: number, state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
17
+ initialize(state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
21
18
  commit(batch: ProfileWriteBatch): Promise<ProfileCurrentState>;
22
19
  /** Restore from one consistent transaction, never mix data across a switch. */
23
20
  restore(): Promise<{
@@ -27,16 +24,19 @@ export declare class ProfileDatabase extends Dexie {
27
24
  messages: ProfileMessage[];
28
25
  outbox: ProfileOutboxCommand[];
29
26
  }>;
30
- saveGeneration(ownerId: string, fence: number, build: ProfileGenerationState, rows: {
27
+ saveGeneration(build: ProfileGenerationState, rows: {
31
28
  threads?: ProfileThread[];
32
29
  windows?: ProfileWindow[];
33
30
  messages?: ProfileMessage[];
34
31
  }): Promise<void>;
32
+ /** Bounded maintenance on the serial Worker queue. Building
33
+ * and validated generations remain resumable; outbox is never involved. */
34
+ cleanupGenerations(limit?: number): Promise<number>;
35
35
  restoreGeneration(generation: string): Promise<{
36
36
  build: ProfileGenerationState | undefined;
37
37
  threads: ProfileThread[];
38
38
  windows: ProfileWindow[];
39
39
  messages: ProfileMessage[];
40
40
  }>;
41
- activateGeneration(ownerId: string, fence: number, generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
41
+ activateGeneration(generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
42
42
  }
@@ -1,3 +1,4 @@
1
+ import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
1
2
  import Dexie, {} from "dexie";
2
3
  import { inboxSequence } from "./inboxStore.js";
3
4
  export function profileDatabaseName(identity) {
@@ -22,40 +23,14 @@ export class ProfileDatabase extends Dexie {
22
23
  inboxState: "key",
23
24
  outbox: "commandId,[state+createdAt],threadId,messageId",
24
25
  });
26
+ // Additive upgrade: retain projections, reading facts and outbox; retire only
27
+ // the old TTL lease. The lifetime browser lock is acquired before opening.
28
+ this.version(2).stores({}).upgrade(transaction => transaction.table("inboxState").delete("lease"));
25
29
  this.on("versionchange", () => { this.close(); return false; });
26
30
  }
27
- async claimWriter(ownerId, now = Date.now(), ttlMs = 30000) {
28
- if (!ownerId || !Number.isSafeInteger(ttlMs) || ttlMs < 1)
29
- throw Error("INVALID_PROFILE_LEASE");
30
- return this.transaction("rw", this.inboxState, async () => {
31
- const old = await this.inboxState.get("lease");
32
- if (old && old.ownerId !== ownerId && old.expiresAt > now)
33
- return undefined;
34
- const fence = old ? old.ownerId === ownerId && old.expiresAt > now ? old.fence : old.fence + 1 : 1;
35
- if (!Number.isSafeInteger(fence))
36
- throw Error("PROFILE_FENCE_EXHAUSTED");
37
- const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs };
38
- await this.inboxState.put(lease);
39
- return lease;
40
- });
41
- }
42
- async assertWriter(ownerId, fence) {
43
- const lease = await this.inboxState.get("lease");
44
- if (!lease || lease.ownerId !== ownerId || lease.fence !== fence || lease.expiresAt <= Date.now())
45
- throw Error("PROFILE_WRITER_FENCED");
46
- }
47
- async releaseWriter(ownerId, fence) {
48
- await this.transaction("rw", this.inboxState, async () => {
49
- const lease = await this.inboxState.get("lease");
50
- // Keep the counter: deleting it would allow a stale producer to reuse fence 1.
51
- if (lease?.ownerId === ownerId && lease.fence === fence)
52
- await this.inboxState.put({ ...lease, expiresAt: 0 });
53
- });
54
- }
55
- async initialize(ownerId, fence, state) {
31
+ async initialize(state) {
56
32
  inboxSequence(state.committedSeq);
57
33
  return this.transaction("rw", this.inboxState, async () => {
58
- await this.assertWriter(ownerId, fence);
59
34
  const previous = await this.inboxState.get("current");
60
35
  if (previous)
61
36
  return previous;
@@ -71,7 +46,6 @@ export class ProfileDatabase extends Dexie {
71
46
  throw Error("PROFILE_GENERATION_MISMATCH");
72
47
  }
73
48
  return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
74
- await this.assertWriter(batch.ownerId, batch.fence);
75
49
  const current = await this.inboxState.get("current");
76
50
  if (!current || current.activeGeneration !== batch.generation || current.epoch !== batch.epoch)
77
51
  throw Error("PROFILE_GENERATION_MISMATCH");
@@ -80,7 +54,8 @@ export class ProfileDatabase extends Dexie {
80
54
  if (inboxSequence(batch.committedSeq) < inboxSequence(current.committedSeq))
81
55
  throw Error("PROFILE_CURSOR_REGRESSION");
82
56
  const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
83
- if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady))
57
+ const localMigrations = batch.localMigrations ? [...new Set([...(current.localMigrations ?? []), ...batch.localMigrations])] : current.localMigrations;
58
+ if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision && (batch.windowStart ?? current.windowStart) === current.windowStart)
84
59
  return current;
85
60
  if (batch.messages?.length)
86
61
  await this.messages.bulkPut(batch.messages);
@@ -98,7 +73,7 @@ export class ProfileDatabase extends Dexie {
98
73
  await this.outbox.bulkDelete(batch.deleteOutbox);
99
74
  if (!Number.isSafeInteger(current.commitRevision + 1))
100
75
  throw Error("PROFILE_REVISION_EXHAUSTED");
101
- const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
76
+ const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, windowStart: batch.windowStart ?? current.windowStart, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
102
77
  await this.inboxState.put(next);
103
78
  return next;
104
79
  });
@@ -106,17 +81,25 @@ export class ProfileDatabase extends Dexie {
106
81
  /** Restore from one consistent transaction, never mix data across a switch. */
107
82
  async restore() {
108
83
  return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
109
- const current = await this.inboxState.get("current");
84
+ let current = await this.inboxState.get("current");
110
85
  const generation = current?.activeGeneration;
111
- return { current,
112
- threads: generation ? await this.threads.where("generation").equals(generation).toArray() : [],
86
+ const threads = generation ? await this.threads.where("generation").equals(generation).toArray() : [];
87
+ if (current && current.windowStart === undefined) {
88
+ // Additive migration for early Profile caches. Restoration already reads
89
+ // these records; never replace a committed range with a startup default.
90
+ const build = await this.inboxState.get(`build:${generation}`);
91
+ const inferred = build?.windowStart ?? (threads.length ? threads.reduce((start, row) => Math.max(start, row.coverage.windowStart), threads[0].coverage.windowStart) : undefined);
92
+ if (inferred !== undefined)
93
+ current = { ...current, windowStart: inferred };
94
+ }
95
+ return { current, threads,
113
96
  windows: generation ? await this.windows.where("generation").equals(generation).toArray() : [],
114
97
  messages: generation ? await this.messages.where("generation").equals(generation).toArray() : [],
115
98
  outbox: await this.outbox.toArray(),
116
99
  };
117
100
  });
118
101
  }
119
- async saveGeneration(ownerId, fence, build, rows) {
102
+ async saveGeneration(build, rows) {
120
103
  inboxSequence(build.committedSeq);
121
104
  for (const row of [...rows.threads ?? [], ...rows.windows ?? [], ...rows.messages ?? []])
122
105
  if (row.generation !== build.generation)
@@ -124,7 +107,6 @@ export class ProfileDatabase extends Dexie {
124
107
  if (build.key !== `build:${build.generation}`)
125
108
  throw Error("PROFILE_GENERATION_MISMATCH");
126
109
  await this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
127
- await this.assertWriter(ownerId, fence);
128
110
  const current = await this.inboxState.get("current");
129
111
  if (current?.activeGeneration === build.generation)
130
112
  throw Error("PROFILE_BUILD_IS_ACTIVE");
@@ -137,6 +119,40 @@ export class ProfileDatabase extends Dexie {
137
119
  await this.inboxState.put(build);
138
120
  });
139
121
  }
122
+ /** Bounded maintenance on the serial Worker queue. Building
123
+ * and validated generations remain resumable; outbox is never involved. */
124
+ async cleanupGenerations(limit = 200) {
125
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)
126
+ throw Error("INVALID_PROFILE_CLEANUP_LIMIT");
127
+ return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
128
+ const current = await this.inboxState.get("current");
129
+ if (!current)
130
+ return 0;
131
+ const builds = (await this.inboxState.toArray()).filter((row) => row.key.startsWith("build:"));
132
+ const protectedGenerations = new Set([current.activeGeneration, ...builds.filter(row => row.projectionVersion === PROFILE_PROJECTION_VERSION && (row.status === "building" || row.status === "validated")).map(row => row.generation)]);
133
+ let removed = 0;
134
+ for (const table of [this.messages, this.windows, this.threads]) {
135
+ if (removed === limit)
136
+ break;
137
+ const keys = await table.where("generation").noneOf([...protectedGenerations]).limit(limit - removed).primaryKeys();
138
+ // Dexie accepts each table's native compound keys. Keep the union of
139
+ // table key types at this maintenance boundary only.
140
+ if (keys.length)
141
+ await table.bulkDelete(keys);
142
+ removed += keys.length;
143
+ }
144
+ if (removed < limit)
145
+ for (const build of builds) {
146
+ if (removed === limit)
147
+ break;
148
+ if (!protectedGenerations.has(build.generation)) {
149
+ await this.inboxState.delete(build.key);
150
+ removed++;
151
+ }
152
+ }
153
+ return removed;
154
+ });
155
+ }
140
156
  async restoreGeneration(generation) {
141
157
  return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState], async () => ({
142
158
  build: await this.inboxState.get(`build:${generation}`),
@@ -145,17 +161,16 @@ export class ProfileDatabase extends Dexie {
145
161
  messages: await this.messages.where("generation").equals(generation).toArray(),
146
162
  }));
147
163
  }
148
- async activateGeneration(ownerId, fence, generation, expectedRevision) {
164
+ async activateGeneration(generation, expectedRevision) {
149
165
  return this.transaction("rw", this.inboxState, async () => {
150
- await this.assertWriter(ownerId, fence);
151
166
  const current = await this.inboxState.get("current");
152
167
  const build = await this.inboxState.get(`build:${generation}`);
153
168
  if (!current || current.commitRevision !== expectedRevision || build?.sourceRevision !== expectedRevision)
154
169
  throw Error("PROFILE_REVISION_CONFLICT");
155
170
  if (build.status !== "validated")
156
171
  throw Error("PROFILE_BUILD_NOT_VALIDATED");
157
- const next = { key: "current", activeGeneration: generation, epoch: build.epoch,
158
- committedSeq: build.committedSeq, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
172
+ const next = { ...current, key: "current", activeGeneration: generation, epoch: build.epoch,
173
+ committedSeq: build.committedSeq, windowStart: build.windowStart ?? current.windowStart, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
159
174
  await this.inboxState.put({ ...build, status: "active" });
160
175
  await this.inboxState.put(next);
161
176
  return next;
@@ -1,14 +1,13 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
2
  import { ProfileProjection, type ProfileOperation } from "./profileProjection.js";
3
3
  import { type InboxBootstrap } from "./inboxStore.js";
4
- import type { ProfileGenerationState, ProfileWriterLease } from "./profileStoreTypes.js";
4
+ import type { ProfileGenerationState } from "./profileStoreTypes.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 declare class ProfileGenerationBuilder {
8
8
  private database;
9
- private lease;
10
9
  private cache;
11
- constructor(database: ProfileDatabase, lease: () => ProfileWriterLease);
10
+ constructor(database: ProfileDatabase);
12
11
  private persist;
13
12
  private load;
14
13
  begin(generation: string, bootstrap: InboxBootstrap, sourceRevision: number): Promise<void>;
@@ -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;