@wtfalch/chat 0.1.0 → 0.2.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,4 +1,4 @@
1
- import { ClientEvent, ContentHelpers, EventStatus, EventTimeline, EventType, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, MsgType, NotificationCountType, Preset, RelationType, RoomEvent, SyncState, createClient as createMatrixClient, } from 'matrix-js-sdk';
1
+ import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, 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
4
  import { createChatStore } from "./store.js";
@@ -31,6 +31,19 @@ export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
31
31
  * `/_matrix/media/...` download paths are unauthenticated and are never
32
32
  * used by this package (ticket #13). */
33
33
  const MEDIA_DOWNLOAD_PATH = '/_matrix/client/v1/media/download';
34
+ /** What `sendTyping` asks the server to auto-expire a typing state after,
35
+ * in ms -- matrix-js-sdk's own default when a caller passes none
36
+ * (`client.js`'s `sendTyping`), used explicitly here since this package's
37
+ * own `sendTyping(roomId, typing)` takes no timeout of its own. A caller
38
+ * wanting the far end to keep seeing "typing" through a long pause calls
39
+ * this again itself; nothing here renews it on a timer. */
40
+ const TYPING_TIMEOUT_MS = 20_000;
41
+ /** How many *matching* events `roomFiles` asks Synapse for per request.
42
+ * Unlike `paginate`'s 30 (which bounds how much plain conversation a
43
+ * person scrolls through at once), this only ever counts events that
44
+ * already passed the `contains_url` filter server-side, so a larger page
45
+ * costs one round trip, not one screenful. */
46
+ const ROOM_FILES_PAGE_SIZE = 50;
34
47
  /**
35
48
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
36
49
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -70,6 +83,33 @@ export function createChatClient(options) {
70
83
  const uploads = new Map();
71
84
  let uploadSeq = 0;
72
85
  const statusListeners = new Set();
86
+ const presenceListeners = new Set();
87
+ const typingListeners = new Map();
88
+ /** Who is currently typing, per room -- built up from `RoomMemberEvent.
89
+ * Typing` one member at a time, the signed-in person's own id never
90
+ * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
91
+ * exactly as ephemeral as the `m.typing` it is built from, and a fresh
92
+ * `start()` has to rebuild it from whatever sync delivers next rather
93
+ * than carry a stale room's list into a new session. */
94
+ const typingUsers = new Map();
95
+ /** What `announcePresence` last said, so every restart can re-apply it --
96
+ * see `reapplyAnnouncedPresence`. `undefined` until a caller announces
97
+ * anything, which leaves matrix-js-sdk to omit `set_presence` entirely
98
+ * and Matrix to default it to `'online'`, exactly as before. Deliberately
99
+ * not cleared by `stop()`: a person idle when their session was torn down
100
+ * is still idle when it comes back, and re-reporting them online for the
101
+ * gap would be the very flicker this exists to stop. */
102
+ let announced;
103
+ /** Rooms `muteRoom` has touched since their last real read. Synapse
104
+ * evaluates a room's `dont_notify` rule once, at receive time, and never
105
+ * recomputes `notification_count` for events already counted under it --
106
+ * confirmed live, unmuting does not make the server's own count catch
107
+ * up, not right away and not on a later poll. So a room stays in this
108
+ * set, and `readRooms()` keeps comparing against the local walk, from
109
+ * the moment it is muted until the next `markRoomRead` proves the two
110
+ * have agreed again -- an unmute alone is not that proof. Every other
111
+ * room never pays for the walk at all. */
112
+ const unreliableServerCount = new Set();
73
113
  async function performExchange() {
74
114
  return exchange(exchangeUrl, getAccessToken, deviceId);
75
115
  }
@@ -159,6 +199,7 @@ export function createChatClient(options) {
159
199
  await target.store.deleteAllData();
160
200
  const outcome = nextSyncOutcome(target);
161
201
  await target.startClient(START_OPTIONS);
202
+ reapplyAnnouncedPresence(target);
162
203
  await outcome;
163
204
  notify();
164
205
  })();
@@ -215,6 +256,7 @@ export function createChatClient(options) {
215
256
  scheduleRefresh(body.expires_at);
216
257
  const outcome = nextSyncOutcome(target);
217
258
  await target.startClient(START_OPTIONS);
259
+ reapplyAnnouncedPresence(target);
218
260
  await outcome;
219
261
  notify();
220
262
  })();
@@ -259,26 +301,87 @@ export function createChatClient(options) {
259
301
  * and nothing in Chat's. A hidden direct room is left out for the reason
260
302
  * `hideDirectMessage` exists. */
261
303
  function readRooms() {
262
- if (!client)
304
+ const target = client;
305
+ if (!target)
263
306
  return [];
264
- const direct = directRoomIds(client);
265
- return client
307
+ const direct = directRoomIds(target);
308
+ return target
266
309
  .getRooms()
267
310
  .filter((room) => room.getMyMembership() === KnownMembership.Join ||
268
311
  room.getMyMembership() === KnownMembership.Invite)
269
312
  .filter((room) => !room.isSpaceRoom())
270
313
  .filter((room) => !(HIDDEN_TAG in room.tags))
271
- .map((room) => ({
272
- id: room.roomId,
273
- name: room.name,
274
- isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
275
- membership: room.getMyMembership() === KnownMembership.Invite
276
- ? 'invite'
277
- : 'join',
278
- unreadCount: room.getMyMembership() === KnownMembership.Invite
279
- ? 1
280
- : room.getUnreadNotificationCount(NotificationCountType.Total),
281
- }));
314
+ .map((room) => {
315
+ const muted = isMuted(target, room.roomId);
316
+ return {
317
+ id: room.roomId,
318
+ name: room.name,
319
+ isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
320
+ membership: room.getMyMembership() === KnownMembership.Invite
321
+ ? 'invite'
322
+ : 'join',
323
+ unreadCount: room.getMyMembership() === KnownMembership.Invite
324
+ ? 1
325
+ : roomUnreadCount(target, room, muted),
326
+ muted,
327
+ };
328
+ });
329
+ }
330
+ /** A room's own `unreadCount` -- see `ChatRoomSummary.unreadCount` for
331
+ * why a muted room (or one `unreliableServerCount` still distrusts)
332
+ * takes the larger of Synapse's own count and the local walk, rather
333
+ * than either alone: Synapse's count is what a room with more unread
334
+ * history than the currently-loaded timeline holds is right about, and
335
+ * the local walk is what a room Synapse has stopped counting for is
336
+ * right about. Every other room skips the walk and costs nothing more
337
+ * than it already did. */
338
+ function roomUnreadCount(target, room, muted) {
339
+ const serverCount = room.getUnreadNotificationCount(NotificationCountType.Total);
340
+ if (!muted && !unreliableServerCount.has(room.roomId))
341
+ return serverCount;
342
+ return Math.max(serverCount, unreadTimelineCount(target, room));
343
+ }
344
+ /** Whether `roomId` carries the room-scoped `dont_notify` rule
345
+ * `muteRoom` writes -- see `ChatClient.muteRoom`. `client.pushRules` is
346
+ * unset only in the narrow window before the pre-sync `getPushRules()`
347
+ * call has landed (`start()` has not resolved yet); reading as unmuted
348
+ * there is the same answer a room with no rule at all gets. */
349
+ function isMuted(target, roomId) {
350
+ const rule = target.pushRules && target.getRoomPushRule('global', roomId);
351
+ return Boolean(rule?.actions.includes(PushRuleActionName.DontNotify));
352
+ }
353
+ /** A muted room's own `unreadCount`, counted here rather than read off
354
+ * Synapse. Confirmed live against Synapse v1.161.0: the room-scoped
355
+ * `dont_notify` rule `muteRoom` writes does not merely withhold the
356
+ * push -- it stops `unread_notifications.notification_count` climbing
357
+ * for that room at all, because Synapse derives that count from the
358
+ * same push-rule evaluation. Reading it here would report zero for
359
+ * exactly the rooms this ticket needs to keep counting, so a muted
360
+ * room counts itself instead: every `m.room.message` in the room's own
361
+ * live timeline, after the local read-up-to marker, sent by somebody
362
+ * else. The same receipt `markRoomRead` sends already moves that
363
+ * marker past everything currently unread, so reading a muted room
364
+ * still clears it. */
365
+ function unreadTimelineCount(target, room) {
366
+ const me = target.getUserId();
367
+ const readUpToId = me ? room.getEventReadUpTo(me) : null;
368
+ const events = room.getLiveTimeline().getEvents();
369
+ const startIndex = readUpToId
370
+ ? events.findIndex((event) => event.getId() === readUpToId) + 1
371
+ : 0;
372
+ let count = 0;
373
+ for (const event of events.slice(startIndex)) {
374
+ if (event.getType() !== EventType.RoomMessage)
375
+ continue;
376
+ if (event.isRelation(RelationType.Replace))
377
+ continue;
378
+ if (event.isRedacted())
379
+ continue;
380
+ if (event.getSender() === me)
381
+ continue;
382
+ count += 1;
383
+ }
384
+ return count;
282
385
  }
283
386
  /** The company space: the one space the account is joined to (chat plan
284
387
  * section 5 -- one agora is one company is one space). `undefined` before
@@ -495,6 +598,7 @@ export function createChatClient(options) {
495
598
  if (!room)
496
599
  return;
497
600
  watchForEdit(event, room);
601
+ watchForPinnedEvents(event, room);
498
602
  notifyTimeline(room.roomId);
499
603
  }
500
604
  /** An edit arriving is two things, a tick apart: the `m.replace` event
@@ -764,6 +868,47 @@ export function createChatClient(options) {
764
868
  return;
765
869
  await client.paginateEventTimeline(thread.liveTimeline, { backwards: true, limit: 30 });
766
870
  }
871
+ /** See `ChatClient.roomFiles`. Walks `/messages` backward with a
872
+ * `contains_url` filter rather than `paginate`'s plain scrollback:
873
+ * Synapse answers with only file-bearing events, so this costs one
874
+ * request per page of *files*, never one per page of conversation.
875
+ * `target`/`client === target` guards the loop the same way
876
+ * `loadMedia` does: a long walk that outlives a `stop()` call returns
877
+ * whatever it already has rather than carrying on against a session
878
+ * the caller has torn down. */
879
+ async function roomFiles(roomId, options) {
880
+ if (!client)
881
+ return [];
882
+ const target = client;
883
+ if (!target.getRoom(roomId))
884
+ return [];
885
+ const filter = new Filter(target.getUserId());
886
+ filter.setDefinition({
887
+ room: { timeline: { types: [EventType.RoomMessage], contains_url: true } },
888
+ });
889
+ const mapper = target.getEventMapper();
890
+ const limit = options?.limit;
891
+ const attachments = [];
892
+ let from = options?.before ?? null;
893
+ while (client === target) {
894
+ const page = await target.createMessagesRequest(roomId, from, ROOM_FILES_PAGE_SIZE, Direction.Backward, filter);
895
+ for (const raw of page.chunk) {
896
+ const event = mapper(raw);
897
+ if (event.isRedacted())
898
+ continue;
899
+ const attachment = toAttachment(event);
900
+ if (!attachment)
901
+ continue;
902
+ attachments.push(attachment);
903
+ if (limit !== undefined && attachments.length >= limit)
904
+ return attachments;
905
+ }
906
+ if (!page.end || page.chunk.length === 0)
907
+ break;
908
+ from = page.end;
909
+ }
910
+ return attachments;
911
+ }
767
912
  /** Builds the Matrix content once, here rather than in `markdown.ts`:
768
913
  * `msgtype`/`format`/`formatted_body` are Matrix's own shape, and this
769
914
  * is the only file in the package that touches matrix-js-sdk (see
@@ -1097,6 +1242,136 @@ export function createChatClient(options) {
1097
1242
  'm.relates_to': { rel_type: RelationType.Annotation, event_id: eventId, key },
1098
1243
  });
1099
1244
  }
1245
+ /** The room's `m.room.pinned_events` content, read straight off
1246
+ * matrix-js-sdk's own current state -- there is no higher-level helper
1247
+ * for it the way `room.name` is one for `m.room.name`. `[]` for a room
1248
+ * with no such state at all, which is every room until the first pin. */
1249
+ function pinnedEventIds(room) {
1250
+ const content = room.currentState
1251
+ .getStateEvents(EventType.RoomPinnedEvents, '')
1252
+ ?.getContent();
1253
+ const pinned = content?.pinned;
1254
+ return Array.isArray(pinned) ? pinned.filter((id) => typeof id === 'string') : [];
1255
+ }
1256
+ /** A room `pinMessage`/`unpinMessage` is currently writing to, chained so
1257
+ * a second call for the same room queues behind the first rather than
1258
+ * racing it -- see `chainPinnedWrite`. Never cleared once a room has
1259
+ * one: an already-settled promise here costs nothing, and clearing it
1260
+ * on a timer or "nothing queued behind this" check is exactly the kind
1261
+ * of race this whole mechanism exists to avoid (an earlier version of
1262
+ * this file tried that and lost a pin to it -- see the report). */
1263
+ const pinnedChain = new Map();
1264
+ /** This client's own best knowledge of a room's pinned list -- not a
1265
+ * cache with a lifetime, but a value kept current two ways: a
1266
+ * successful write updates it immediately (see `chainPinnedWrite`),
1267
+ * and `watchForPinnedEvents` updates it the moment any
1268
+ * `m.room.pinned_events` -- this client's own echo, or another
1269
+ * client's -- lands through `/sync`. So it is never "expired"; it is
1270
+ * either right now, or about to be corrected by the next sync, exactly
1271
+ * like `room.currentState` itself. */
1272
+ const pinnedKnown = new Map();
1273
+ /** Keeps `pinnedKnown` current with whatever this client has actually
1274
+ * seen land, own write or somebody else's -- called from
1275
+ * `onRoomTimelineChanged` for every event, same as `watchForEdit`. */
1276
+ function watchForPinnedEvents(event, room) {
1277
+ if (event.getType() !== EventType.RoomPinnedEvents)
1278
+ return;
1279
+ const pinned = event.getContent().pinned;
1280
+ if (!Array.isArray(pinned))
1281
+ return;
1282
+ pinnedKnown.set(room.roomId, pinned.filter((id) => typeof id === 'string'));
1283
+ }
1284
+ /** Queues one read-modify-write of `room`'s `m.room.pinned_events`
1285
+ * behind whatever `pinMessage`/`unpinMessage` already have in flight
1286
+ * for it, so `await pinMessage(a); await pinMessage(b);` -- or even
1287
+ * neither awaited before the next call starts -- ends with both pinned
1288
+ * rather than losing `a`.
1289
+ *
1290
+ * The loss without this: `sendStateEvent`'s promise resolves on
1291
+ * Synapse's HTTP response, before the echo has come back through
1292
+ * `/sync` and landed in `room.currentState` (confirmed live -- a
1293
+ * second call's read of `pinnedEventIds(room)` still saw the list from
1294
+ * *before* the first call, even after a full `await`). Both calls
1295
+ * reported success; the server ended up with only the second id.
1296
+ *
1297
+ * The fix: `mutate` is handed `pinnedKnown`, this client's own running
1298
+ * idea of the list, rather than a fresh read that has not caught up --
1299
+ * seeded from `room.currentState` only the first time this room is
1300
+ * touched, when there is nothing of this client's own yet.
1301
+ *
1302
+ * What this does not fix: two different `ChatClient`s -- two accounts,
1303
+ * or two devices of one account -- writing to the same room's pinned
1304
+ * list at once. Each keeps its own `pinnedChain`/`pinnedKnown`, so
1305
+ * nothing here (or anywhere) sequences across clients. Matrix gives
1306
+ * `m.room.pinned_events` no compare-and-swap: it is one state value,
1307
+ * replaced whole, and Synapse's own state resolution -- never a merge
1308
+ * -- decides which of two concurrent writes wins, silently, the same
1309
+ * way it always has. This narrows the hazard to that one,
1310
+ * protocol-level case; it does not remove it. */
1311
+ function chainPinnedWrite(target, room, mutate) {
1312
+ const roomId = room.roomId;
1313
+ const queuedAfter = pinnedChain.get(roomId) ?? Promise.resolve();
1314
+ const result = queuedAfter
1315
+ .catch(() => { })
1316
+ .then(async () => {
1317
+ if (client !== target)
1318
+ return;
1319
+ const current = pinnedKnown.get(roomId) ?? pinnedEventIds(room);
1320
+ const wanted = mutate(current);
1321
+ if (!wanted)
1322
+ return;
1323
+ await target.sendStateEvent(roomId, EventType.RoomPinnedEvents, { pinned: wanted }, '');
1324
+ if (client === target)
1325
+ pinnedKnown.set(roomId, wanted);
1326
+ });
1327
+ pinnedChain.set(roomId, result.catch(() => { }));
1328
+ return result;
1329
+ }
1330
+ /** See `ChatClient.pinMessage`. Already-pinned is a no-op resolved
1331
+ * without a round trip -- there is nothing Synapse could refuse, and
1332
+ * refusing here would be wrong: the caller asked for a state that
1333
+ * already holds. Everything else is a plain `sendStateEvent`, chained
1334
+ * through `chainPinnedWrite` so a second call for this room is safe,
1335
+ * and its rejection is handed straight back -- see the module's house
1336
+ * rule (ticket #8: a member's pin in a room whose power levels predate
1337
+ * the change must reject, never resolve as if it had worked). */
1338
+ async function pinMessage(roomId, eventId) {
1339
+ if (!client)
1340
+ throw new Error('chat: pinMessage called before start()');
1341
+ const target = client;
1342
+ const room = target.getRoom(roomId);
1343
+ if (!room)
1344
+ throw new Error(`chat: not in room ${roomId}`);
1345
+ await chainPinnedWrite(target, room, (current) => current.includes(eventId) ? undefined : [...current, eventId]);
1346
+ }
1347
+ /** See `ChatClient.unpinMessage`. Not-pinned is a no-op for the same
1348
+ * reason `pinMessage`'s already-pinned is one, and the same chain. */
1349
+ async function unpinMessage(roomId, eventId) {
1350
+ if (!client)
1351
+ throw new Error('chat: unpinMessage called before start()');
1352
+ const target = client;
1353
+ const room = target.getRoom(roomId);
1354
+ if (!room)
1355
+ throw new Error(`chat: not in room ${roomId}`);
1356
+ await chainPinnedWrite(target, room, (current) => current.includes(eventId) ? current.filter((id) => id !== eventId) : undefined);
1357
+ }
1358
+ /** See `ChatClient.pinnedMessages`. `findEvent` rather than
1359
+ * `room.findEventById`: a pinned reply lives wherever `threadReplies`
1360
+ * says a reply can live, the same gap `editMessage`/`deleteMessage`
1361
+ * already close for the write side. */
1362
+ function pinnedMessages(roomId) {
1363
+ const room = client?.getRoom(roomId);
1364
+ if (!room)
1365
+ return [];
1366
+ const events = [];
1367
+ for (const eventId of pinnedEventIds(room)) {
1368
+ const found = findEvent(room, eventId);
1369
+ const mapped = found ? toTimelineEvent(found, room, false) : undefined;
1370
+ if (mapped)
1371
+ events.push(mapped);
1372
+ }
1373
+ return events;
1374
+ }
1100
1375
  function readUpToEventId(roomId) {
1101
1376
  const room = client?.getRoom(roomId);
1102
1377
  const userId = client?.getUserId();
@@ -1189,11 +1464,6 @@ export function createChatClient(options) {
1189
1464
  starting = (async () => {
1190
1465
  const body = await performExchange();
1191
1466
  const store = createChatStore(storeName);
1192
- // Loads any previously-persisted sync data before the sync loop can
1193
- // touch the store; skipping it leaves `store.backend` unset, and the
1194
- // store silently degrades to an in-memory one on first access
1195
- // (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
1196
- await store.startup();
1197
1467
  const created = createMatrixClient({
1198
1468
  baseUrl: body.homeserver,
1199
1469
  userId: body.user_id,
@@ -1201,11 +1471,32 @@ export function createChatClient(options) {
1201
1471
  deviceId: body.device_id,
1202
1472
  store,
1203
1473
  });
1474
+ // Loads any previously-persisted sync data before the sync loop can
1475
+ // touch the store; skipping it leaves `store.backend` unset, and the
1476
+ // store silently degrades to an in-memory one on first access
1477
+ // (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
1478
+ //
1479
+ // Must run after `createMatrixClient`, not before: matrix-js-sdk's
1480
+ // own constructor is what calls `store.setUserCreator` (`client.ts`'s
1481
+ // `this._store.setUserCreator(...)`), and `IndexedDBStore.startup`
1482
+ // needs that already set before it can replay any `m.presence`
1483
+ // persisted from a earlier session -- calling this any earlier
1484
+ // throws matrix-js-sdk's own "IndexedDBStore.startup must be called
1485
+ // after assigning it to the client, not before!" the moment a store
1486
+ // actually has presence to replay. Dormant the whole time presence
1487
+ // was off (ticket #7): every store's persisted `userPresenceEvents`
1488
+ // was empty, so the guard this trips was never reached. Confirmed
1489
+ // live: `test/integration/sync.test.ts`'s restarted-client case is
1490
+ // the one that surfaced it, the moment the test stack turned
1491
+ // presence on.
1492
+ await store.startup();
1204
1493
  client = created;
1205
1494
  created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1206
1495
  created.on(ClientEvent.Sync, onSync);
1207
1496
  created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1208
1497
  created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1498
+ created.on(UserEvent.Presence, onUserPresence);
1499
+ created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
1209
1500
  scheduleRefresh(body.expires_at);
1210
1501
  const outcome = nextSyncOutcome(created);
1211
1502
  // Without `threadSupport`, matrix-js-sdk puts every `m.thread` reply
@@ -1214,6 +1505,7 @@ export function createChatClient(options) {
1214
1505
  // and the room keeps only the message that started it (ticket #17).
1215
1506
  // It is a `startClient` option, not a `createClient` one.
1216
1507
  await created.startClient(START_OPTIONS);
1508
+ reapplyAnnouncedPresence(created);
1217
1509
  await outcome;
1218
1510
  })();
1219
1511
  return starting;
@@ -1224,6 +1516,13 @@ export function createChatClient(options) {
1224
1516
  upload.abort.abort();
1225
1517
  }
1226
1518
  uploads.clear();
1519
+ // A restart gets a brand-new `MatrixClient`; `chainPinnedWrite`'s own
1520
+ // `client !== target` check already keeps a still-running chain from
1521
+ // writing through the old one, but there is nothing left worth basing
1522
+ // a future write on either.
1523
+ pinnedChain.clear();
1524
+ pinnedKnown.clear();
1525
+ typingUsers.clear();
1227
1526
  starting = undefined;
1228
1527
  clearTimeout(refreshTimer);
1229
1528
  refreshTimer = undefined;
@@ -1232,6 +1531,8 @@ export function createChatClient(options) {
1232
1531
  client.removeListener(ClientEvent.Sync, onSync);
1233
1532
  client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
1234
1533
  client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1534
+ client.removeListener(UserEvent.Presence, onUserPresence);
1535
+ client.removeListener(RoomMemberEvent.Typing, onRoomMemberTyping);
1235
1536
  client.stopClient();
1236
1537
  }
1237
1538
  client = undefined;
@@ -1245,6 +1546,153 @@ export function createChatClient(options) {
1245
1546
  statusListeners.add(listener);
1246
1547
  return () => statusListeners.delete(listener);
1247
1548
  }
1549
+ /** Matrix's own three presence strings, plus MSC3026's unstable `busy`,
1550
+ * folded onto the four states `Presence` exposes -- see `Presence`'s own
1551
+ * comment for why anything else, `undefined` included, reads as
1552
+ * `'offline'` rather than being treated as an error. */
1553
+ function toPresence(raw) {
1554
+ switch (raw) {
1555
+ case 'online':
1556
+ return 'online';
1557
+ case 'unavailable':
1558
+ return 'away';
1559
+ case 'busy':
1560
+ case 'org.matrix.msc3026.busy':
1561
+ return 'busy';
1562
+ default:
1563
+ return 'offline';
1564
+ }
1565
+ }
1566
+ /** See `ChatClient.presence`. `client.getUser` is matrix-js-sdk's own
1567
+ * cache, populated the moment an `m.presence` event for that person has
1568
+ * ever arrived -- this never fetches. */
1569
+ function presence(userId) {
1570
+ return toPresence(client?.getUser(userId)?.presence);
1571
+ }
1572
+ /** See `ChatClient.announcePresence`. Two requests, and both are needed:
1573
+ *
1574
+ * `setSyncPresence` changes the `set_presence` this session's *own*
1575
+ * `/sync` carries from here on, which is the only thing that makes an
1576
+ * announcement survive -- Synapse's `user_syncing` feeds that parameter
1577
+ * straight into `set_state(is_sync=True)`, and the only state a sync is
1578
+ * forbidden to overwrite is `'busy'`. Without it a person announced away
1579
+ * is back online within one long poll, by their own client.
1580
+ *
1581
+ * It only reaches the wire on the *next* poll, though (`sync.js` reads
1582
+ * `this.presence` when it builds each request's query string, and never
1583
+ * interrupts one in flight), which for an idle tab is up to 30 seconds
1584
+ * away. The `PUT` closes that gap. Ordered sync-parameter first so that
1585
+ * a poll returning between the two carries the new value rather than
1586
+ * undoing the `PUT` that had not been sent yet.
1587
+ *
1588
+ * **The `PUT` is best-effort, and its failure is not this call's.**
1589
+ * Synapse allows one presence change per ten seconds
1590
+ * (`rc_presence.per_user`, default `per_second: 0.1, burst_count: 1`),
1591
+ * and refuses the rest with a `429` -- so a person who goes idle and
1592
+ * comes straight back would otherwise get a rejection for an
1593
+ * announcement that had in fact taken effect. It had: `setSyncPresence`
1594
+ * is local bookkeeping that cannot fail, and the next poll carries it.
1595
+ * Synapse treats the same limit differently there, ignoring a sync's
1596
+ * `set_presence` for one round rather than refusing the sync
1597
+ * (`rest/client/sync.py`: `affect_presence = False`), so the state
1598
+ * converges on the poll after. Rejecting here would tell the caller
1599
+ * nothing true and nothing it could act on. */
1600
+ async function announcePresence(next) {
1601
+ announced = next === 'away' ? SetPresence.Unavailable : SetPresence.Online;
1602
+ const target = client;
1603
+ if (!target)
1604
+ return;
1605
+ await target.setSyncPresence(announced);
1606
+ try {
1607
+ await target.setPresence({ presence: announced });
1608
+ }
1609
+ catch {
1610
+ // Best-effort by design -- see above. The announcement is already
1611
+ // made; this only decided how soon anybody else would see it.
1612
+ }
1613
+ }
1614
+ /** `stopClient()` drops matrix-js-sdk's `SyncApi` entirely and
1615
+ * `startClient()` builds a fresh one (`client.js`'s `this.syncApi =
1616
+ * undefined` / `new SyncApi(...)`), so the `set_presence` an
1617
+ * announcement set lives exactly as long as one sync loop. Every restart
1618
+ * in this file -- a dead token, a refused sync position, a plain
1619
+ * `stop()` then `start()` -- would otherwise put an idle person silently
1620
+ * back online, which is the failure `announcePresence` exists to
1621
+ * prevent. So each restart re-applies it.
1622
+ *
1623
+ * The earliest this can run is once `startClient` returns, by which time
1624
+ * that restart's own first sync has already gone out carrying nothing --
1625
+ * so an idle person does flicker back to `'online'` for that one poll.
1626
+ * Every poll after it is right. Closing even that would mean reaching
1627
+ * into matrix-js-sdk's sync loop before it starts, which it offers no
1628
+ * hook for, and a restart of an idle session is rare enough not to be
1629
+ * worth a fork. */
1630
+ function reapplyAnnouncedPresence(target) {
1631
+ if (announced === undefined)
1632
+ return;
1633
+ void target.setSyncPresence(announced);
1634
+ }
1635
+ /** `UserEvent.Presence` is re-emitted onto the client itself for every
1636
+ * `User` matrix-js-sdk has ever created (`User.createUser`'s own "events
1637
+ * will also emit on MatrixClient") -- so one listener, attached once in
1638
+ * `start()`, covers every person this session ever hears about, not just
1639
+ * the members of a room a caller happens to be looking at. */
1640
+ function onUserPresence(_event, user) {
1641
+ const changed = new Map([[user.userId, toPresence(user.presence)]]);
1642
+ for (const listener of presenceListeners)
1643
+ listener(changed);
1644
+ }
1645
+ function onPresenceChanged(listener) {
1646
+ presenceListeners.add(listener);
1647
+ return () => presenceListeners.delete(listener);
1648
+ }
1649
+ function notifyTyping(roomId) {
1650
+ const userIds = [...(typingUsers.get(roomId) ?? [])];
1651
+ for (const listener of typingListeners.get(roomId) ?? [])
1652
+ listener(userIds);
1653
+ }
1654
+ /** `RoomMemberEvent.Typing` is re-emitted onto the client for every
1655
+ * member of every room it knows (`_createAndReEmitRoom`'s own
1656
+ * `RoomStateEvent.NewMember` wiring), so -- like `onUserPresence` -- one
1657
+ * listener attached once covers every room. The signed-in person's own
1658
+ * typing is dropped here rather than in `notifyTyping`: `m.typing`
1659
+ * lists everyone currently typing including this session, and a person
1660
+ * is never told they themselves are typing. */
1661
+ function onRoomMemberTyping(_event, member) {
1662
+ if (member.userId === client?.getUserId())
1663
+ return;
1664
+ let set = typingUsers.get(member.roomId);
1665
+ if (member.typing) {
1666
+ if (!set) {
1667
+ set = new Set();
1668
+ typingUsers.set(member.roomId, set);
1669
+ }
1670
+ set.add(member.userId);
1671
+ }
1672
+ else if (set) {
1673
+ set.delete(member.userId);
1674
+ if (set.size === 0)
1675
+ typingUsers.delete(member.roomId);
1676
+ }
1677
+ notifyTyping(member.roomId);
1678
+ }
1679
+ function onTypingChanged(roomId, listener) {
1680
+ let set = typingListeners.get(roomId);
1681
+ if (!set) {
1682
+ set = new Set();
1683
+ typingListeners.set(roomId, set);
1684
+ }
1685
+ set.add(listener);
1686
+ return () => set?.delete(listener);
1687
+ }
1688
+ /** See `ChatClient.sendTyping`. Fire-and-forget, the same as every other
1689
+ * ephemeral signal in this file: a dropped typing notification is not
1690
+ * worth retrying, and there is no local echo to settle either way. */
1691
+ function sendTyping(roomId, typing) {
1692
+ if (!client)
1693
+ return;
1694
+ client.sendTyping(roomId, typing, TYPING_TIMEOUT_MS).catch(() => { });
1695
+ }
1248
1696
  /** Sends `m.read` for the newest event in the room's live timeline and
1249
1697
  * clears the count right away, rather than waiting for the server to
1250
1698
  * echo the receipt back on a later sync -- matrix-js-sdk's own local
@@ -1265,6 +1713,37 @@ export function createChatClient(options) {
1265
1713
  await client.sendReadReceipt(newest);
1266
1714
  room.setUnreadNotificationCount(NotificationCountType.Total, 0);
1267
1715
  room.setUnreadNotificationCount(NotificationCountType.Highlight, 0);
1716
+ // A real read is the only thing that proves Synapse's own count and
1717
+ // the local walk have caught up with each other -- both are 0 now,
1718
+ // whether or not the room is still muted. Until this, calling
1719
+ // `muteRoom(roomId, false)` alone must not be read as that proof: see
1720
+ // `unreliableServerCount`.
1721
+ unreliableServerCount.delete(roomId);
1722
+ notify();
1723
+ }
1724
+ /** See `ChatClient.muteRoom`. `setRoomMutePushRule` PUTs (or, unmuting,
1725
+ * DELETEs) the room-scoped rule and then re-fetches `/pushrules/` on
1726
+ * its own before resolving, so `client.pushRules` -- and so `isMuted`,
1727
+ * and so the next `rooms()` -- already reflects the server's own
1728
+ * answer by the time this returns; nothing here needs to wait for a
1729
+ * fresh `/sync`. `notify()` still runs explicitly because that refresh
1730
+ * is a plain HTTP round trip, not a landed sync, so `onSync` never
1731
+ * fires for it.
1732
+ *
1733
+ * Muting or unmuting both mark the room `unreliableServerCount`: once
1734
+ * muted, Synapse stops climbing on its own count, and unmuting does not
1735
+ * make it recompute what it already decided not to count -- confirmed
1736
+ * live, `notification_count` stays exactly where muting left it, not
1737
+ * just right after unmuting but on every later poll too. So the room
1738
+ * keeps comparing against the local walk across the whole mute ->
1739
+ * traffic -> unmute run, until a real read proves the two agree again. */
1740
+ async function muteRoom(roomId, muted) {
1741
+ if (!client)
1742
+ return;
1743
+ if (!client.getRoom(roomId))
1744
+ return;
1745
+ await client.setRoomMutePushRule('global', roomId, muted);
1746
+ unreliableServerCount.add(roomId);
1268
1747
  notify();
1269
1748
  }
1270
1749
  return {
@@ -1273,6 +1752,7 @@ export function createChatClient(options) {
1273
1752
  rooms: readRooms,
1274
1753
  totalUnreadCount: () => readRooms().reduce((sum, room) => sum + room.unreadCount, 0),
1275
1754
  markRoomRead,
1755
+ muteRoom,
1276
1756
  connectionStatus: () => status,
1277
1757
  onConnectionStatusChanged,
1278
1758
  onRoomsChanged,
@@ -1280,6 +1760,9 @@ export function createChatClient(options) {
1280
1760
  people: readPeople,
1281
1761
  roomMembers,
1282
1762
  toggleReaction,
1763
+ pinMessage,
1764
+ unpinMessage,
1765
+ pinnedMessages,
1283
1766
  startDirectMessage,
1284
1767
  hideDirectMessage,
1285
1768
  acceptInvitation,
@@ -1287,6 +1770,7 @@ export function createChatClient(options) {
1287
1770
  timeline,
1288
1771
  onTimelineChanged,
1289
1772
  paginate,
1773
+ roomFiles,
1290
1774
  sendMessage,
1291
1775
  editMessage,
1292
1776
  deleteMessage,
@@ -1296,5 +1780,10 @@ export function createChatClient(options) {
1296
1780
  canLoadMedia,
1297
1781
  loadMedia,
1298
1782
  sendFile,
1783
+ presence,
1784
+ announcePresence,
1785
+ onPresenceChanged,
1786
+ sendTyping,
1787
+ onTypingChanged,
1299
1788
  };
1300
1789
  }