@wtfalch/chat 0.1.0 → 0.3.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.
@@ -22,7 +22,14 @@ export function formatSize(bytes) {
22
22
  * no URL to put in an `<img src>` -- the bytes have to come through the
23
23
  * client. `null` while it is still coming, and `null` for good if it
24
24
  * cannot be had. */
25
- export function useMediaUrl(client, mxcUri) {
25
+ /** A Matrix event id from the server starts with `$`. A local echo's
26
+ * (`~...`) is not one yet, and the media proxy only serves a file whose
27
+ * message it can find (wtfalch/chat#32), so nothing is fetched until the
28
+ * server's id arrives. */
29
+ function isServerEventId(eventId) {
30
+ return eventId.startsWith('$');
31
+ }
32
+ export function useMediaUrl(client, mxcUri, roomId, eventId) {
26
33
  const [attempt, setAttempt] = useState(0);
27
34
  const [result, setResult] = useState(null);
28
35
  useEffect(() => {
@@ -32,7 +39,7 @@ export function useMediaUrl(client, mxcUri) {
32
39
  let current = null;
33
40
  let cancelled = false;
34
41
  void client
35
- .loadMedia(mxcUri)
42
+ .loadMedia(mxcUri, roomId, eventId)
36
43
  .catch(() => null)
37
44
  .then((url) => {
38
45
  if (cancelled) {
@@ -41,15 +48,18 @@ export function useMediaUrl(client, mxcUri) {
41
48
  return;
42
49
  }
43
50
  current = url;
44
- setResult({ client, mxcUri, url, attempt });
51
+ setResult({ client, mxcUri, eventId, url, attempt });
45
52
  });
46
53
  return () => {
47
54
  cancelled = true;
48
55
  if (current)
49
56
  URL.revokeObjectURL(current);
50
57
  };
51
- }, [client, mxcUri, attempt]);
52
- const current = result?.client === client && result.mxcUri === mxcUri && result.attempt === attempt
58
+ }, [client, mxcUri, roomId, eventId, attempt]);
59
+ const current = result?.client === client &&
60
+ result.mxcUri === mxcUri &&
61
+ result.eventId === eventId &&
62
+ result.attempt === attempt
53
63
  ? result
54
64
  : null;
55
65
  return {
@@ -65,8 +75,8 @@ export function useMediaUrl(client, mxcUri) {
65
75
  * load, or that a reader cannot see, still has to say what it is -- the
66
76
  * agora's Named Station Rule, which is why there is no bare thumbnail
67
77
  * anywhere in here. */
68
- export function AttachmentView({ attachment, client, upload }) {
69
- const { url, failed, retry } = useMediaUrl(client, upload ? null : attachment.mxcUri);
78
+ export function AttachmentView({ attachment, client, roomId, upload }) {
79
+ const { url, failed, retry } = useMediaUrl(client, upload || !isServerEventId(attachment.eventId) ? null : attachment.mxcUri, roomId, attachment.eventId);
70
80
  return (_jsxs("div", { className: "chat-file", children: [attachment.isImage && url && (_jsx("img", { className: "chat-file-image", src: url, alt: attachment.name })), _jsxs("div", { className: "chat-file-row", children: [_jsx("span", { className: "chat-file-name", children: attachment.name }), _jsx("span", { className: "chat-file-size", children: formatSize(attachment.size) }), url && (_jsx("a", { className: "chat-file-get", href: url, download: attachment.name, children: "Download" }))] }), failed && (_jsxs("p", { className: "chat-message-status", children: ["Could not load this file.", ' ', _jsx(Button, { kind: "ghost", size: "sm", onPress: retry, children: "Retry download" })] })), upload && (_jsxs("p", { className: "chat-file-progress", children: [_jsx("progress", { "aria-label": `Uploading ${attachment.name}`, value: upload.loaded, max: upload.total || 1 }), _jsxs("span", { children: [Math.round((upload.loaded / (upload.total || 1)) * 100), "% sent"] })] }))] }));
71
81
  }
72
82
  /** Fills in the `src` of every `img[data-mxc]` the sanitiser left in a
@@ -76,10 +86,10 @@ export function AttachmentView({ attachment, client, upload }) {
76
86
  * nothing is requested until this runs and nothing is ever requested
77
87
  * without the token. An image whose bytes cannot be had simply stays
78
88
  * blank beside its own `alt`. */
79
- export function useInlineMedia(client, host, html) {
89
+ export function useInlineMedia(client, host, html, roomId, eventId) {
80
90
  useEffect(() => {
81
91
  const element = host.current;
82
- if (!element || !html)
92
+ if (!element || !html || !isServerEventId(eventId))
83
93
  return;
84
94
  const images = Array.from(element.querySelectorAll('img[data-mxc]'));
85
95
  if (images.length === 0)
@@ -91,7 +101,7 @@ export function useInlineMedia(client, host, html) {
91
101
  if (!mxcUri)
92
102
  continue;
93
103
  client
94
- .loadMedia(mxcUri)
104
+ .loadMedia(mxcUri, roomId, eventId)
95
105
  .then((url) => {
96
106
  if (!url)
97
107
  return;
@@ -109,5 +119,5 @@ export function useInlineMedia(client, host, html) {
109
119
  for (const url of made)
110
120
  URL.revokeObjectURL(url);
111
121
  };
112
- }, [client, host, html]);
122
+ }, [client, host, html, roomId, eventId]);
113
123
  }
@@ -25,7 +25,7 @@ export function MessageRow({ event, client, roomId, onOpenThread, highlighted })
25
25
  // The sanitiser leaves an allowed image with a reference and no `src`;
26
26
  // this is what puts one there, with the bytes fetched under the token.
27
27
  const body = useRef(null);
28
- useInlineMedia(client, body, html);
28
+ useInlineMedia(client, body, html, roomId, event.id);
29
29
  const [picking, setPicking] = useState(false);
30
30
  const [editing, setEditing] = useState(false);
31
31
  const [confirmingDelete, setConfirmingDelete] = useState(false);
@@ -56,7 +56,7 @@ 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, 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.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
60
  // Asked in the row rather than in a dialog: a redaction cannot
61
61
  // be taken back, and a browser dialog would take the whole
62
62
  // conversation away to ask one question.
@@ -25,8 +25,22 @@ export type ChatRoomSummary = {
25
25
  /** Matrix's own total notification count for this room (`unread_
26
26
  * notifications.notification_count` from `/sync`), zeroed the moment
27
27
  * `markRoomRead` sends a receipt for the newest event. An unanswered
28
- * invitation contributes one until answered or withdrawn. */
28
+ * invitation contributes one until answered or withdrawn.
29
+ *
30
+ * A muted room is the one exception, and by necessity: confirmed live,
31
+ * Synapse's own notification count is itself gated by the room-scoped
32
+ * `dont_notify` rule `muteRoom` writes, so reading it there would
33
+ * report zero forever. A muted room counts itself instead -- every
34
+ * message after the local read-up-to marker, sent by somebody else --
35
+ * which is what keeps this field climbing while `muted` stops the
36
+ * bell. */
29
37
  readonly unreadCount: number;
38
+ /** Whether `muteRoom` has muted this room: a room-scoped push rule with
39
+ * the `dont_notify` action, which is what a list dims. Independent of
40
+ * `unreadCount` -- muting stops a room from notifying, never from
41
+ * counting, so a muted room keeps climbing exactly as an unmuted one
42
+ * would. */
43
+ readonly muted: boolean;
30
44
  };
31
45
  /** Someone this person can start a direct message with: a member of the
32
46
  * company space. Guests are never in the space (chat plan section 5), so
@@ -77,11 +91,21 @@ export type ChatAttachment = {
77
91
  /** Bytes, as the sender reported them. `0` when the sender sent none. */
78
92
  readonly size: number;
79
93
  readonly mxcUri: string;
94
+ /** The message this file was posted in. `loadMedia` needs it: the media
95
+ * proxy only serves a file whose message it can find in the room
96
+ * (wtfalch/chat#32). */
97
+ readonly eventId: string;
80
98
  /** Whether this package will preview it inline. An image, and only ever
81
99
  * by the `mimeType` the sender declared -- which is why the preview is
82
100
  * still fetched through `loadMedia` rather than pointed at. */
83
101
  readonly isImage: boolean;
84
102
  };
103
+ /** One page of `roomFiles`. `next` is `null` when the room has no older
104
+ * files; otherwise pass it back as `before` to continue. */
105
+ export type ChatRoomFilesPage = {
106
+ readonly files: readonly ChatAttachment[];
107
+ readonly next: string | null;
108
+ };
85
109
  /** A file still going up, as `timeline()` shows it: a message that is not
86
110
  * a message yet. `total` is the file's own size, so a caller draws a
87
111
  * proportion without knowing anything about chunks. */
@@ -162,6 +186,16 @@ export type ChatTimelinePage = {
162
186
  * network drop, or recovering from a refused sync position with a fresh
163
187
  * full sync), or not connected at all. */
164
188
  export type ChatConnectionStatus = 'connected' | 'catching-up' | 'offline';
189
+ /** Someone's `m.presence`, reduced to the four states `@wtfalch/design`'s
190
+ * `Presence` dot draws. Matrix itself only ever reports three --
191
+ * `'online'`, `'unavailable'` (this package's `'away'`) and `'offline'` --
192
+ * plus MSC3026's unstable `'busy'` (`org.matrix.msc3026.busy` on the
193
+ * wire), which some clients send and Synapse merely relays without
194
+ * understanding. Anything else this package has never seen, including no
195
+ * presence at all, reads as `'offline'` -- the same state a person who is
196
+ * genuinely offline has, which is the honest answer when the only
197
+ * difference is that nobody has said otherwise (see `ChatClient.presence`). */
198
+ export type Presence = 'online' | 'busy' | 'away' | 'offline';
165
199
  export type CreateChatClientOptions = {
166
200
  /** `POST` here exchanges the agora's current ZITADEL token for a Matrix
167
201
  * one. See `apps/chat-service/README.md`. */
@@ -218,11 +252,70 @@ export type ChatClient = {
218
252
  * reads `hasMore` off that, not off this promise. A no-op, resolved
219
253
  * promise for a room not joined. */
220
254
  paginate: (roomId: string, threadId?: string | null) => Promise<void>;
255
+ /** Every file shared in `roomId`, most recently sent first, without the
256
+ * caller ever paging the room's timeline to find them -- see
257
+ * `ChatAttachment` for what counts as a file. `options.limit` stops
258
+ * once that many have been collected; omitted, this keeps going until
259
+ * Synapse says there is nothing older. The result's `next` is the
260
+ * cursor for the files after these: pass it back as `options.before` to
261
+ * load more (#33). It is Synapse's own opaque `/messages` token, not a
262
+ * `ChatTimelineEvent.id`, and `null` once there is nothing older. With
263
+ * a `limit`, `next` resumes exactly after the last file returned: no
264
+ * file is skipped and none comes back twice. Synapse can hand back a
265
+ * cursor that turns out to have nothing behind it, so the last page may
266
+ * be empty.
267
+ *
268
+ * Filtered server-side, not paged client-side: `GET .../messages`
269
+ * takes Matrix's own `contains_url` filter, and Synapse answers it with
270
+ * only file-bearing events, no matter how much plain conversation sits
271
+ * between them -- confirmed live against this package's own test
272
+ * Synapse (v1.161.0): a single filtered request found a file sent
273
+ * before 50 plain messages that a caller's already-synced timeline and
274
+ * one `paginate()` page (38 events between them) could not have
275
+ * reached. matrix-js-sdk's `TimelineWindow` and `relations` both
276
+ * assume a timeline or an event already in hand; neither expresses
277
+ * "every event of this shape, anywhere in history", so this goes
278
+ * through matrix-js-sdk's own `createMessagesRequest` (oddly marked
279
+ * private, but exported and used exactly this way elsewhere in the
280
+ * SDK) rather than a hand-rolled HTTP call.
281
+ *
282
+ * **Spans the room's threads too, unlike `timeline()`.** `timeline()`
283
+ * deliberately excludes a thread's replies -- they "live in the thread
284
+ * and nowhere else, which is what keeps the room readable" (see above).
285
+ * This does not: `/messages` carries no thread-vs-room distinction at
286
+ * all, so a file shared inside a thread comes back exactly like one
287
+ * shared in the room -- confirmed live against Synapse. Deliberately
288
+ * kept, not just left over: a Files panel asking "every file shared
289
+ * here" means the threads too, and a caller who wants only the room's
290
+ * own files can still get them by asking each thread's `timeline()`
291
+ * what it excludes.
292
+ *
293
+ * **An encrypted room's files never appear.** `m.room.encrypted` has no
294
+ * top-level `url` for `contains_url` to match, so this returns `[]` for
295
+ * a room full of files exactly as it would for one with none -- an
296
+ * empty list from such a room means "cannot see", not "none". Not a bug
297
+ * to fix here: this package never calls `initRustCrypto()` (see the
298
+ * module comment), so an encrypted room's whole timeline is already
299
+ * unusable, not just this method.
300
+ *
301
+ * No files and a `null` cursor before `start()` resolves, or for a room
302
+ * this client does not know. */
303
+ roomFiles: (roomId: string, options?: {
304
+ limit?: number;
305
+ before?: string;
306
+ }) => Promise<ChatRoomFilesPage>;
221
307
  /** Everyone joined to `roomId`, by name, the signed-in person included --
222
308
  * who a message in this room can mention. A room's own membership, not
223
309
  * the company's: mentioning somebody who is not here would notify
224
310
  * nobody. Empty for a room this client does not know. */
225
311
  roomMembers: (roomId: string) => ChatPerson[];
312
+ /** Who has seen `eventId` in `roomId`: every joined person whose read
313
+ * receipt is at this message or a newer one, by name (#31). Leaves out
314
+ * the signed-in person and the message's own sender. Only people who
315
+ * send public read receipts appear. `onTimelineChanged` fires when a
316
+ * receipt moves, so a view re-reads this then. Empty for a room or
317
+ * message this client does not have loaded. */
318
+ readBy: (roomId: string, eventId: string) => ChatPerson[];
226
319
  /** Adds the signed-in person's reaction to `eventId`, or takes it away
227
320
  * if it is already theirs -- one call for both, because that is the one
228
321
  * thing a person ever means by pressing a reaction.
@@ -259,6 +352,12 @@ export type ChatClient = {
259
352
  * thread hanging off a deleted message keeps every reply, and a reader
260
353
  * scrolling past does not have the page move under them. */
261
354
  deleteMessage: (roomId: string, eventId: string) => Promise<void>;
355
+ /** Reports someone's message to the company's chat admins, with a
356
+ * reason (#29). The admins see who reported which message and why
357
+ * (`listReports` in `@wtfalch/chat/admin`), and can remove it or ban
358
+ * its sender. The message stays until they act. Rejects if the server
359
+ * refuses, for instance for a message this person cannot see. */
360
+ reportMessage: (roomId: string, eventId: string, reason: string) => Promise<void>;
262
361
  /** Retries a `'failed'` send with the same content. A no-op if `localId`
263
362
  * is no longer in the room's pending events (already retried, already
264
363
  * settled). */
@@ -280,14 +379,18 @@ export type ChatClient = {
280
379
  * `loadMedia`. This is what the sanitiser asks before it keeps an
281
380
  * `img` at all. */
282
381
  canLoadMedia: (mxcUri: string) => boolean;
283
- /** Fetches `mxcUri` from `/_matrix/client/v1/media/download` with this
284
- * session's token and resolves with an object URL for the bytes, or
285
- * `null` if this session may not load it or the fetch failed.
382
+ /** Fetches `mxcUri` through `apps/chat-service`'s media proxy and
383
+ * resolves with an object URL for the bytes. Synapse's own download
384
+ * endpoint serves any valid token without checking the room
385
+ * (wtfalch/chat#32), so this package never asks it directly. The proxy
386
+ * checks that this session is still in `roomId` and that `eventId`, a
387
+ * message in that room, references `mxcUri`. Resolves with `null` if
388
+ * this session may not load it, either check fails, or the fetch fails.
286
389
  *
287
390
  * **The caller owns the URL and must `URL.revokeObjectURL` it**, or the
288
391
  * blob is held for the life of the document. The React components in
289
392
  * `@wtfalch/chat/react` do that on unmount. */
290
- loadMedia: (mxcUri: string) => Promise<string | null>;
393
+ loadMedia: (mxcUri: string, roomId: string, eventId: string) => Promise<string | null>;
291
394
  /** Sends `file` to `roomId` as `m.image` (an image) or `m.file`, and
292
395
  * returns the id its row carries in `timeline()` at once -- before a
293
396
  * byte has gone up. That row is `'pending'` with `upload` counting, and
@@ -307,6 +410,20 @@ export type ChatClient = {
307
410
  * person scrolls to the newest message. A no-op if the room is unknown
308
411
  * or has no events yet. */
309
412
  markRoomRead: (roomId: string) => Promise<void>;
413
+ /** Stops `roomId` from notifying, without stopping it from counting
414
+ * unread: `muted` and `unreadCount` are two different fields on
415
+ * `ChatRoomSummary`, and this only ever changes one of them -- a person
416
+ * who mutes a noisy room still watches it climb, and still knows to
417
+ * look.
418
+ *
419
+ * Writes (or, unmuting, deletes) a room-scoped push rule carrying the
420
+ * `dont_notify` action, through matrix-js-sdk's own
421
+ * `setRoomMutePushRule` -- scoped `'global'`, an account-wide ruleset
422
+ * rather than a device-specific one, so muting here mutes every device
423
+ * signed into this person's account, not just this session.
424
+ *
425
+ * A no-op for a room this client does not know. */
426
+ muteRoom: (roomId: string, muted: boolean) => Promise<void>;
310
427
  /** Everyone in the company space except the signed-in person, by name.
311
428
  * Empty before `start()` resolves, and empty for a session whose
312
429
  * account is in no space. */
@@ -337,4 +454,142 @@ export type ChatClient = {
337
454
  /** Called with the current status whenever it changes. Returns a
338
455
  * function that stops listening. */
339
456
  onConnectionStatusChanged: (listener: (status: ChatConnectionStatus) => void) => () => void;
457
+ /** Adds `eventId` to `roomId`'s pinned messages -- Matrix's own
458
+ * `m.room.pinned_events` state, one list the whole room shares rather
459
+ * than a per-person bookmark. A no-op, already resolved, if it is
460
+ * already pinned.
461
+ *
462
+ * Ordinary members can call this (ticket #8, settled on
463
+ * wtfalch/agora#255): `apps/chat-service`'s `powerLevels()` grants
464
+ * `m.room.pinned_events` its own power level, 0, overriding the chat
465
+ * plan's "nobody but `@chat-admin` ... pins" on this one point. That
466
+ * reaches only a room created after the change landed -- an existing
467
+ * room's power levels are never backfilled -- so this **rejects**
468
+ * rather than resolving quietly when Synapse refuses it. A caller in an
469
+ * older channel sees the promise reject, not a pin that silently did
470
+ * nothing.
471
+ *
472
+ * **Safe to call twice in a row from one client** --
473
+ * `await pinMessage(a); await pinMessage(b);`, or neither awaited
474
+ * first -- and have both survive: each call is queued behind this
475
+ * client's own last write for the room rather than built on a read of
476
+ * `roomId`'s local state, which a resolved `sendStateEvent` does not
477
+ * prove has caught up yet (confirmed live: it had not, even after a
478
+ * full `await`).
479
+ *
480
+ * **Not safe across two `ChatClient`s** -- two accounts, or two
481
+ * devices of one account -- pinning in the same room at once. Nothing
482
+ * sequences *between* clients, and Matrix gives `m.room.pinned_events`
483
+ * no compare-and-swap: it is one state value, replaced whole, so a
484
+ * genuine race is decided by Synapse's own state resolution, never
485
+ * merged, and can still silently drop one side's pin. This is a limit
486
+ * the protocol imposes, not a gap this method leaves open by
487
+ * accident. */
488
+ pinMessage: (roomId: string, eventId: string) => Promise<void>;
489
+ /** Takes `eventId` back out of `roomId`'s pinned messages. A no-op,
490
+ * already resolved, if it is not pinned. Needs the same power level as
491
+ * `pinMessage`, rejects the same way in a room whose power levels
492
+ * predate ticket #8, and carries the same two guarantees: safe to
493
+ * chain with `pinMessage`/`unpinMessage` calls from this client, not
494
+ * safe against another client writing to the same room's pinned list
495
+ * at once. */
496
+ unpinMessage: (roomId: string, eventId: string) => Promise<void>;
497
+ /** `roomId`'s currently pinned messages, in the order `m.room.pinned_
498
+ * events` lists them, each reduced the same way `timeline()` reduces a
499
+ * message. A pinned id this client cannot find an event for -- paginated
500
+ * away, or never loaded -- is left out rather than drawn as a gap.
501
+ * Empty for a room with nothing pinned, or one this client does not
502
+ * know. */
503
+ pinnedMessages: (roomId: string) => readonly ChatTimelineEvent[];
504
+ /** Somebody's presence, read off matrix-js-sdk's own `User` object --
505
+ * never fetched, and never kept up to date by this call itself, only by
506
+ * whatever `m.presence` Matrix has already delivered through sync. A
507
+ * user this session has not seen a presence event for, the signed-in
508
+ * person's own id included, reads as `'offline'`.
509
+ *
510
+ * **Every company's Synapse ships with presence off** (ticket #7's own
511
+ * finding, tracked at `wtfalch/app-template#352`, `bootstrap/steps/
512
+ * chat-instance.ts:142`): until that lands, Synapse never emits an
513
+ * `m.presence` event at all, so this method is honest and returns
514
+ * `'offline'` for everyone, always, in production -- not because nobody
515
+ * is online, but because the server never says. Typing is unaffected.
516
+ *
517
+ * **`'away'` only happens if somebody announces it.** Left alone, a
518
+ * syncing client re-asserts `'online'` on every poll, so a person with
519
+ * a tab open all night reads as available forever. `announcePresence`
520
+ * is what breaks that, and nothing else in this package does -- see its
521
+ * own comment for why. `'busy'` still comes only from some *other*
522
+ * Matrix client (MSC3026, unstable, and off unless a homeserver opts in
523
+ * with `msc3026_enabled`). */
524
+ presence: (userId: string) => Presence;
525
+ /** Says whether the signed-in person is at their machine. This is the
526
+ * only way `'away'` is ever reachable, and a caller that never calls it
527
+ * leaves everyone reading `'online'` for as long as a tab stays open.
528
+ *
529
+ * **The SDK cannot decide this for itself.** A library sees method
530
+ * calls, and a cron job calling `timeline()` looks exactly like a person
531
+ * reading. Only the app knows about the Page Visibility API, a locked
532
+ * screen, and real keystrokes, so the app is what calls this --
533
+ * `'away'` when it stops seeing activity, `'online'` on the next real
534
+ * input. That half is Agora's, and is not built yet.
535
+ *
536
+ * **Why it takes two requests.** Confirmed live against Synapse
537
+ * v1.161.0: every `/sync` carries an implicit `set_presence`, so a plain
538
+ * `PUT .../presence/status` is undone by this session's own next poll
539
+ * seconds later (`handlers/presence.py`'s `user_syncing` ->
540
+ * `set_state(is_sync=True)`, which exempts only `'busy'`). Announcing
541
+ * changes the sync parameter itself, which is what makes it stick, and
542
+ * also sends the `PUT` so the change lands now rather than whenever the
543
+ * current long poll happens to return.
544
+ *
545
+ * **Remembered, not just sent.** An announcement survives this client's
546
+ * own restarts -- a dead token, a refused sync position, a `stop()` and
547
+ * `start()` -- because each of those builds a fresh sync loop that would
548
+ * otherwise default the person back to `'online'`. Announcing before
549
+ * `start()` sends nothing, and applies to the session that follows.
550
+ *
551
+ * **Never rejects, and never needs retrying.** Synapse allows one
552
+ * presence change per ten seconds and refuses the rest, so flipping
553
+ * idle and back quickly means the `PUT` is turned away -- but the
554
+ * announcement still stands, because what carries it is the sync, and
555
+ * the state catches up within a poll. Call it as often as real activity
556
+ * suggests; it is a statement of the current truth, not a queued
557
+ * command. */
558
+ announcePresence: (presence: 'online' | 'away') => Promise<void>;
559
+ /** Called whenever somebody's presence changes, with just the people who
560
+ * changed -- one entry, almost always, since Matrix delivers `m.presence`
561
+ * one person at a time. Returns a function that stops listening.
562
+ *
563
+ * Nothing is replayed on subscribing: a caller that wants a room's
564
+ * current presence has to read `presence(userId)` for each member first
565
+ * and use this only to hear about what changes after. */
566
+ onPresenceChanged: (listener: (changed: ReadonlyMap<string, Presence>) => void) => () => void;
567
+ /** Tells `roomId` the signed-in person has started, or stopped, typing --
568
+ * `m.typing`, which is not an event: nothing lands in `timeline()`, and
569
+ * nothing is retried if this fails, the same as any other presence-like
570
+ * signal nobody is meant to notice going missing once.
571
+ *
572
+ * **Not a heartbeat.** Matrix expires a typing state on its own after a
573
+ * server-side timeout (this sends the SDK's own default, 20 seconds) --
574
+ * so a composer that wants the other side to keep seeing "typing" while
575
+ * a person keeps composing has to call this again itself, on further
576
+ * keystrokes, rather than once at the start. Sending `false` (a blurred
577
+ * composer, a sent message) clears it at once rather than waiting that
578
+ * out. */
579
+ sendTyping: (roomId: string, typing: boolean) => void;
580
+ /** Called with everyone currently typing in `roomId`, other than the
581
+ * signed-in person -- Matrix's own `m.typing` lists every typing member
582
+ * including this session, and a person is never told they are typing.
583
+ * Returns a function that stops listening. A no-op subscription, never
584
+ * called, for a room this client does not know: `m.typing` is scoped to
585
+ * a room this client has joined, so one it has not is simply silent,
586
+ * the same as `onTimelineChanged` on an unknown room.
587
+ *
588
+ * **Matrix never says "stopped" for a room you left.** `m.typing` is
589
+ * ephemeral, resent by the server as the complete current list on every
590
+ * change -- but a room you have left sends nothing further at all, so a
591
+ * list this call last reported for it can go stale forever rather than
592
+ * clearing to empty. A caller that cares should stop listening itself
593
+ * once the room is gone from `rooms()`. */
594
+ onTypingChanged: (roomId: string, listener: (userIds: readonly string[]) => void) => () => void;
340
595
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",