@pmate/chat-sdk 0.12.0-next.86 → 0.12.0-next.88

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.
@@ -2,6 +2,22 @@ export type ChatErrorCode = "unavailable" | "access-denied" | "authentication-re
2
2
  /** Stable recovery categories. The original failure remains available as cause. */
3
3
  export declare class ChatError extends Error {
4
4
  readonly code: ChatErrorCode;
5
+ readonly diagnostic?: {
6
+ source: string;
7
+ stage?: string;
8
+ database?: string;
9
+ tables?: string;
10
+ mode?: string;
11
+ attempt?: number;
12
+ route?: string;
13
+ method?: string;
14
+ operationId?: string;
15
+ clientRequestId?: string;
16
+ serverRequestId?: string;
17
+ serverCode?: string;
18
+ status?: number;
19
+ durationMs?: number;
20
+ };
5
21
  readonly retryable: boolean;
6
22
  readonly status?: number;
7
23
  /** Present only when access was denied for one conversation, not the Team. */
@@ -10,5 +26,6 @@ export declare class ChatError extends Error {
10
26
  cause?: unknown;
11
27
  status?: number;
12
28
  threadId?: string;
29
+ diagnostic?: ChatError["diagnostic"];
13
30
  });
14
31
  }
package/lib/chatError.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Stable recovery categories. The original failure remains available as cause. */
2
2
  export class ChatError extends Error {
3
3
  code;
4
+ diagnostic;
4
5
  retryable;
5
6
  status;
6
7
  /** Present only when access was denied for one conversation, not the Team. */
@@ -11,6 +12,7 @@ export class ChatError extends Error {
11
12
  this.name = "ChatError";
12
13
  this.status = options.status;
13
14
  this.threadId = options.threadId;
15
+ this.diagnostic = options.diagnostic;
14
16
  this.retryable = ["unavailable", "storage-unavailable", "busy"].includes(code);
15
17
  }
16
18
  }
@@ -74,6 +74,7 @@ export declare class ChatEngine {
74
74
  private threadSubscribers;
75
75
  private openQueue;
76
76
  private opening;
77
+ private threadRecovery;
77
78
  private drainOpens;
78
79
  /** Listen first, then open the local window; concurrent consumers share the initial read. */
79
80
  subscribeThread(threadId: string, listener: (snapshot: ChatThreadSnapshot) => void, options?: SubscribeOptions<ChatThreadSnapshot>): () => void;
@@ -108,15 +108,18 @@ export class ChatEngine {
108
108
  }
109
109
  threadSubscribers = new Map();
110
110
  openQueue = new Set();
111
- opening = 0;
111
+ opening = new Set();
112
+ threadRecovery = new Map();
112
113
  drainOpens() {
113
- while (!this.closed && this.opening < 4 && this.openQueue.size) {
114
- const id = this.openQueue.values().next().value;
114
+ while (!this.closed && this.opening.size < 4 && this.openQueue.size) {
115
+ const id = [...this.openQueue].find(id => !this.opening.has(id));
116
+ if (id === undefined)
117
+ break;
115
118
  this.openQueue.delete(id);
116
119
  if (!this.threadSubscribers.has(id))
117
120
  continue;
118
- this.opening++;
119
- void this.getThread(id).catch(() => { }).finally(() => { this.opening--; this.drainOpens(); });
121
+ this.opening.add(id);
122
+ void this.getThread(id).catch(() => { }).finally(() => { this.opening.delete(id); this.drainOpens(); });
120
123
  }
121
124
  }
122
125
  /** Listen first, then open the local window; concurrent consumers share the initial read. */
@@ -124,6 +127,20 @@ export class ChatEngine {
124
127
  const off = this.subscribe(threadId, listener, options), count = this.threadSubscribers.get(threadId) ?? 0;
125
128
  this.threadSubscribers.set(threadId, count + 1);
126
129
  if (!count) {
130
+ // Track coverage independently of consumer field filters. A canonical history
131
+ // reset also invalidates open discussion windows sharing that source epoch.
132
+ let complete = this.advanced.getSnapshot(threadId).complete;
133
+ this.threadRecovery.set(threadId, this.advanced.subscribeChanges(threadId, () => {
134
+ const next = this.advanced.getSnapshot(threadId).complete, lost = complete && !next;
135
+ complete = next;
136
+ if (lost)
137
+ queueMicrotask(() => {
138
+ if (this.closed || !this.advanced.active || !this.threadSubscribers.has(threadId) || this.getSnapshot(threadId).status !== "pending")
139
+ return;
140
+ this.openQueue.add(threadId);
141
+ this.drainOpens();
142
+ });
143
+ }, ["complete"]));
127
144
  this.openQueue.add(threadId);
128
145
  this.drainOpens();
129
146
  }
@@ -139,6 +156,8 @@ export class ChatEngine {
139
156
  else {
140
157
  this.threadSubscribers.delete(threadId);
141
158
  this.openQueue.delete(threadId);
159
+ this.threadRecovery.get(threadId)?.();
160
+ this.threadRecovery.delete(threadId);
142
161
  }
143
162
  };
144
163
  }
@@ -283,5 +302,5 @@ export class ChatEngine {
283
302
  updateGroup(threadId, changes) { return this.threadOperation(threadId, async () => this.group(await this.advanced.updateGroup(threadId, changes))); }
284
303
  dissolveGroup(threadId, options = {}) { return this.threadOperation(threadId, async () => this.group(await this.advanced.dissolveGroup(threadId, options))); }
285
304
  revokeAccess() { return this.operation(() => this.advanced.revokeAccess()); }
286
- close() { this.closed = true; return this.operation(() => this.advanced.close()).finally(() => { this.errors.clear(); this.targets.clear(); this.listeners.clear(); this.threadSubscribers.clear(); this.openQueue.clear(); this.views.clear(); this.summary = undefined; this.present = createMessagePresenter(); this.messageLists = new WeakMap(); this.groups = new WeakMap(); this.redactedQuotes = new WeakMap(); }); }
305
+ close() { this.closed = true; this.threadRecovery.forEach(off => off()); this.threadRecovery.clear(); return this.operation(() => this.advanced.close()).finally(() => { this.errors.clear(); this.targets.clear(); this.listeners.clear(); this.threadSubscribers.clear(); this.openQueue.clear(); this.views.clear(); this.summary = undefined; this.present = createMessagePresenter(); this.messageLists = new WeakMap(); this.groups = new WeakMap(); this.redactedQuotes = new WeakMap(); }); }
287
306
  }
@@ -11,7 +11,7 @@ export function asChatError(error) {
11
11
  : /BACKPRESSURE|TOO_LARGE/.test(message) ? "busy"
12
12
  : status === 400 || /INVALID_|CONVERSATION_MISMATCH|CONVERSATION_UNKNOWN|NOT_OWNED/.test(message) ? "invalid-input"
13
13
  : /QuotaExceeded|DatabaseClosed|UnknownError|AbortError/.test(value?.name ?? "") || /STORAGE_|DATABASE_|CACHE_WRITE/.test(message) ? "storage-unavailable" : "unavailable";
14
- return new ChatError(code, message, { cause: error, status, threadId: value?.threadId });
14
+ return new ChatError(code, message, { cause: error, status, threadId: value?.threadId, diagnostic: value?.diagnostic });
15
15
  }
16
16
  /** Keep a conversation denial distinct from loss of Team authority. */
17
17
  export function threadChatError(error, threadId) {
@@ -1,4 +1,6 @@
1
1
  import type { Dexie } from "dexie";
2
2
  /** WebKit can invalidate an IDB connection while the application is suspended.
3
3
  * Only replay a whole rejected transaction; never replay individual requests or clear data. */
4
- export declare function recoverableTransactions(db: Dexie, isClosed: () => boolean): Dexie["transaction"];
4
+ export declare function recoverableTransactions(db: Dexie, isClosed: () => boolean, options?: {
5
+ retryAbort?: boolean;
6
+ }): Dexie["transaction"];
@@ -1,16 +1,31 @@
1
1
  /** WebKit can invalidate an IDB connection while the application is suspended.
2
2
  * Only replay a whole rejected transaction; never replay individual requests or clear data. */
3
- export function recoverableTransactions(db, isClosed) {
4
- const transaction = (...args) => db.transaction.apply(db, args);
3
+ export function recoverableTransactions(db, isClosed, options = {}) {
4
+ const transaction = async (args, attempt) => {
5
+ try {
6
+ return await db.transaction.apply(db, args);
7
+ }
8
+ catch (cause) {
9
+ const original = cause;
10
+ const error = new Error(original.message, { cause });
11
+ error.name = original.name;
12
+ Object.assign(error, { status: original.status, threadId: original.threadId, inner: original.inner, diagnostic: { source: "storage", database: db.name, tables: args.slice(1, -1).flat().map((table) => table.name ?? String(table)).join(","), mode: String(args[0]), attempt } });
13
+ throw error;
14
+ }
15
+ };
5
16
  let recovery;
6
17
  return (async (...args) => {
7
18
  try {
8
- return await transaction(...args);
19
+ return await transaction(args, 1);
9
20
  }
10
21
  catch (error) {
11
22
  const failure = error;
12
- if (isClosed() || !(failure.name === "UnknownError" || failure.inner?.name === "UnknownError") || !/without an in-progress transaction/i.test(failure.message ?? ""))
23
+ const aborted = options.retryAbort && (failure.name === "AbortError" || failure.inner?.name === "AbortError");
24
+ if (isClosed() || !aborted && (!(failure.name === "UnknownError" || failure.inner?.name === "UnknownError") || !/without an in-progress transaction/i.test(failure.message ?? "")))
13
25
  throw error;
26
+ // An aborted transaction has already rolled back; replay without closing other live transactions.
27
+ if (aborted)
28
+ return transaction(args, 2);
14
29
  if (!recovery) {
15
30
  db.close({ disableAutoOpen: false });
16
31
  const opening = db.open();
@@ -21,7 +36,7 @@ export function recoverableTransactions(db, isClosed) {
21
36
  await recovery;
22
37
  if (isClosed())
23
38
  throw error;
24
- return transaction(...args);
39
+ return transaction(args, 2);
25
40
  }
26
41
  });
27
42
  }
@@ -27,6 +27,7 @@ export declare class ReadCountsClient {
27
27
  private heartbeat?;
28
28
  private controller?;
29
29
  private generation;
30
+ private operationId;
30
31
  private retries;
31
32
  private closed;
32
33
  private closing?;
@@ -44,6 +45,7 @@ export declare class ReadCountsClient {
44
45
  private requestedRevision;
45
46
  private force;
46
47
  constructor(options: ReadCountsOptions);
48
+ private report;
47
49
  private denyCache;
48
50
  private post;
49
51
  private subscription;
@@ -1,6 +1,41 @@
1
+ import { asChatError, ChatError } from "./chatError.js";
1
2
  import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
2
3
  import { IndexedDbResponseCache, isResponseCacheAuthorityError, assertResponseCacheAccess } from "./responseCache.js";
3
4
  import { messageScopeKey } from "./messageStore.js";
5
+ const requestId = () => crypto.randomUUID();
6
+ const safeId = (value) => value && /^[a-zA-Z0-9_.:@-]{1,128}$/.test(value) ? value : undefined;
7
+ // Error bodies are untrusted; never retain their text, scope, or arbitrary fields.
8
+ async function failureCode(response) {
9
+ if (response.bodyUsed || response.body?.locked)
10
+ return;
11
+ const reader = response.body?.getReader();
12
+ if (!reader)
13
+ return;
14
+ let timer;
15
+ try {
16
+ const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("READ_COUNTS_DIAGNOSTIC_TIMEOUT")), 250); });
17
+ let text = "", bytes = 0;
18
+ const decoder = new TextDecoder();
19
+ while (true) {
20
+ const part = await Promise.race([reader.read(), deadline]);
21
+ if (part.done)
22
+ break;
23
+ bytes += part.value.byteLength;
24
+ if (bytes > 4096)
25
+ return;
26
+ text += decoder.decode(part.value, { stream: true });
27
+ }
28
+ const code = JSON.parse(text + decoder.decode())?.message;
29
+ return typeof code === "string" && /^(SOCIAL_READ_(UNAVAILABLE|IDENTITY_UNAVAILABLE|FORBIDDEN)|INVALID_READ_COUNTS|UNAUTHORIZED|INVALID_SOCIAL_READ_IDENTITY|READ_RECEIVER_NOT_READY)$/.test(code) ? code : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ void reader.cancel().catch(() => { });
37
+ }
38
+ }
4
39
  let subscriptionSequence = 0;
5
40
  function nextSubscriptionSequence() { subscriptionSequence = Math.max(Date.now() * 1000, subscriptionSequence + 1); return subscriptionSequence; }
6
41
  /** One active conversation; fixed event window, bounded batches, no count polling. */
@@ -12,6 +47,7 @@ export class ReadCountsClient {
12
47
  heartbeat;
13
48
  controller;
14
49
  generation = 0;
50
+ operationId = requestId();
15
51
  retries = 0;
16
52
  closed = false;
17
53
  closing;
@@ -38,26 +74,44 @@ export class ReadCountsClient {
38
74
  if (options.scope) {
39
75
  if (options.scope.appId !== options.appId || options.scope.profileId !== options.profileId)
40
76
  throw new Error("READ_COUNTS_SCOPE_MISMATCH");
41
- this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope), { access: options.access });
77
+ this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope), { access: options.access, retryAbort: true });
42
78
  }
43
79
  }
80
+ report(error, stage) {
81
+ const failure = asChatError(error);
82
+ this.options.onError?.(new ChatError(failure.code, failure.message, { cause: error, status: failure.status, threadId: failure.threadId, diagnostic: { ...failure.diagnostic, source: "read-counts", stage } }));
83
+ }
44
84
  denyCache() {
45
85
  this.revoked = true;
46
86
  this.accessVersion++;
47
87
  this.lastResult = undefined;
48
- void this.cache?.invalidate().catch(error => this.options.onError?.(error));
88
+ void this.cache?.invalidate().catch(error => this.report(error, "cache.invalidate"));
49
89
  }
50
90
  async post(path, body, signal) {
51
91
  const scopeVersion = this.options.access ? await assertResponseCacheAccess(this.options.access) : undefined;
52
- const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
53
- if (!response.ok)
54
- throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
55
- const envelope = await response.json();
56
- if (envelope.success !== true)
57
- throw new Error("INVALID_READ_COUNTS_RESPONSE");
58
- if (this.options.access)
59
- await assertResponseCacheAccess(this.options.access, scopeVersion);
60
- return envelope.data;
92
+ const clientRequestId = requestId(), started = performance.now();
93
+ const diagnostic = { source: "read-counts", route: path, method: "POST", operationId: this.operationId, clientRequestId, attempt: path.endsWith("/counts") ? this.retries + 1 : 1 };
94
+ try {
95
+ const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json", "x-request-id": clientRequestId }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
96
+ diagnostic.status = response.status;
97
+ diagnostic.serverRequestId = safeId(response.headers.get("x-request-id"));
98
+ if (!response.ok) {
99
+ diagnostic.serverCode = await failureCode(response);
100
+ throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
101
+ }
102
+ const envelope = await response.json();
103
+ if (envelope.success !== true)
104
+ throw new Error("INVALID_READ_COUNTS_RESPONSE");
105
+ diagnostic.durationMs = Math.round(performance.now() - started);
106
+ // Keep validation and retry behavior unchanged; add only transport diagnostics.
107
+ if (this.options.access)
108
+ await assertResponseCacheAccess(this.options.access, scopeVersion);
109
+ return envelope.data;
110
+ }
111
+ catch (error) {
112
+ diagnostic.durationMs = Math.round(performance.now() - started);
113
+ throw Object.assign(error instanceof Error ? error : new Error("READ_COUNTS_REQUEST_FAILED"), { diagnostic });
114
+ }
61
115
  }
62
116
  subscription(threadId, release) {
63
117
  if (release && isOffline())
@@ -102,7 +156,7 @@ export class ReadCountsClient {
102
156
  this.heartbeat = undefined;
103
157
  }
104
158
  if (!isOfflineNetworkFailure(error))
105
- this.options.onError?.(error);
159
+ this.report(error, "subscription.renew");
106
160
  }).finally(() => { if (this.subscriptionPending === pending)
107
161
  this.subscriptionPending = undefined; });
108
162
  this.subscriptionPending = pending;
@@ -121,6 +175,7 @@ export class ReadCountsClient {
121
175
  return;
122
176
  }
123
177
  const old = this.thread;
178
+ this.operationId = requestId();
124
179
  this.generation++;
125
180
  this.controller?.abort();
126
181
  clearTimeout(this.timer);
@@ -137,7 +192,7 @@ export class ReadCountsClient {
137
192
  this.subscribed = false;
138
193
  this.subscriptionDenied = false;
139
194
  if (old)
140
- void this.subscription(old, true).catch(error => this.options.onError?.(error));
195
+ void this.subscription(old, true).catch(error => this.report(error, "subscription.release"));
141
196
  if (!threadId)
142
197
  return;
143
198
  this.renew();
@@ -190,7 +245,7 @@ export class ReadCountsClient {
190
245
  const key = JSON.stringify(["counts", threadId, [...ids].sort()]);
191
246
  try {
192
247
  const stored = this.cache ? await this.cache.read(key).catch(error => { if (isResponseCacheAuthorityError(error))
193
- throw error; this.options.onError?.(error); return undefined; }) : undefined;
248
+ throw error; this.report(error, "cache.read"); return undefined; }) : undefined;
194
249
  if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
195
250
  return;
196
251
  const cached = this.revoked || (stored?.cached && stored.cached.value.revision < this.revision) ? undefined : stored?.cached;
@@ -214,7 +269,7 @@ export class ReadCountsClient {
214
269
  this.revoked = false;
215
270
  if (stored)
216
271
  await this.cache?.write(key, value, stored.epoch).catch(error => { if (isResponseCacheAuthorityError(error))
217
- throw error; this.options.onError?.(error); });
272
+ throw error; this.report(error, "cache.write"); });
218
273
  if (generation !== this.generation || this.closed || accessVersion !== this.accessVersion)
219
274
  return;
220
275
  this.revision = value.revision;
@@ -237,7 +292,7 @@ export class ReadCountsClient {
237
292
  clearInterval(this.heartbeat);
238
293
  this.heartbeat = undefined;
239
294
  }
240
- this.options.onError?.(error);
295
+ this.report(error, "counts.request");
241
296
  if (!isResponseCacheAuthorityError(error) && (!/READ_COUNTS_HTTP_4\d\d|INVALID_READ_COUNTS/.test(String(error)) || /READ_COUNTS_HTTP_(409|429)/.test(String(error))) && this.retries < 3) {
242
297
  retryDelay = 1000 * 2 ** this.retries++;
243
298
  this.dirty = true;
@@ -265,6 +320,6 @@ export class ReadCountsClient {
265
320
  if (old)
266
321
  void this.subscription(old, true).catch(() => { });
267
322
  this.thread = undefined;
268
- return this.closing = this.cache?.close().catch(error => this.options.onError?.(error)) ?? Promise.resolve();
323
+ return this.closing = this.cache?.close().catch(error => this.report(error, "cache.close")) ?? Promise.resolve();
269
324
  }
270
325
  }
@@ -5,6 +5,7 @@ export type ResponseCacheAccess = () => Promise<{
5
5
  export declare function isResponseCacheAuthorityError(error: unknown): boolean;
6
6
  export declare function assertResponseCacheAccess(access?: ResponseCacheAccess, expectedVersion?: number): Promise<number | undefined>;
7
7
  export type ResponseCacheOptions<T> = {
8
+ retryAbort?: boolean;
8
9
  indexedDB?: IDBFactory;
9
10
  name?: string;
10
11
  access?: ResponseCacheAccess;
@@ -36,7 +36,7 @@ export class IndexedDbResponseCache {
36
36
  if (!Number.isSafeInteger(value) || value < 1 || value > max)
37
37
  throw new Error("INVALID_RESPONSE_CACHE_LIMIT");
38
38
  this.db = new Dexie(options.name ?? "pmate-chat-response-windows", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
39
- this.transact = recoverableTransactions(this.db, () => this.closed);
39
+ this.transact = recoverableTransactions(this.db, () => this.closed, { retryAbort: options.retryAbort });
40
40
  this.db.version(1).stores({ windows: "[scope+key],scope", epochs: "scope" });
41
41
  this.rows = this.db.table("windows");
42
42
  this.epochs = this.db.table("epochs");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.12.0-next.86",
3
+ "version": "0.12.0-next.88",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -58,15 +58,6 @@
58
58
  "publishConfig": {
59
59
  "access": "public"
60
60
  },
61
- "scripts": {
62
- "clean": "rimraf lib",
63
- "build": "pnpm run clean && tsc -p tsconfig.build.json && cp src/voice/recorder-processor.js lib/voice/recorder-processor.js",
64
- "prepack": "pnpm run build",
65
- "npm:publish": "pnpm run build && npm publish --access public --registry https://registry.npmjs.org/",
66
- "test": "vitest run",
67
- "storybook": "storybook dev -p 6009",
68
- "build-storybook": "storybook build --output-dir dist"
69
- },
70
61
  "dependencies": {
71
62
  "@emoji-mart/data": "^1.2.1",
72
63
  "@emoji-mart/react": "^1.1.1",
@@ -82,16 +73,24 @@
82
73
  "devDependencies": {
83
74
  "@storybook/addon-docs": "^9.0.17",
84
75
  "@storybook/react-vite": "9.0.17",
85
- "@tailwindcss/vite": "catalog:",
86
- "@types/react": "catalog:",
87
- "@types/react-dom": "catalog:",
76
+ "@tailwindcss/vite": "^4.1.3",
77
+ "@types/react": "^19.2.7",
78
+ "@types/react-dom": "^19.2.3",
88
79
  "fake-indexeddb": "^6.2.5",
89
- "react": "catalog:",
90
- "react-dom": "catalog:",
80
+ "react": "^19.1.1",
81
+ "react-dom": "^19.1.1",
91
82
  "rimraf": "^6.1.2",
92
83
  "storybook": "^9.0.17",
93
- "tailwindcss": "catalog:",
84
+ "tailwindcss": "^4.0.14",
94
85
  "typescript": "5.9.2",
95
86
  "vitest": "^4.0.17"
87
+ },
88
+ "scripts": {
89
+ "clean": "rimraf lib",
90
+ "build": "pnpm run clean && tsc -p tsconfig.build.json && cp src/voice/recorder-processor.js lib/voice/recorder-processor.js",
91
+ "npm:publish": "pnpm run build && npm publish --access public --registry https://registry.npmjs.org/",
92
+ "test": "vitest run",
93
+ "storybook": "storybook dev -p 6009",
94
+ "build-storybook": "storybook build --output-dir dist"
96
95
  }
97
- }
96
+ }