@wtfalch/chat 0.5.0 → 0.6.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.
@@ -1,7 +1,7 @@
1
- import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
1
+ import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEvent, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
2
2
  import { exchange } from "./exchange.js";
3
3
  import { toFormattedBody } from "./markdown.js";
4
- import { createChatStore } from "./store.js";
4
+ import { createChatStore, cryptoStoreDbPrefix, purgeStaleChatStores } from "./store.js";
5
5
  /** A Matrix token never outlives the ZITADEL token it was swapped for (see
6
6
  * the chat plan section 4), and Synapse's own introspection cache is only
7
7
  * good for two minutes -- so a minute of headroom before `expires_at` is
@@ -12,11 +12,48 @@ const REFRESH_MARGIN_MS = 60_000;
12
12
  * margin above, so a client that cannot refresh keeps trying while the
13
13
  * token it holds is still good. */
14
14
  const REFRESH_RETRY_MS = 5_000;
15
+ /** First and longest wait between attempts to rebuild a client whose crypto
16
+ * failed to come up during a recovery (`swapClient`). */
17
+ const REBUILD_RETRY_MS = 1_000;
18
+ const REBUILD_RETRY_MAX_MS = 30_000;
19
+ /** The custom `m.room.member` content key `readGuest` looks for, carrying
20
+ * `{ until }` -- see `docs/guests.md`, "What the SDK shows", and
21
+ * `ChatPerson.guest`. Nothing writes it yet, and nothing should until the
22
+ * chat-service half is designed: review on #73 found that a member's own
23
+ * join event replaces an invite's content wholesale, so a marker
24
+ * `@chat-admin` set on the invite does not survive the guest's own accept,
25
+ * and in the meantime this key is as writable as a display name -- any
26
+ * member could set or clear it on themselves. A trustworthy marker needs
27
+ * the chat service's grant list as source of truth, read through an
28
+ * authenticated route, not a field on event content the room's own
29
+ * members control. This constant and `readGuest` are the one place that
30
+ * changes once that lands. */
31
+ const GUEST_MARKER_KEY = 'dev.wtfalch.chat.guest';
15
32
  /** The room tag that takes a direct room out of the sidebar. A tag, not a
16
33
  * leave: the person stays joined, so the room's history is exactly where
17
34
  * they left it when the DM is reopened (ticket #16). Namespaced, as the
18
35
  * Matrix spec requires of any tag outside `m.` and `u.`. */
19
36
  const HIDDEN_TAG = 'com.wtfalch.hidden';
37
+ /** The pre-merge key for MSC2867's marked-unread flag. `markRoomUnread`
38
+ * writes it alongside the now-stable `m.marked_unread` (`EventType.
39
+ * MarkedUnread`) so a client that has not caught up to the merged MSC
40
+ * still reads the flag; `isMarkedUnread` falls back to it for the same
41
+ * reason. Not in matrix-js-sdk's `RoomAccountDataEvents` map -- it only
42
+ * knows the stable key -- so it is written the same way `reportMessage`
43
+ * reaches an endpoint the typed client has no wrapper for: by hand. */
44
+ const FAMEDLY_MARKED_UNREAD = 'com.famedly.marked_unread';
45
+ /** The room account data type a draft is stored under -- namespaced the
46
+ * same way `HIDDEN_TAG` namespaces this package's custom room tag. See
47
+ * `ChatClient.getDraft`. */
48
+ const DRAFT_EVENT_TYPE = 'com.wtfalch.draft';
49
+ /** The Matrix spec's own tag for a starred room -- `starRoom` writes and
50
+ * deletes it exactly as `hideDirectMessage` does `HIDDEN_TAG`, and
51
+ * `readRooms()` reads it the same way (agora#27). */
52
+ const FAVOURITE_TAG = 'm.favourite';
53
+ /** The MSC4133 extended-profile key `setOwnStatus` writes and `personStatus`
54
+ * reads -- namespaced the same way `HIDDEN_TAG` and `DRAFT_EVENT_TYPE` are.
55
+ * See `ChatClient.status` and `docs/status.md`. */
56
+ const STATUS_PROFILE_KEY = 'com.wtfalch.status';
20
57
  /** Every `startClient()` in this file passes these, including the two
21
58
  * recoveries: a restart that dropped `threadSupport` would quietly put
22
59
  * every later thread reply back into the room's own timeline. */
@@ -39,6 +76,15 @@ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
39
76
  url.searchParams.set('eventId', eventId);
40
77
  return url.toString();
41
78
  }
79
+ /** Where a thread's follow state lives: `apps/chat-service`'s
80
+ * `/_chat/threads/...`, next to `exchangeUrl` like the media proxy. */
81
+ function threadFollowUrl(exchangeUrl, roomId, threadId) {
82
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
83
+ return `${base}/_chat/threads/${encodeURIComponent(roomId)}/${encodeURIComponent(threadId)}/follow`;
84
+ }
85
+ function setDraftAccountData(target, roomId, content) {
86
+ return target.setRoomAccountData(roomId, DRAFT_EVENT_TYPE, content);
87
+ }
42
88
  /** What `sendTyping` asks the server to auto-expire a typing state after,
43
89
  * in ms -- matrix-js-sdk's own default when a caller passes none
44
90
  * (`client.js`'s `sendTyping`), used explicitly here since this package's
@@ -62,13 +108,21 @@ const SEARCH_LIMIT_DEFAULT = 50;
62
108
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
63
109
  * caller never sees, refreshed on its own, exposing only what a UI needs.
64
110
  *
65
- * **Crypto stays off.** Encryption is not in the first ship (chat plan
66
- * section 6), so this never calls `initRustCrypto()`. matrix-js-sdk only
67
- * imports its Rust crypto WASM when that is called (`client.js`: "importing
68
- * rust-crypto will download the webassembly, so we delay it until we know
69
- * it will be [needed]") -- so skipping it means the WASM module is never
70
- * loaded, in the browser or under vitest. No shim or polyfill for it is
71
- * needed either way.
111
+ * **Crypto stays off unless asked for.** `encryptionEnabled` gates a call
112
+ * to `initRustCrypto()`, made once, right after the `MatrixClient` exists
113
+ * and before anything else touches this closure's own state -- key
114
+ * backup, recovery key and device verification (chat#67-69) all need a
115
+ * running `CryptoApi` (`getCrypto()`) to build against. Omitted or
116
+ * `false`, this behaves exactly as it always has and never calls it at
117
+ * all: matrix-js-sdk only imports its Rust crypto WASM when
118
+ * `initRustCrypto()` is called (`client.js`: "importing rust-crypto will
119
+ * download the webassembly, so we delay it until we know it will be
120
+ * [needed]") -- so skipping it means the WASM module is never loaded, in
121
+ * the browser or under vitest. No shim or polyfill for it is needed
122
+ * either way. Its own store, bound to the exchanged identity the same
123
+ * tuple `createChatStore` binds the sync one to (`cryptoStoreDbPrefix`) --
124
+ * without that, matrix-js-sdk's fixed default name is shared by every
125
+ * client in the browser (chat#71 review).
72
126
  *
73
127
  * **Refresh, not a Matrix refresh token.** There is no such thing (section
74
128
  * 4): a near-expiry timer and a `Session.logged_out` listener (fired by
@@ -82,8 +136,11 @@ const SEARCH_LIMIT_DEFAULT = 50;
82
136
  * resume syncing.
83
137
  */
84
138
  export function createChatClient(options) {
85
- const { exchangeUrl, getAccessToken, deviceId, storeName } = options;
139
+ const { exchangeUrl, getAccessToken, deviceId, storeName, encryptionEnabled } = options;
86
140
  let client;
141
+ /** True while `swapClient` has disposed `client` and not yet replaced it:
142
+ * its crypto is closed, so `getCrypto()` must not hand it out. */
143
+ let cryptoClosed = false;
87
144
  let starting;
88
145
  let refreshTimer;
89
146
  let recovering;
@@ -99,6 +156,13 @@ export function createChatClient(options) {
99
156
  const statusListeners = new Set();
100
157
  const presenceListeners = new Set();
101
158
  const typingListeners = new Map();
159
+ /** See `ChatClient.status`. A `userId` missing from this map has never
160
+ * been asked about; `personStatus` uses that (not the value once
161
+ * present) to decide whether to start a fetch, so a placeholder `null`
162
+ * written the moment a fetch starts never triggers a second one while
163
+ * the first is still in flight. */
164
+ const chatStatusCache = new Map();
165
+ const chatStatusListeners = new Set();
102
166
  /** Who is currently typing, per room -- built up from `RoomMemberEvent.
103
167
  * Typing` one member at a time, the signed-in person's own id never
104
168
  * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
@@ -124,8 +188,14 @@ export function createChatClient(options) {
124
188
  * have agreed again -- an unmute alone is not that proof. Every other
125
189
  * room never pays for the walk at all. */
126
190
  const unreliableServerCount = new Set();
191
+ /** The newest token any exchange returned. `buildClient` reads it, so a
192
+ * client rebuilt after a refresh that landed on its disposed predecessor
193
+ * still starts on the current token. */
194
+ let latestToken;
127
195
  async function performExchange() {
128
- return exchange(exchangeUrl, getAccessToken, deviceId);
196
+ const body = await exchange(exchangeUrl, getAccessToken, deviceId);
197
+ latestToken = body.access_token;
198
+ return body;
129
199
  }
130
200
  /** A failed proactive refresh must not end proactive refreshing: nothing
131
201
  * else re-arms this timer, so without the retry the client would go
@@ -205,23 +275,37 @@ export function createChatClient(options) {
205
275
  async function recoverFromRefusedPosition() {
206
276
  if (resyncing)
207
277
  return resyncing;
278
+ if (encryptionEnabled && recovering)
279
+ return recovering;
208
280
  const target = client;
209
281
  if (!target)
210
282
  return;
211
- resyncing = (async () => {
212
- target.stopClient();
213
- await target.store.deleteAllData();
214
- const outcome = nextSyncOutcome(target);
215
- await target.startClient(START_OPTIONS);
216
- reapplyAnnouncedPresence(target);
283
+ const run = (async () => {
284
+ const created = await restartClient(target, {
285
+ baseUrl: target.baseUrl,
286
+ userId: target.getUserId() ?? '',
287
+ accessToken: target.getAccessToken() ?? '',
288
+ deviceId: target.getDeviceId() ?? '',
289
+ }, true);
290
+ if (!created)
291
+ return;
292
+ const outcome = nextSyncOutcome(created);
293
+ await created.startClient(START_OPTIONS);
294
+ if (client !== created)
295
+ return;
296
+ reapplyAnnouncedPresence(created);
217
297
  await outcome;
298
+ if (client !== created)
299
+ return;
218
300
  notify();
219
301
  })();
302
+ resyncing = run;
220
303
  try {
221
- await resyncing;
304
+ await run;
222
305
  }
223
306
  finally {
224
- resyncing = undefined;
307
+ if (resyncing === run)
308
+ resyncing = undefined;
225
309
  }
226
310
  }
227
311
  /** Waits for the next sync to either land or fail, so callers can await a
@@ -260,25 +344,41 @@ export function createChatClient(options) {
260
344
  async function recoverFromLoggedOut() {
261
345
  if (recovering)
262
346
  return recovering;
347
+ if (encryptionEnabled && resyncing)
348
+ return resyncing;
263
349
  const target = client;
264
350
  if (!target)
265
351
  return;
266
- recovering = (async () => {
352
+ const run = (async () => {
267
353
  const body = await performExchange();
268
- target.stopClient();
269
- target.setAccessToken(body.access_token);
354
+ if (client !== target)
355
+ return;
356
+ const created = await restartClient(target, {
357
+ baseUrl: body.homeserver,
358
+ userId: body.user_id,
359
+ accessToken: body.access_token,
360
+ deviceId: body.device_id,
361
+ }, false);
362
+ if (!created)
363
+ return;
270
364
  scheduleRefresh(body.expires_at);
271
- const outcome = nextSyncOutcome(target);
272
- await target.startClient(START_OPTIONS);
273
- reapplyAnnouncedPresence(target);
365
+ const outcome = nextSyncOutcome(created);
366
+ await created.startClient(START_OPTIONS);
367
+ if (client !== created)
368
+ return;
369
+ reapplyAnnouncedPresence(created);
274
370
  await outcome;
371
+ if (client !== created)
372
+ return;
275
373
  notify();
276
374
  })();
375
+ recovering = run;
277
376
  try {
278
- await recovering;
377
+ await run;
279
378
  }
280
379
  finally {
281
- recovering = undefined;
380
+ if (recovering === run)
381
+ recovering = undefined;
282
382
  }
283
383
  }
284
384
  /** matrix-js-sdk only emits this for `M_UNKNOWN_TOKEN` (`http-api/fetch.ts`),
@@ -339,7 +439,15 @@ export function createChatClient(options) {
339
439
  isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
340
440
  membership,
341
441
  unreadCount: membership === 'invite' ? 1 : roomUnreadCount(target, room, muted),
442
+ // No invite-state equivalent of a highlight to read -- an
443
+ // unanswered invitation is never "mentioned", only invited.
444
+ mentionCount: membership === 'invite'
445
+ ? 0
446
+ : room.getUnreadNotificationCount(NotificationCountType.Highlight),
342
447
  muted,
448
+ markedUnread: isMarkedUnread(room),
449
+ archived: roomArchived(room),
450
+ starred: FAVOURITE_TAG in room.tags,
343
451
  };
344
452
  });
345
453
  }
@@ -388,6 +496,18 @@ export function createChatClient(options) {
388
496
  const rule = target.pushRules && target.getRoomPushRule('global', roomId);
389
497
  return Boolean(rule?.actions.includes(PushRuleActionName.DontNotify));
390
498
  }
499
+ /** See `ChatRoomSummary.markedUnread`. Reads the stable `m.marked_unread`
500
+ * key first and only falls back to the pre-merge `com.famedly.marked_
501
+ * unread` one when the stable key is entirely absent -- `markRoomUnread`
502
+ * always writes both together, so the two disagreeing means only a
503
+ * client that predates this package wrote the legacy key alone. */
504
+ function isMarkedUnread(room) {
505
+ const stable = room.getAccountData(EventType.MarkedUnread)?.getContent();
506
+ if (stable)
507
+ return Boolean(stable.unread);
508
+ const legacy = room.getAccountData(FAMEDLY_MARKED_UNREAD)?.getContent();
509
+ return Boolean(legacy?.unread);
510
+ }
391
511
  /** A muted room's own `unreadCount`, counted here rather than read off
392
512
  * Synapse. Confirmed live against Synapse v1.161.0: the room-scoped
393
513
  * `dont_notify` rule `muteRoom` writes does not merely withhold the
@@ -429,23 +549,44 @@ export function createChatClient(options) {
429
549
  .getRooms()
430
550
  .find((room) => room.isSpaceRoom() && room.getMyMembership() === KnownMembership.Join);
431
551
  }
552
+ /** `GUEST_MARKER_KEY` off `member`'s own `m.room.member` event, if
553
+ * chat-service marked one -- see `ChatPerson.guest`. */
554
+ function readGuest(member) {
555
+ const marker = member.events.member?.getContent()[GUEST_MARKER_KEY];
556
+ return typeof marker?.until === 'string' ? { until: marker.until } : undefined;
557
+ }
432
558
  function toPerson(member) {
433
- return { userId: member.userId, name: member.name };
559
+ const guest = readGuest(member);
560
+ return { userId: member.userId, name: member.name, ...(guest ? { guest } : {}) };
434
561
  }
435
- /** Everyone in the company space but the signed-in person. Guests are not
436
- * in the space, so this cannot offer one -- see `ChatPerson`. */
562
+ /** Everyone in the company space but the signed-in person, plus every
563
+ * guest sharing a joined room with them -- see `ChatClient.people`. A
564
+ * guest is never in the space, so the second half is the only way one is
565
+ * ever offered here. */
437
566
  function readPeople() {
438
567
  if (!client)
439
568
  return [];
440
- const space = companySpace(client);
441
- if (!space)
442
- return [];
443
569
  const me = client.getUserId();
444
- return space
445
- .getMembersWithMembership(KnownMembership.Join)
446
- .filter((member) => member.userId !== me)
447
- .map(toPerson)
448
- .sort((a, b) => a.name.localeCompare(b.name));
570
+ const people = new Map();
571
+ const space = companySpace(client);
572
+ if (space) {
573
+ for (const member of space.getMembersWithMembership(KnownMembership.Join)) {
574
+ if (member.userId !== me)
575
+ people.set(member.userId, toPerson(member));
576
+ }
577
+ }
578
+ for (const room of client.getRooms()) {
579
+ if (room.isSpaceRoom() || room.getMyMembership() !== KnownMembership.Join)
580
+ continue;
581
+ for (const member of room.getMembersWithMembership(KnownMembership.Join)) {
582
+ if (member.userId === me || people.has(member.userId))
583
+ continue;
584
+ const person = toPerson(member);
585
+ if (person.guest)
586
+ people.set(member.userId, person);
587
+ }
588
+ }
589
+ return [...people.values()].sort((a, b) => a.name.localeCompare(b.name));
449
590
  }
450
591
  /** Who else is in a room, joined or still invited -- an invitee counts,
451
592
  * or a DM started a second ago would not be found as an existing one
@@ -1056,7 +1197,13 @@ export function createChatClient(options) {
1056
1197
  // `threadId ?? null` rather than the two-argument overload: passing the
1057
1198
  // thread's root id is what makes the reply relate to the *root*, which
1058
1199
  // is the only shape Matrix has -- there is no replying to a reply.
1059
- client.sendMessage(roomId, threadId ?? null, content).catch(() => {
1200
+ client
1201
+ .sendMessage(roomId, threadId ?? null, content)
1202
+ .then(() => {
1203
+ if (threadId)
1204
+ autoFollowThread(roomId, threadId);
1205
+ })
1206
+ .catch(() => {
1060
1207
  // The failure already lives on the event's own status (`NOT_SENT`);
1061
1208
  // a caller reads that through `timeline()`, not this promise.
1062
1209
  });
@@ -1225,7 +1372,16 @@ export function createChatClient(options) {
1225
1372
  // it is an ordinary message: a send that fails is retried and
1226
1373
  // cancelled through the event, with the bytes already up.
1227
1374
  dropUpload(roomId, pending.id);
1228
- void target.sendMessage(roomId, pending.threadId, content).catch(() => { });
1375
+ const threadId = pending.threadId;
1376
+ // A file sent into a thread is a reply, so it follows the thread
1377
+ // just as `sendMessage` does, once it is sent.
1378
+ void target
1379
+ .sendMessage(roomId, threadId, content)
1380
+ .then(() => {
1381
+ if (threadId)
1382
+ autoFollowThread(roomId, threadId);
1383
+ })
1384
+ .catch(() => { });
1229
1385
  })
1230
1386
  .catch(() => {
1231
1387
  if (pending.abort.signal.aborted)
@@ -1385,6 +1541,16 @@ export function createChatClient(options) {
1385
1541
  * matrix-js-sdk's own current state -- there is no higher-level helper
1386
1542
  * for it the way `room.name` is one for `m.room.name`. `[]` for a room
1387
1543
  * with no such state at all, which is every room until the first pin. */
1544
+ /** Whether the room's `m.room.power_levels` has locked member writes --
1545
+ * the same `events_default >= 100` test `apps/chat-service/src/manage.ts`
1546
+ * uses for `AdminChannel.archived`, read straight off matrix-js-sdk's own
1547
+ * current state the same way `pinnedEventIds` reads pinned events. */
1548
+ function roomArchived(room) {
1549
+ const eventsDefault = room.currentState
1550
+ .getStateEvents(EventType.RoomPowerLevels, '')
1551
+ ?.getContent()?.events_default;
1552
+ return Number(eventsDefault ?? 0) >= 100;
1553
+ }
1388
1554
  function pinnedEventIds(room) {
1389
1555
  const content = room.currentState
1390
1556
  .getStateEvents(EventType.RoomPinnedEvents, '')
@@ -1420,6 +1586,26 @@ export function createChatClient(options) {
1420
1586
  return;
1421
1587
  pinnedKnown.set(room.roomId, pinned.filter((id) => typeof id === 'string'));
1422
1588
  }
1589
+ /** This client's own current draft per room -- not a cache with a
1590
+ * lifetime, kept current two ways: a successful `setDraft`/`clearDraft`
1591
+ * updates it immediately, and `watchForDraft` updates it the moment the
1592
+ * account data lands through `/sync`, this client's own echo or
1593
+ * another device's -- the same two-way pattern `pinnedKnown` keeps for
1594
+ * `m.room.pinned_events`. Absent for a room whose draft this client has
1595
+ * not seen; `getDraft` reads that as `''`. */
1596
+ const drafts = new Map();
1597
+ /** Keeps `drafts` current with whatever this client has actually seen
1598
+ * land -- this client's own echo, or another device's -- registered
1599
+ * directly against `RoomEvent.AccountData` rather than folded into
1600
+ * `onRoomTimelineChanged`: a draft is account data, not a timeline
1601
+ * event, and fires on its own event. */
1602
+ function watchForDraft(event, room) {
1603
+ if (event.getType() !== DRAFT_EVENT_TYPE)
1604
+ return;
1605
+ const text = event.getContent().text;
1606
+ drafts.set(room.roomId, text ?? '');
1607
+ notifyTimeline(room.roomId);
1608
+ }
1423
1609
  /** Queues one read-modify-write of `room`'s `m.room.pinned_events`
1424
1610
  * behind whatever `pinMessage`/`unpinMessage` already have in flight
1425
1611
  * for it, so `await pinMessage(a); await pinMessage(b);` -- or even
@@ -1511,6 +1697,31 @@ export function createChatClient(options) {
1511
1697
  }
1512
1698
  return events;
1513
1699
  }
1700
+ /** See `ChatClient.getDraft`. */
1701
+ function getDraft(roomId) {
1702
+ return drafts.get(roomId) ?? '';
1703
+ }
1704
+ /** See `ChatClient.setDraft`. */
1705
+ async function setDraft(roomId, text) {
1706
+ if (!client)
1707
+ return;
1708
+ const target = client;
1709
+ if (!target.getRoom(roomId))
1710
+ return;
1711
+ drafts.set(roomId, text);
1712
+ await setDraftAccountData(target, roomId, { text });
1713
+ }
1714
+ /** See `ChatClient.clearDraft`. Writes `{}`, the same empty shape
1715
+ * `hideDirectMessage` writes to clear a room tag. */
1716
+ async function clearDraft(roomId) {
1717
+ if (!client)
1718
+ return;
1719
+ const target = client;
1720
+ if (!target.getRoom(roomId))
1721
+ return;
1722
+ drafts.set(roomId, '');
1723
+ await setDraftAccountData(target, roomId, {});
1724
+ }
1514
1725
  function readUpToEventId(roomId) {
1515
1726
  const room = client?.getRoom(roomId);
1516
1727
  const userId = client?.getUserId();
@@ -1533,6 +1744,73 @@ export function createChatClient(options) {
1533
1744
  ? { serverName, mediaId }
1534
1745
  : undefined;
1535
1746
  }
1747
+ /** One call to the thread follow route, refreshing the token once on a
1748
+ * 401 like `loadMedia` does. Resolves with whether the person now
1749
+ * follows the thread; rejects when the service refuses. */
1750
+ async function threadFollowRequest(method, roomId, threadId, body) {
1751
+ if (!client)
1752
+ throw new Error('chat: thread follow called before start()');
1753
+ const target = client;
1754
+ const url = threadFollowUrl(exchangeUrl, roomId, threadId);
1755
+ const request = () => fetch(url, {
1756
+ method,
1757
+ headers: {
1758
+ Authorization: `Bearer ${target.getAccessToken() ?? ''}`,
1759
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
1760
+ },
1761
+ body: body ? JSON.stringify(body) : undefined,
1762
+ redirect: 'error',
1763
+ credentials: 'omit',
1764
+ });
1765
+ let response = await request();
1766
+ if (response.status === 401 && client === target) {
1767
+ await refreshToken();
1768
+ response = await request();
1769
+ }
1770
+ if (!response.ok)
1771
+ throw new Error(`chat: thread follow refused: ${response.status}`);
1772
+ return (await response.json()).following === true;
1773
+ }
1774
+ /** `onThreadFollowChanged` listeners, by `roomId threadId`. */
1775
+ const threadFollowListeners = new Map();
1776
+ function notifyThreadFollow(roomId, threadId, following) {
1777
+ for (const listener of threadFollowListeners.get(`${roomId} ${threadId}`) ?? []) {
1778
+ listener(following);
1779
+ }
1780
+ }
1781
+ /** See `ChatClient.onThreadFollowChanged`. */
1782
+ function onThreadFollowChanged(roomId, threadId, listener) {
1783
+ const key = `${roomId} ${threadId}`;
1784
+ let set = threadFollowListeners.get(key);
1785
+ if (!set) {
1786
+ set = new Set();
1787
+ threadFollowListeners.set(key, set);
1788
+ }
1789
+ set.add(listener);
1790
+ return () => {
1791
+ set.delete(listener);
1792
+ };
1793
+ }
1794
+ /** Posting in a thread follows it, once the post is sent. Best effort: a
1795
+ * failed follow loses nothing the person wrote, and the thread's Follow
1796
+ * control still works. */
1797
+ function autoFollowThread(roomId, threadId) {
1798
+ threadFollowRequest('PUT', roomId, threadId, { auto: true })
1799
+ .then((following) => notifyThreadFollow(roomId, threadId, following))
1800
+ .catch(() => { });
1801
+ }
1802
+ /** See `ChatClient.threadFollowing`. */
1803
+ function threadFollowing(roomId, threadId) {
1804
+ return threadFollowRequest('GET', roomId, threadId);
1805
+ }
1806
+ /** See `ChatClient.followThread`. */
1807
+ async function followThread(roomId, threadId) {
1808
+ await threadFollowRequest('PUT', roomId, threadId);
1809
+ }
1810
+ /** See `ChatClient.unfollowThread`. */
1811
+ async function unfollowThread(roomId, threadId) {
1812
+ await threadFollowRequest('DELETE', roomId, threadId);
1813
+ }
1536
1814
  /** See `ChatClient.canLoadMedia`. */
1537
1815
  function canLoadMedia(mxcUri) {
1538
1816
  return parseMxc(mxcUri) !== undefined;
@@ -1601,46 +1879,113 @@ export function createChatClient(options) {
1601
1879
  isImage: msgtype === MsgType.Image && mimeType.startsWith('image/'),
1602
1880
  };
1603
1881
  }
1882
+ /** Restarts `target` for a recovery, returning the client that is now
1883
+ * live, or `undefined` when `stop()` or another start replaced `target`
1884
+ * meanwhile. Without encryption it is the same client, restarted by the
1885
+ * caller: nothing here is lost, and the rooms keep their pending and
1886
+ * local-echo events. With encryption it is a fresh client, because
1887
+ * matrix-js-sdk cannot bring crypto back on a stopped one --
1888
+ * `initRustCrypto` binds listeners that outlive the freed OlmMachine --
1889
+ * and a rebuild drops those pending events, so only crypto pays for it. */
1890
+ async function restartClient(target, creds, wipeStore) {
1891
+ if (!encryptionEnabled) {
1892
+ target.stopClient();
1893
+ target.setAccessToken(creds.accessToken);
1894
+ if (wipeStore)
1895
+ await target.store.deleteAllData();
1896
+ return client === target ? target : undefined;
1897
+ }
1898
+ return swapClient(target, creds, wipeStore);
1899
+ }
1900
+ /** The old client is disposed before the new one is built, so two
1901
+ * OlmMachines never share one crypto store. A failed build (WASM fetch,
1902
+ * blocked IndexedDB) is retried with a growing delay until it works or
1903
+ * `stop()` lands: nothing else would restart a client whose listeners
1904
+ * are gone. `getCrypto()` answers `undefined` meanwhile. */
1905
+ async function swapClient(target, creds, wipeStore) {
1906
+ disposeClient(target);
1907
+ cryptoClosed = true;
1908
+ let wiped = !wipeStore;
1909
+ let created;
1910
+ for (let delay = REBUILD_RETRY_MS; !created; delay = Math.min(delay * 2, REBUILD_RETRY_MAX_MS)) {
1911
+ if (client !== target)
1912
+ return undefined;
1913
+ try {
1914
+ if (!wiped)
1915
+ await target.store.deleteAllData();
1916
+ wiped = true;
1917
+ created = await buildClient(creds);
1918
+ }
1919
+ catch {
1920
+ await new Promise((resolve) => setTimeout(resolve, delay));
1921
+ }
1922
+ }
1923
+ if (client !== target) {
1924
+ disposeClient(created);
1925
+ return undefined;
1926
+ }
1927
+ if (latestToken)
1928
+ created.setAccessToken(latestToken);
1929
+ client = created;
1930
+ cryptoClosed = false;
1931
+ attachListeners(created);
1932
+ return created;
1933
+ }
1934
+ function disposeClient(target) {
1935
+ target.stopClient();
1936
+ target.removeAllListeners();
1937
+ }
1938
+ async function buildClient(creds) {
1939
+ await purgeStaleChatStores(storeName, creds.baseUrl, creds.userId);
1940
+ const store = createChatStore(storeName, creds.baseUrl, creds.userId);
1941
+ const created = createMatrixClient({
1942
+ ...creds,
1943
+ accessToken: latestToken ?? creds.accessToken,
1944
+ store,
1945
+ });
1946
+ if (encryptionEnabled)
1947
+ await initCrypto(created);
1948
+ await store.startup();
1949
+ return created;
1950
+ }
1951
+ function attachListeners(created) {
1952
+ created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1953
+ created.on(ClientEvent.Sync, onSync);
1954
+ created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1955
+ created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1956
+ created.on(RoomEvent.Receipt, onRoomReceipt);
1957
+ created.on(RoomEvent.AccountData, watchForDraft);
1958
+ created.on(UserEvent.Presence, onUserPresence);
1959
+ created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
1960
+ }
1961
+ function initCrypto(target) {
1962
+ // Per account and device, not `storeName` alone: the Rust store refuses
1963
+ // a different device id, so a fresh sign-in needs its own database.
1964
+ const prefix = cryptoStoreDbPrefix(storeName, target.getUserId() ?? '', target.getDeviceId() ?? '');
1965
+ return target.initRustCrypto({ cryptoDatabasePrefix: prefix });
1966
+ }
1604
1967
  async function start() {
1605
1968
  if (starting)
1606
1969
  return starting;
1607
- starting = (async () => {
1970
+ const attempt = (async () => {
1608
1971
  const body = await performExchange();
1609
- const store = createChatStore(storeName);
1610
- const created = createMatrixClient({
1972
+ // Built before anything touches the outer closure's state (`client`,
1973
+ // the listeners, the refresh timer): a WASM fetch or a blocked
1974
+ // IndexedDB can throw inside `buildClient`, and `created` is still a
1975
+ // local the caller never saw, so a failure needs nothing undone and
1976
+ // `start()` can simply be called again. `buildClient` scopes the crypto
1977
+ // store per account and device and runs `store.startup()` after the
1978
+ // client exists, as `IndexedDBStore` requires (it needs
1979
+ // `setUserCreator`, which the client constructor calls, before it can
1980
+ // replay persisted `m.presence`).
1981
+ const created = await buildClient({
1611
1982
  baseUrl: body.homeserver,
1612
1983
  userId: body.user_id,
1613
1984
  accessToken: body.access_token,
1614
1985
  deviceId: body.device_id,
1615
- store,
1616
1986
  });
1617
- // Loads any previously-persisted sync data before the sync loop can
1618
- // touch the store; skipping it leaves `store.backend` unset, and the
1619
- // store silently degrades to an in-memory one on first access
1620
- // (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
1621
- //
1622
- // Must run after `createMatrixClient`, not before: matrix-js-sdk's
1623
- // own constructor is what calls `store.setUserCreator` (`client.ts`'s
1624
- // `this._store.setUserCreator(...)`), and `IndexedDBStore.startup`
1625
- // needs that already set before it can replay any `m.presence`
1626
- // persisted from a earlier session -- calling this any earlier
1627
- // throws matrix-js-sdk's own "IndexedDBStore.startup must be called
1628
- // after assigning it to the client, not before!" the moment a store
1629
- // actually has presence to replay. Dormant the whole time presence
1630
- // was off (ticket #7): every store's persisted `userPresenceEvents`
1631
- // was empty, so the guard this trips was never reached. Confirmed
1632
- // live: `test/integration/sync.test.ts`'s restarted-client case is
1633
- // the one that surfaced it, the moment the test stack turned
1634
- // presence on.
1635
- await store.startup();
1636
1987
  client = created;
1637
- created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1638
- created.on(ClientEvent.Sync, onSync);
1639
- created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1640
- created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1641
- created.on(RoomEvent.Receipt, onRoomReceipt);
1642
- created.on(UserEvent.Presence, onUserPresence);
1643
- created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
1988
+ attachListeners(created);
1644
1989
  scheduleRefresh(body.expires_at);
1645
1990
  const outcome = nextSyncOutcome(created);
1646
1991
  // Without `threadSupport`, matrix-js-sdk puts every `m.thread` reply
@@ -1652,7 +1997,14 @@ export function createChatClient(options) {
1652
1997
  reapplyAnnouncedPresence(created);
1653
1998
  await outcome;
1654
1999
  })();
1655
- return starting;
2000
+ starting = attempt;
2001
+ // Undo a failed start, so a later `start()` retries from scratch
2002
+ // instead of returning this same rejection until `stop()`.
2003
+ attempt.catch(() => {
2004
+ if (starting === attempt)
2005
+ stop();
2006
+ });
2007
+ return attempt;
1656
2008
  }
1657
2009
  function stop() {
1658
2010
  for (const pending of uploads.values()) {
@@ -1666,20 +2018,23 @@ export function createChatClient(options) {
1666
2018
  // a future write on either.
1667
2019
  pinnedChain.clear();
1668
2020
  pinnedKnown.clear();
2021
+ drafts.clear();
1669
2022
  typingUsers.clear();
2023
+ // Whatever this session had fetched may be stale by the time a caller
2024
+ // restarts it -- a status set or cleared while this client was down --
2025
+ // and the cache is cheap to rebuild: `personStatus` refetches on the
2026
+ // next read for anyone still of interest.
2027
+ chatStatusCache.clear();
1670
2028
  starting = undefined;
1671
2029
  clearTimeout(refreshTimer);
1672
2030
  refreshTimer = undefined;
1673
- if (client) {
1674
- client.removeListener(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1675
- client.removeListener(ClientEvent.Sync, onSync);
1676
- client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
1677
- client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1678
- client.removeListener(RoomEvent.Receipt, onRoomReceipt);
1679
- client.removeListener(UserEvent.Presence, onUserPresence);
1680
- client.removeListener(RoomMemberEvent.Typing, onRoomMemberTyping);
1681
- client.stopClient();
1682
- }
2031
+ if (client)
2032
+ disposeClient(client);
2033
+ cryptoClosed = false;
2034
+ // A recovery still sleeping in `swapClient` must not make the next
2035
+ // client's recovery wait on it.
2036
+ recovering = undefined;
2037
+ resyncing = undefined;
1683
2038
  client = undefined;
1684
2039
  setStatus('offline');
1685
2040
  }
@@ -1791,6 +2146,83 @@ export function createChatClient(options) {
1791
2146
  presenceListeners.add(listener);
1792
2147
  return () => presenceListeners.delete(listener);
1793
2148
  }
2149
+ /** Whether `value` is shaped enough to be a `ChatStatus` -- checked
2150
+ * before trusting anything read off a profile field nothing in this
2151
+ * package wrote, whether that is a stale shape from an older client or
2152
+ * simply someone else's unrelated custom profile data. */
2153
+ function isChatStatus(value) {
2154
+ if (!value || typeof value !== 'object')
2155
+ return false;
2156
+ const kind = value.kind;
2157
+ return (kind === 'here' ||
2158
+ kind === 'busy' ||
2159
+ kind === 'meeting' ||
2160
+ kind === 'vacation' ||
2161
+ kind === 'sick');
2162
+ }
2163
+ function notifyStatusChanged(userId, next) {
2164
+ chatStatusCache.set(userId, next);
2165
+ const changed = new Map([[userId, next]]);
2166
+ for (const listener of chatStatusListeners)
2167
+ listener(changed);
2168
+ }
2169
+ /** See `ChatClient.status`. `getExtendedProfileProperty` already checks
2170
+ * matrix-js-sdk's own store before reaching the network (populated only
2171
+ * by a sync filter this package does not set up, so in practice this
2172
+ * always makes a real request) -- a 404 and a server with MSC4133 off
2173
+ * both land here as "nothing to show", the same honest `null` either
2174
+ * way. */
2175
+ async function fetchPersonStatus(userId) {
2176
+ const target = client;
2177
+ if (!target)
2178
+ return;
2179
+ try {
2180
+ const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2181
+ notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
2182
+ }
2183
+ catch {
2184
+ notifyStatusChanged(userId, null);
2185
+ }
2186
+ }
2187
+ /** See `ChatClient.status`. Exported as `status` on the returned client
2188
+ * -- named differently in here only because this closure already has a
2189
+ * `status` variable of its own (`ChatConnectionStatus`, see above). */
2190
+ function personStatus(userId) {
2191
+ if (!chatStatusCache.has(userId)) {
2192
+ chatStatusCache.set(userId, null);
2193
+ void fetchPersonStatus(userId);
2194
+ }
2195
+ return chatStatusCache.get(userId) ?? null;
2196
+ }
2197
+ /** See `ChatClient.setOwnStatus`. The optimistic write is rolled back on
2198
+ * a rejection -- unlike `starRoom`/`muteRoom`, a write here fails for an
2199
+ * entirely ordinary reason in production today (MSC4133 off until
2200
+ * wtfalch/foundry#41), so leaving the cache holding a status that was
2201
+ * never actually saved would be a common bug, not a rare one. */
2202
+ async function setOwnStatus(next) {
2203
+ const target = client;
2204
+ if (!target)
2205
+ return;
2206
+ const userId = target.getUserId();
2207
+ if (!userId)
2208
+ return;
2209
+ const previous = chatStatusCache.get(userId) ?? null;
2210
+ notifyStatusChanged(userId, next);
2211
+ try {
2212
+ if (next === null)
2213
+ await target.deleteExtendedProfileProperty(STATUS_PROFILE_KEY);
2214
+ else
2215
+ await target.setExtendedProfileProperty(STATUS_PROFILE_KEY, next);
2216
+ }
2217
+ catch (error) {
2218
+ notifyStatusChanged(userId, previous);
2219
+ throw error;
2220
+ }
2221
+ }
2222
+ function onStatusChanged(listener) {
2223
+ chatStatusListeners.add(listener);
2224
+ return () => chatStatusListeners.delete(listener);
2225
+ }
1794
2226
  function notifyTyping(roomId) {
1795
2227
  const userIds = [...(typingUsers.get(roomId) ?? [])];
1796
2228
  for (const listener of typingListeners.get(roomId) ?? [])
@@ -1864,6 +2296,11 @@ export function createChatClient(options) {
1864
2296
  // `muteRoom(roomId, false)` alone must not be read as that proof: see
1865
2297
  // `unreliableServerCount`.
1866
2298
  unreliableServerCount.delete(roomId);
2299
+ // A person opening a room they had marked unread has, by definition,
2300
+ // just read it -- a flag a real read left standing would be a flag no
2301
+ // read ever clears.
2302
+ if (isMarkedUnread(room))
2303
+ await markRoomUnread(roomId, false);
1867
2304
  notify();
1868
2305
  }
1869
2306
  /** See `ChatClient.muteRoom`. `setRoomMutePushRule` PUTs (or, unmuting,
@@ -1891,6 +2328,47 @@ export function createChatClient(options) {
1891
2328
  unreliableServerCount.add(roomId);
1892
2329
  notify();
1893
2330
  }
2331
+ /** See `ChatClient.markRoomUnread`. Unlike `muteRoom`'s push rule, room
2332
+ * account data has no refetch-on-write matrix-js-sdk does for us -- it
2333
+ * only lands locally once a `/sync` echoes it back (`RoomEvent.
2334
+ * AccountData`, which nothing here listens for). Waiting for that round
2335
+ * trip would make this the one write in the file that resolves before
2336
+ * its own effect is visible, so the room's local `accountData` is
2337
+ * updated by hand the moment the server has accepted the write --
2338
+ * exactly the event a landed sync would otherwise hand back, which is
2339
+ * why a later, real echo of the same content is harmless. */
2340
+ async function markRoomUnread(roomId, unread) {
2341
+ if (!client)
2342
+ return;
2343
+ const room = client.getRoom(roomId);
2344
+ if (!room)
2345
+ return;
2346
+ await client.setRoomAccountData(roomId, EventType.MarkedUnread, { unread });
2347
+ const userId = client.getUserId();
2348
+ if (userId) {
2349
+ await client.http.authedRequest(Method.Put, `/user/${encodeURIComponent(userId)}/rooms/${encodeURIComponent(roomId)}/account_data/${FAMEDLY_MARKED_UNREAD}`, undefined, { unread });
2350
+ }
2351
+ room.addAccountData([
2352
+ new MatrixEvent({ type: EventType.MarkedUnread, content: { unread } }),
2353
+ new MatrixEvent({ type: FAMEDLY_MARKED_UNREAD, content: { unread } }),
2354
+ ]);
2355
+ notify();
2356
+ }
2357
+ /** See `ChatClient.starRoom`. `setRoomTag`/`deleteRoomTag` are the same
2358
+ * two calls `hideDirectMessage` uses for `HIDDEN_TAG`, and carry the
2359
+ * same lack of local echo: Synapse pushes the tag straight back down
2360
+ * the already-parked `/sync`, and `readRooms()` picks it up from
2361
+ * there a round trip later, not a render later. */
2362
+ async function starRoom(roomId, starred) {
2363
+ if (!client)
2364
+ return;
2365
+ if (!client.getRoom(roomId))
2366
+ return;
2367
+ if (starred)
2368
+ await client.setRoomTag(roomId, FAVOURITE_TAG, {});
2369
+ else
2370
+ await client.deleteRoomTag(roomId, FAVOURITE_TAG);
2371
+ }
1894
2372
  return {
1895
2373
  start,
1896
2374
  stop,
@@ -1898,10 +2376,13 @@ export function createChatClient(options) {
1898
2376
  totalUnreadCount: () => readRooms().reduce((sum, room) => sum + room.unreadCount, 0),
1899
2377
  markRoomRead,
1900
2378
  muteRoom,
2379
+ markRoomUnread,
2380
+ starRoom,
1901
2381
  connectionStatus: () => status,
1902
2382
  onConnectionStatusChanged,
1903
2383
  onRoomsChanged,
1904
2384
  userId: () => client?.getUserId() ?? null,
2385
+ getCrypto: () => (cryptoClosed ? undefined : client?.getCrypto()),
1905
2386
  people: readPeople,
1906
2387
  roomMembers,
1907
2388
  readBy,
@@ -1925,12 +2406,22 @@ export function createChatClient(options) {
1925
2406
  retryMessage,
1926
2407
  cancelMessage,
1927
2408
  readUpToEventId,
2409
+ getDraft,
2410
+ setDraft,
2411
+ clearDraft,
2412
+ threadFollowing,
2413
+ followThread,
2414
+ unfollowThread,
2415
+ onThreadFollowChanged,
1928
2416
  canLoadMedia,
1929
2417
  loadMedia,
1930
2418
  sendFile,
1931
2419
  presence,
1932
2420
  announcePresence,
1933
2421
  onPresenceChanged,
2422
+ status: personStatus,
2423
+ setOwnStatus,
2424
+ onStatusChanged,
1934
2425
  sendTyping,
1935
2426
  onTypingChanged,
1936
2427
  };