@wtfalch/chat 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,17 @@
2
2
 
3
3
  Team chat, on Matrix. Mirrors [`@wtfalch/email`](https://github.com/wtfalch/email)'s
4
4
  shape: a client the agora gives a way to get a token, a React section built on
5
- it, and a fake of both for stories and tests.
5
+ it.
6
+
7
+ ## Breaking in 0.11.0
8
+
9
+ - `ChatTimelineEvent` has two new required fields: `viaAssistant` (`string | null`) and `undecryptable` (`boolean`). Code that builds a `ChatTimelineEvent` by hand must set them, for example `viaAssistant: null` and `undecryptable: false`.
10
+
11
+ ## Breaking in 0.10.0
12
+
13
+ - `stop()` returns `Promise<void>` instead of `void`. It settles once every store the client built is destroyed, and it never rejects. A hand-written `ChatClient` with `stop: () => {}` no longer compiles; return a resolved promise.
14
+ - A `start()` that `stop()` overtook rejects with `ChatStartCancelledError`, exported from the package. Attach a handler when you do not await `start()`.
15
+ - The `./fake` export is gone. An app that needs a stand-in for development keeps its own copy.
6
16
 
7
17
  ## Exports
8
18
 
@@ -10,7 +20,6 @@ it, and a fake of both for stories and tests.
10
20
  | --- | --- |
11
21
  | `@wtfalch/chat` | `createChatClient`: a matrix-js-sdk `MatrixClient` behind the token exchange, refreshed on its own, exposing a small typed API |
12
22
  | `@wtfalch/chat/react` | The `Chat` component: rooms, a timeline, a composer, direct messages, threads, reactions and mentions |
13
- | `@wtfalch/chat/fake` | A real `createChatClient`, wired to a fake exchange and a fake homeserver instead of the network |
14
23
  | `@wtfalch/chat/chat.css` | Styles, on `@wtfalch/design` tokens |
15
24
 
16
25
  ## The client
@@ -29,6 +38,10 @@ await chat.start();
29
38
  chat.onRoomsChanged((rooms) => render(rooms));
30
39
  ```
31
40
 
41
+ A `start()` that `stop()` overtakes rejects with `ChatStartCancelledError`; if you do not await it, attach a handler:
42
+ `void chat.start().catch((error) => { if (!(error instanceof ChatStartCancelledError)) report(error); });`
43
+ `stop()` returns a Promise that settles once the store is destroyed; it never rejects.
44
+
32
45
  `createChatClient` takes only a way to get a current ZITADEL access token
33
46
  (`getAccessToken`) -- it knows nothing else about the agora, and never imports
34
47
  an Agora type. On `start()`, it `POST`s `exchangeUrl` with that token and a
@@ -325,10 +338,13 @@ entities, `svg onload`, `object`/`embed`/`form`/`base`/`meta`, every `on*`
325
338
  handler, the `<scr<script>ipt>` trick, foreign image sources, and messages
326
339
  built out of nothing but depth or siblings.
327
340
 
328
- ## The fake
341
+ ## The test double
342
+
343
+ Not exported and not published: `src/chat/fake` is this package's own test
344
+ double, left out of the build.
329
345
 
330
346
  ```ts
331
- import { fakeChat } from '@wtfalch/chat/fake';
347
+ import { fakeChat } from '../fake/index.ts';
332
348
 
333
349
  const { client, server, dispose } = fakeChat();
334
350
  await client.start();
@@ -339,7 +355,7 @@ dispose();
339
355
  Like `@wtfalch/email`'s `fakeMail`, this is a fake transport, not a fake
340
356
  client: `createChatClient` and matrix-js-sdk run unchanged, against a fake
341
357
  exchange and homeserver answered by intercepting `fetch`. `FakeChatServer`
342
- (also exported) gives a test finer control -- seeding rooms (with a starting
358
+ gives a test finer control -- seeding rooms (with a starting
343
359
  `notificationCount`), seeding the company space (`isSpace`) and who is in it
344
360
  (`members`, `invited`), adding, renaming or delivering someone leaving a room
345
361
  mid-test, sending a message into one, invalidating the current token to
@@ -110,8 +110,17 @@ export function createChatAdmin(options) {
110
110
  });
111
111
  const data = await response.json().catch(() => null);
112
112
  if (!response.ok) {
113
- const code = record(data) && typeof data.error === 'string' && /^[a-z_]{1,64}$/.test(data.error)
114
- ? data.error
113
+ // The shared estate envelope (`@wtfalch/contracts`):
114
+ // `{ error: { code, message, reason? } }`. `reason`, when the
115
+ // service sent one, is the finer-grained value this SDK's own
116
+ // `code` has always carried (`user_not_found`, not just the closed
117
+ // nine-value `not_found`) -- preferred for that reason.
118
+ const errorField = record(data) ? data.error : undefined;
119
+ const nested = record(errorField) ? errorField : undefined;
120
+ const candidate = (nested && typeof nested.reason === 'string' ? nested.reason : undefined) ??
121
+ (nested && typeof nested.code === 'string' ? nested.code : undefined);
122
+ const code = typeof candidate === 'string' && /^[a-z_]{1,64}$/.test(candidate)
123
+ ? candidate
115
124
  : 'request_failed';
116
125
  throw new ChatAdminError(response.status, code);
117
126
  }
@@ -42,4 +42,10 @@ export declare function normaliseTopic(raw: string): string;
42
42
  * no-op while `clientRunning` is still true, so a plain retry would never
43
43
  * resume syncing.
44
44
  */
45
+ /** Rejection of a `start()` that `stop()` overtook. */
46
+ export declare class ChatStartCancelledError extends Error {
47
+ constructor(options?: {
48
+ cause?: unknown;
49
+ });
50
+ }
45
51
  export declare function createChatClient(options: CreateChatClientOptions): ChatClient;
@@ -179,6 +179,13 @@ const SEARCH_LIMIT_DEFAULT = 50;
179
179
  * no-op while `clientRunning` is still true, so a plain retry would never
180
180
  * resume syncing.
181
181
  */
182
+ /** Rejection of a `start()` that `stop()` overtook. */
183
+ export class ChatStartCancelledError extends Error {
184
+ constructor(options) {
185
+ super('chat: start cancelled by stop()', options);
186
+ this.name = 'ChatStartCancelledError';
187
+ }
188
+ }
182
189
  export function createChatClient(options) {
183
190
  const { exchangeUrl, getAccessToken, deviceId, storeName, encryptionEnabled } = options;
184
191
  let client;
@@ -208,6 +215,11 @@ export function createChatClient(options) {
208
215
  /** The account `secretStorageKeys` belongs to. */
209
216
  let secretStorageUserId;
210
217
  let starting;
218
+ // Bumped by `stop()`; a `start()` compares it after each await to learn it
219
+ // was overtaken. `teardown` settles once the last stop's store is destroyed.
220
+ let generation = 0;
221
+ let teardown = Promise.resolve();
222
+ const buildsInFlight = new Set();
211
223
  let refreshTimer;
212
224
  let recovering;
213
225
  let resyncing;
@@ -850,6 +862,14 @@ export function createChatClient(options) {
850
862
  for (const listener of timelineListeners.get(roomId) ?? [])
851
863
  listener();
852
864
  }
865
+ /** An event finished decrypting, or failed to: the row appears (or
866
+ * changes) without waiting for a sync. Removed with the client's other
867
+ * listeners by `removeAllListeners`. */
868
+ function onEventDecrypted(event) {
869
+ const roomId = event.getRoomId();
870
+ if (roomId)
871
+ notifyTimeline(roomId);
872
+ }
853
873
  /** `RoomEvent.Timeline` (a page landing, a new event arriving) and
854
874
  * `RoomEvent.LocalEchoUpdated` (an optimistic send's status changing) are
855
875
  * both re-emitted onto the client itself for every room (`sync.ts`'s
@@ -1004,19 +1024,30 @@ export function createChatClient(options) {
1004
1024
  * room's own state -- which is out of this ticket's scope (chat plan
1005
1025
  * section 9). */
1006
1026
  function toTimelineEvent(event, room, inThread) {
1007
- if (event.getType() !== EventType.RoomMessage)
1027
+ const encrypted = event.getWireType() === EventType.RoomMessageEncrypted;
1028
+ // Still decrypting: shown once `MatrixEventEvent.Decrypted` fires.
1029
+ if (encrypted && event.isBeingDecrypted())
1030
+ return undefined;
1031
+ const undecryptable = encrypted &&
1032
+ (event.isDecryptionFailure() || event.getType() === EventType.RoomMessageEncrypted);
1033
+ if (!undecryptable && event.getType() !== EventType.RoomMessage)
1008
1034
  return undefined;
1009
1035
  if (event.isRelation(RelationType.Replace))
1010
1036
  return undefined;
1037
+ if (event.isRelation(RelationType.Annotation))
1038
+ return undefined;
1011
1039
  const id = event.getId();
1012
1040
  const senderId = event.getSender();
1013
1041
  if (!id || !senderId)
1014
1042
  return undefined;
1015
1043
  const content = event.getContent();
1016
- const body = typeof content.body === 'string' ? content.body : '';
1017
- const formattedBody = content.format === 'org.matrix.custom.html' && typeof content.formatted_body === 'string'
1044
+ const body = !undecryptable && typeof content.body === 'string' ? content.body : '';
1045
+ const formattedBody = !undecryptable &&
1046
+ content.format === 'org.matrix.custom.html' &&
1047
+ typeof content.formatted_body === 'string'
1018
1048
  ? content.formatted_body
1019
1049
  : null;
1050
+ const via = content['com.wtfalch.via'];
1020
1051
  return {
1021
1052
  id,
1022
1053
  senderId,
@@ -1030,9 +1061,11 @@ export function createChatClient(options) {
1030
1061
  mentionsMe: mentionsMe(event),
1031
1062
  edited: event.replacingEventId() !== undefined,
1032
1063
  deleted: event.isRedacted(),
1033
- attachment: event.isRedacted() ? null : toAttachment(event),
1064
+ attachment: event.isRedacted() || undecryptable ? null : toAttachment(event),
1034
1065
  upload: null,
1035
1066
  mine: senderId === client?.getUserId(),
1067
+ viaAssistant: typeof via === 'string' && via !== '' ? via : null,
1068
+ undecryptable,
1036
1069
  };
1037
1070
  }
1038
1071
  /** `event.status` is `null`/`undefined` once the real event has replaced
@@ -1515,6 +1548,8 @@ export function createChatClient(options) {
1515
1548
  },
1516
1549
  upload: { loaded: upload.loaded, total: upload.file.size },
1517
1550
  mine: true,
1551
+ viaAssistant: null,
1552
+ undecryptable: false,
1518
1553
  };
1519
1554
  }
1520
1555
  function uploadRows(room, threadId) {
@@ -2184,6 +2219,7 @@ export function createChatClient(options) {
2184
2219
  async function swapClient(target, creds, wipeStore) {
2185
2220
  disposeClient(target);
2186
2221
  cryptoClosed = true;
2222
+ await destroyStore(target.store);
2187
2223
  let wiped = !wipeStore;
2188
2224
  let created;
2189
2225
  for (let delay = REBUILD_RETRY_MS; !created; delay = Math.min(delay * 2, REBUILD_RETRY_MAX_MS)) {
@@ -2193,7 +2229,26 @@ export function createChatClient(options) {
2193
2229
  if (!wiped)
2194
2230
  await target.store.deleteAllData();
2195
2231
  wiped = true;
2196
- created = await buildClient(creds);
2232
+ if (client !== target)
2233
+ return undefined;
2234
+ // Registered with `stop()`, which waits on it; a build `stop()`
2235
+ // overtook destroys its own store and answers `undefined`.
2236
+ const building = buildClient(creds).then(async (built) => {
2237
+ if (client !== target) {
2238
+ disposeClient(built);
2239
+ await destroyStore(built.store);
2240
+ return undefined;
2241
+ }
2242
+ return built;
2243
+ });
2244
+ const tracked = building.catch(() => undefined);
2245
+ buildsInFlight.add(tracked);
2246
+ try {
2247
+ created = await building;
2248
+ }
2249
+ finally {
2250
+ buildsInFlight.delete(tracked);
2251
+ }
2197
2252
  }
2198
2253
  catch {
2199
2254
  await new Promise((resolve) => setTimeout(resolve, delay));
@@ -2201,6 +2256,7 @@ export function createChatClient(options) {
2201
2256
  }
2202
2257
  if (client !== target) {
2203
2258
  disposeClient(created);
2259
+ await destroyStore(created.store);
2204
2260
  return undefined;
2205
2261
  }
2206
2262
  if (latestToken)
@@ -2214,6 +2270,15 @@ export function createChatClient(options) {
2214
2270
  target.stopClient();
2215
2271
  target.removeAllListeners();
2216
2272
  }
2273
+ /** Never rejects: a failed destroy is reported and teardown goes on. */
2274
+ async function destroyStore(store) {
2275
+ try {
2276
+ await store.destroy();
2277
+ }
2278
+ catch (error) {
2279
+ console.error('chat: store destroy failed', error);
2280
+ }
2281
+ }
2217
2282
  async function buildClient(creds) {
2218
2283
  if (secretStorageUserId !== creds.userId)
2219
2284
  secretStorageKeys.clear();
@@ -2238,9 +2303,15 @@ export function createChatClient(options) {
2238
2303
  },
2239
2304
  },
2240
2305
  });
2241
- if (encryptionEnabled)
2242
- await initCrypto(created);
2243
- await store.startup();
2306
+ try {
2307
+ if (encryptionEnabled)
2308
+ await initCrypto(created);
2309
+ await store.startup();
2310
+ }
2311
+ catch (error) {
2312
+ await destroyStore(store);
2313
+ throw error;
2314
+ }
2244
2315
  return created;
2245
2316
  }
2246
2317
  function attachListeners(created) {
@@ -2248,6 +2319,7 @@ export function createChatClient(options) {
2248
2319
  created.on(ClientEvent.Sync, onSync);
2249
2320
  created.on(RoomEvent.Timeline, onRoomTimelineChanged);
2250
2321
  created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
2322
+ created.on(MatrixEventEvent.Decrypted, onEventDecrypted);
2251
2323
  created.on(RoomEvent.Receipt, onRoomReceipt);
2252
2324
  created.on(RoomEvent.AccountData, watchForDraft);
2253
2325
  created.on(UserEvent.Presence, onUserPresence);
@@ -2280,8 +2352,16 @@ export function createChatClient(options) {
2280
2352
  async function start() {
2281
2353
  if (starting)
2282
2354
  return starting;
2355
+ const myGeneration = generation;
2356
+ const cancelled = () => generation !== myGeneration;
2283
2357
  const attempt = (async () => {
2358
+ // Never open the IndexedDB while the previous one is still closing.
2359
+ await teardown;
2360
+ if (cancelled())
2361
+ throw new ChatStartCancelledError();
2284
2362
  const body = await performExchange();
2363
+ if (cancelled())
2364
+ throw new ChatStartCancelledError();
2285
2365
  // Built before anything touches the outer closure's state (`client`,
2286
2366
  // the listeners, the refresh timer): a WASM fetch or a blocked
2287
2367
  // IndexedDB can throw inside `buildClient`, and `created` is still a
@@ -2291,12 +2371,38 @@ export function createChatClient(options) {
2291
2371
  // client exists, as `IndexedDBStore` requires (it needs
2292
2372
  // `setUserCreator`, which the client constructor calls, before it can
2293
2373
  // replay persisted `m.presence`).
2294
- const created = await buildClient({
2374
+ // `stop()` waits on `building`, which also destroys a store whose
2375
+ // start was overtaken.
2376
+ const building = buildClient({
2295
2377
  baseUrl: body.homeserver,
2296
2378
  userId: body.user_id,
2297
2379
  accessToken: body.access_token,
2298
2380
  deviceId: body.device_id,
2381
+ }).then(async (built) => {
2382
+ if (cancelled()) {
2383
+ disposeClient(built);
2384
+ await destroyStore(built.store);
2385
+ }
2386
+ return built;
2299
2387
  });
2388
+ const tracked = building.catch(() => undefined);
2389
+ buildsInFlight.add(tracked);
2390
+ let created;
2391
+ try {
2392
+ created = await building;
2393
+ }
2394
+ catch (error) {
2395
+ if (cancelled()) {
2396
+ console.error('chat: build failed after stop()', error);
2397
+ throw new ChatStartCancelledError({ cause: error });
2398
+ }
2399
+ throw error;
2400
+ }
2401
+ finally {
2402
+ buildsInFlight.delete(tracked);
2403
+ }
2404
+ if (cancelled())
2405
+ throw new ChatStartCancelledError();
2300
2406
  client = created;
2301
2407
  attachListeners(created);
2302
2408
  scheduleRefresh(body.expires_at);
@@ -2345,8 +2451,19 @@ export function createChatClient(options) {
2345
2451
  starting = undefined;
2346
2452
  clearTimeout(refreshTimer);
2347
2453
  refreshTimer = undefined;
2348
- if (client)
2349
- disposeClient(client);
2454
+ const stopped = client;
2455
+ if (stopped)
2456
+ disposeClient(stopped);
2457
+ generation += 1;
2458
+ const previous = teardown;
2459
+ const building = [...buildsInFlight];
2460
+ buildsInFlight.clear();
2461
+ teardown = (async () => {
2462
+ await previous;
2463
+ await Promise.all(building);
2464
+ if (stopped)
2465
+ await destroyStore(stopped.store);
2466
+ })();
2350
2467
  cryptoClosed = false;
2351
2468
  // A recovery still sleeping in `swapClient` must not make the next
2352
2469
  // client's recovery wait on it.
@@ -2354,6 +2471,7 @@ export function createChatClient(options) {
2354
2471
  resyncing = undefined;
2355
2472
  client = undefined;
2356
2473
  setStatus('offline');
2474
+ return teardown;
2357
2475
  }
2358
2476
  function onRoomsChanged(listener) {
2359
2477
  listeners.add(listener);
@@ -2550,10 +2668,20 @@ export function createChatClient(options) {
2550
2668
  void fetchAutomaticStatus(userId);
2551
2669
  try {
2552
2670
  const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2671
+ // A reply that lands after `stop()` or a client swap must not write;
2672
+ // the placeholder goes, so the next read fetches through the live client.
2673
+ if (client !== target) {
2674
+ if (chatStatusCache.get(userId) === null)
2675
+ chatStatusCache.delete(userId);
2676
+ return;
2677
+ }
2553
2678
  notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
2554
2679
  }
2555
2680
  catch {
2556
- notifyStatusChanged(userId, null);
2681
+ if (client === target)
2682
+ notifyStatusChanged(userId, null);
2683
+ else if (chatStatusCache.get(userId) === null)
2684
+ chatStatusCache.delete(userId);
2557
2685
  }
2558
2686
  }
2559
2687
  /** See `ChatClient.status`. Exported as `status` on the returned client
@@ -18,8 +18,17 @@ export async function exchange(exchangeUrl, getAccessToken, deviceId) {
18
18
  if (!response.ok) {
19
19
  let reason;
20
20
  try {
21
+ // The shared estate envelope (`@wtfalch/contracts`):
22
+ // `{ error: { code, message, reason? } }`. `reason`, when the
23
+ // service sent one, is the more specific of the two -- `code` is
24
+ // only the closed nine-value set.
21
25
  const problem = (await response.json());
22
- reason = typeof problem.reason === 'string' ? problem.reason : undefined;
26
+ reason =
27
+ typeof problem.error?.reason === 'string'
28
+ ? problem.error.reason
29
+ : typeof problem.error?.code === 'string'
30
+ ? problem.error.code
31
+ : undefined;
23
32
  }
24
33
  catch {
25
34
  // The body was not JSON, or was empty. The status is still enough to
@@ -6,5 +6,5 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from './client.ts';
9
+ export { ChatStartCancelledError, createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from './client.ts';
10
10
  export type { ChatAttachment, ChatBrowsableRoom, ChatNewRoom, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -6,4 +6,4 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from "./client.js";
9
+ export { ChatStartCancelledError, createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from "./client.js";
@@ -11,6 +11,9 @@ export type MessageRowProps = {
11
11
  /** The message the reader was sent here to find, marked so they can see
12
12
  * which one it is. */
13
13
  highlighted?: boolean;
14
+ /** Given, a locked message (one this client holds no key for) offers
15
+ * "Verify to read", and this is called on press. */
16
+ onVerify?: () => void;
14
17
  };
15
18
  /** One `m.room.message` event: sender, time, body, and -- pending or failed
16
19
  * -- its own optimistic-send state. `formatted_body` is a stranger's HTML,
@@ -18,4 +21,4 @@ export type MessageRowProps = {
18
21
  * ticket #15's safety requirement); plain `body` needs no such pass and is
19
22
  * drawn as text, with `chat.css`'s `white-space: pre-wrap` carrying its
20
23
  * own line breaks. */
21
- export declare function MessageRow({ event, client, roomId, onOpenThread, highlighted }: MessageRowProps): import("react").JSX.Element;
24
+ export declare function MessageRow({ event, client, roomId, onOpenThread, highlighted, onVerify, }: MessageRowProps): import("react").JSX.Element;
@@ -14,7 +14,7 @@ const QUICK_REACTIONS = ['👍', '🎉', '👀', '❤️', '😄', '🤔'];
14
14
  * ticket #15's safety requirement); plain `body` needs no such pass and is
15
15
  * drawn as text, with `chat.css`'s `white-space: pre-wrap` carrying its
16
16
  * own line breaks. */
17
- export function MessageRow({ event, client, roomId, onOpenThread, highlighted }) {
17
+ export function MessageRow({ event, client, roomId, onOpenThread, highlighted, onVerify, }) {
18
18
  const time = new Date(event.ts).toLocaleTimeString(undefined, {
19
19
  hour: 'numeric',
20
20
  minute: '2-digit',
@@ -32,7 +32,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
32
32
  /** Only your own, and only once it is really sent: Matrix ignores an
33
33
  * `m.replace` from anybody else, and an event still in flight has no id
34
34
  * on the server to replace or redact yet. */
35
- const own = event.mine && event.status === 'sent' && !event.deleted;
35
+ const own = event.mine && event.status === 'sent' && !event.deleted && !event.undecryptable;
36
36
  function react(key) {
37
37
  setPicking(false);
38
38
  client.toggleReaction(roomId, event.id, key).catch(() => {
@@ -41,7 +41,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
41
41
  // would be this component's own guess about a count it does not own.
42
42
  });
43
43
  }
44
- return (_jsxs("div", { className: `chat-message${event.status !== 'sent' ? ` is-${event.status}` : ''}${highlighted ? ' is-here' : ''}${event.mentionsMe ? ' is-mentioned' : ''}`, "data-event-id": event.id, "data-status": event.status, children: [_jsxs("div", { className: "chat-message-meta", children: [_jsx("span", { className: "chat-message-sender", children: event.senderName }), _jsx("time", { className: "chat-message-time", dateTime: new Date(event.ts).toISOString(), children: time }), event.edited && !event.deleted && _jsx("span", { className: "chat-message-edited", children: "edited" })] }), event.deleted ? (
44
+ return (_jsxs("div", { className: `chat-message${event.status !== 'sent' ? ` is-${event.status}` : ''}${highlighted ? ' is-here' : ''}${event.mentionsMe ? ' is-mentioned' : ''}`, "data-event-id": event.id, "data-status": event.status, children: [_jsxs("div", { className: "chat-message-meta", children: [_jsx("span", { className: "chat-message-sender", children: event.senderName }), _jsx("time", { className: "chat-message-time", dateTime: new Date(event.ts).toISOString(), children: time }), event.edited && !event.deleted && _jsx("span", { className: "chat-message-edited", children: "edited" })] }), event.undecryptable ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "chat-message-body is-undecryptable", children: "Locked message" }), onVerify && (_jsx(Button, { kind: "ghost", size: "sm", onPress: onVerify, children: "Verify to read" }))] })) : event.deleted ? (
45
45
  // The row stays where it was. Dropping it would move every message
46
46
  // under it while somebody is reading, and a thread hanging off this
47
47
  // one still has to have something to hang from.
@@ -56,7 +56,8 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
56
56
  dangerouslySetInnerHTML: { __html: html } })) : event.attachment ? (
57
57
  // A file names itself in its own row, so the body would say the
58
58
  // same thing twice.
59
- _jsx(AttachmentView, { attachment: event.attachment, client: client, roomId: roomId, upload: event.upload })) : (_jsx("div", { className: "chat-message-body", children: event.body })), (event.reactions.length > 0 || (event.status === 'sent' && !event.deleted)) && (_jsxs("div", { className: "chat-reactions", children: [event.reactions.map((reaction) => (_jsx(ReactionPill, { reaction: reaction, onPress: react }, reaction.key))), event.status === 'sent' && !event.deleted && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "chat-react", onClick: () => setPicking((open) => !open), "aria-expanded": picking, children: "React" }), picking && (_jsx("span", { className: "chat-react-choices", children: QUICK_REACTIONS.map((key) => (_jsx("button", { type: "button", className: "chat-react-choice", onClick: () => react(key), "aria-label": `React with ${key}`, children: key }, key))) }))] })), own && !editing && !confirmingDelete && (_jsxs(_Fragment, { children: [!event.attachment && (_jsx("button", { type: "button", className: "chat-react", onClick: () => setEditing(true), children: "Edit" })), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(true), children: "Delete" })] })), own && confirmingDelete && (
59
+ _jsx(AttachmentView, { attachment: event.attachment, client: client, roomId: roomId, upload: event.upload })) : (_jsx("div", { className: "chat-message-body", children: event.body })), !event.undecryptable &&
60
+ (event.reactions.length > 0 || (event.status === 'sent' && !event.deleted)) && (_jsxs("div", { className: "chat-reactions", children: [event.reactions.map((reaction) => (_jsx(ReactionPill, { reaction: reaction, onPress: react }, reaction.key))), event.status === 'sent' && !event.deleted && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "chat-react", onClick: () => setPicking((open) => !open), "aria-expanded": picking, children: "React" }), picking && (_jsx("span", { className: "chat-react-choices", children: QUICK_REACTIONS.map((key) => (_jsx("button", { type: "button", className: "chat-react-choice", onClick: () => react(key), "aria-label": `React with ${key}`, children: key }, key))) }))] })), own && !editing && !confirmingDelete && (_jsxs(_Fragment, { children: [!event.attachment && (_jsx("button", { type: "button", className: "chat-react", onClick: () => setEditing(true), children: "Edit" })), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(true), children: "Delete" })] })), own && confirmingDelete && (
60
61
  // Asked in the row rather than in a dialog: a redaction cannot
61
62
  // be taken back, and a browser dialog would take the whole
62
63
  // conversation away to ask one question.
@@ -66,6 +67,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
66
67
  // As above: the message stays, and sync says what is there.
67
68
  });
68
69
  }, children: "Delete" }), _jsx("button", { type: "button", className: "chat-react", onClick: () => setConfirmingDelete(false), children: "Keep" })] }))] })), onOpenThread &&
70
+ !event.undecryptable &&
69
71
  (event.thread ? (
70
72
  // Always drawn: a thread hanging off a message is something the
71
73
  // reader needs to know is there, not an action they have to go
@@ -268,6 +268,13 @@ export type ChatTimelineEvent = {
268
268
  * anybody but the original sender, and moderating other people's
269
269
  * messages is the manage app's (ticket #19's "not in this ticket"). */
270
270
  readonly mine: boolean;
271
+ /** The assistant's name when an assistant sent this message for a person
272
+ * (`com.wtfalch.via` in the event's content), `null` otherwise. */
273
+ readonly viaAssistant: string | null;
274
+ /** `true` for an encrypted event this client holds no key for. `body` is
275
+ * `''` and `formattedBody` and `attachment` are `null`. `false`
276
+ * otherwise. */
277
+ readonly undecryptable: boolean;
271
278
  };
272
279
  /** The rest of what a send can carry, beyond the text itself. */
273
280
  export type ChatSendOptions = {
@@ -367,8 +374,11 @@ export type ChatClient = {
367
374
  * it again while already started is a no-op. */
368
375
  start: () => Promise<void>;
369
376
  /** Stops syncing and releases the underlying Matrix client. Safe to call
370
- * more than once, and before `start()` ever resolves. */
371
- stop: () => void;
377
+ * more than once, and before `start()` ever resolves. The state change is
378
+ * immediate; the promise settles once any in-flight store startup has
379
+ * finished and the store is destroyed. It never rejects. A `start()` that
380
+ * this overtakes rejects with `ChatStartCancelledError`. */
381
+ stop: () => Promise<void>;
372
382
  /** The rooms the person is currently in. Empty before `start()` resolves. */
373
383
  rooms: () => ChatRoomSummary[];
374
384
  /** Called with the current room list whenever it changes. Returns a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,10 +21,6 @@
21
21
  "types": "./dist/chat/react/index.d.ts",
22
22
  "default": "./dist/chat/react/index.js"
23
23
  },
24
- "./fake": {
25
- "types": "./dist/chat/fake/index.d.ts",
26
- "default": "./dist/chat/fake/index.js"
27
- },
28
24
  "./chat.css": "./dist/chat/chat.css",
29
25
  "./package.json": "./package.json",
30
26
  "./admin": {
@@ -48,7 +44,7 @@
48
44
  "test:acceptance": "vitest run --config vitest.acceptance.config.ts"
49
45
  },
50
46
  "peerDependencies": {
51
- "@wtfalch/design": ">=0.28.0 <0.31.0",
47
+ "@wtfalch/design": ">=0.30.0 <0.32.0",
52
48
  "react": "^19.0.0",
53
49
  "react-dom": "^19.0.0"
54
50
  },
@@ -69,7 +65,7 @@
69
65
  "@types/node": "22.20.2",
70
66
  "@types/react": "19.3.0",
71
67
  "@types/react-dom": "19.3.0",
72
- "@wtfalch/design": "0.30.0",
68
+ "@wtfalch/design": "0.31.0",
73
69
  "fake-indexeddb": "6.2.5",
74
70
  "jsdom": "30.0.1",
75
71
  "react": "19.2.4",
@@ -1,27 +0,0 @@
1
- import type { ChatClient } from '../types.ts';
2
- import { FakeChatServer, type FakeChatServerOptions } from './server.ts';
3
- export { FakeChatServer } from './server.ts';
4
- export type { FakeChatServerOptions, FakeHierarchyChild, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
5
- export { SAMPLE_ROOMS } from './sample.ts';
6
- export type FakeChatOptions = FakeChatServerOptions & {
7
- storeName?: string;
8
- deviceId?: string;
9
- };
10
- export type FakeChat = {
11
- /** A real `ChatClient`. Everything this package exports works against it
12
- * unchanged, through the real `createChatClient`. */
13
- client: ChatClient;
14
- /** The homeserver behind it, to drive more rooms or a token refusal, or
15
- * to assert on how many times the exchange was called. */
16
- server: FakeChatServer;
17
- /** Stops the client and uninstalls the fake. Call it when a story or a
18
- * test is done. */
19
- dispose: () => void;
20
- };
21
- /**
22
- * A client and the fake exchange/homeserver behind it.
23
- *
24
- * Seeded with `SAMPLE_ROOMS` unless told otherwise, because a fake with no
25
- * rooms demonstrates the empty state and nothing else.
26
- */
27
- export declare function fakeChat(options?: FakeChatOptions): FakeChat;
@@ -1,48 +0,0 @@
1
- /**
2
- * `@wtfalch/chat/fake` -- a real `createChatClient`, wired to a
3
- * fake exchange and a fake homeserver instead of the network, for stories
4
- * and tests. See `server.ts`'s module comment for why it fakes the
5
- * transport rather than the client.
6
- *
7
- * ```ts
8
- * import { fakeChat } from '@wtfalch/chat/fake'
9
- *
10
- * const { client, dispose } = fakeChat()
11
- * await client.start()
12
- * client.rooms() // SAMPLE_ROOMS, joined
13
- * dispose()
14
- * ```
15
- */
16
- import { createChatClient } from "../client.js";
17
- import { SAMPLE_ROOMS } from "./sample.js";
18
- import { FakeChatServer } from "./server.js";
19
- export { FakeChatServer } from "./server.js";
20
- export { SAMPLE_ROOMS } from "./sample.js";
21
- /**
22
- * A client and the fake exchange/homeserver behind it.
23
- *
24
- * Seeded with `SAMPLE_ROOMS` unless told otherwise, because a fake with no
25
- * rooms demonstrates the empty state and nothing else.
26
- */
27
- export function fakeChat(options = {}) {
28
- const { storeName, deviceId, ...serverOptions } = options;
29
- const server = new FakeChatServer({ rooms: SAMPLE_ROOMS, ...serverOptions });
30
- const client = createChatClient({
31
- exchangeUrl: server.exchangeUrl,
32
- getAccessToken: () => 'fake-zitadel-token',
33
- deviceId: deviceId ?? 'fake-device',
34
- storeName: storeName ?? 'fake',
35
- });
36
- let disposed = false;
37
- return {
38
- client,
39
- server,
40
- dispose: () => {
41
- if (disposed)
42
- return;
43
- disposed = true;
44
- client.stop();
45
- server.dispose();
46
- },
47
- };
48
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Global `fetch` interception, shared by every `FakeChatServer`.
3
- *
4
- * **A fake transport, not a fake API** -- the same choice `@wtfalch/email`'s
5
- * `fakeMail()` makes. `createChatClient` and matrix-js-sdk run unchanged; only
6
- * the network is answered by memory instead of a real homeserver.
7
- *
8
- * Unlike a single captured `route` callback, this keeps a list: two fakes --
9
- * two companies' homeservers -- can be installed at once, each answering only
10
- * its own origin and falling through to the next. The real `fetch` is
11
- * restored once the last one is disposed.
12
- */
13
- export type FetchRoute = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> | null;
14
- /** Registers `route`. Returns a function that unregisters it.
15
- *
16
- * `globalThis.fetch` stays patched once the first route is installed, and
17
- * is never put back: a request made to a disposed fake is still in flight
18
- * when its route goes, and restoring the real `fetch` underneath it sends
19
- * that request to DNS. Everything but a `.example.test` host goes straight
20
- * through to the real `fetch` either way, so nothing else is affected. */
21
- export declare function installFetchRoute(route: FetchRoute): () => void;