@wtfalch/chat 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -148,6 +148,19 @@ starts a background fetch and reads `null` until it resolves, the same
148
148
  lazy-then-cached shape as most of this package's reads that reach the
149
149
  network.
150
150
 
151
+ **The automatic `meeting` overlay** ([#46](https://github.com/wtfalch/chat/issues/46),
152
+ decision: [wtfalch/calls#39](https://github.com/wtfalch/calls/issues/39)).
153
+ `chat.applyAutomaticStatus(userId, { kind: 'meeting' | null, sequence })`
154
+ composes an ephemeral overlay over `status()`'s durable value --
155
+ `automatic ?? explicit` -- rather than replacing it, so a call ending never
156
+ loses whatever the person had already set (vacation, busy, sick). It is
157
+ never written into the explicit status's own profile field: it lives only
158
+ in this client's memory, for the life of the session. `sequence` is the
159
+ caller's own monotonic counter for `userId`; a call whose `sequence` is not
160
+ strictly greater than the last one applied for that `userId` is dropped, so
161
+ a retried or out-of-order delivery can never erase a fresher value with a
162
+ stale one.
163
+
151
164
  **Off until Synapse turns it on.** MSC4133 is gated by
152
165
  `experimental_features.msc4133_enabled`, off by default, tracked at
153
166
  [wtfalch/foundry#41](https://github.com/wtfalch/foundry/issues/41) the
@@ -262,6 +275,21 @@ with `redactMessage(roomId, eventId)`, and bans a person from a channel with
262
275
  `banPerson(roomId, subject, reason?)` until `unbanPerson(roomId, subject)`.
263
276
  Admins act as `@chat-admin`, and only in channels the service created.
264
277
 
278
+ **Topics, browsing and new rooms.** `ChatRoomSummary.topic` is the room's
279
+ `m.room.topic` as plain text (trimmed, at most `MAX_TOPIC_LENGTH` characters),
280
+ and `canSetTopic` says whether this person's power level allows
281
+ `chat.setRoomTopic(roomId, topic)`, which rejects without calling the
282
+ homeserver when it does not. `chat.browseRooms()` lists the company space's
283
+ `public` and `restricted` child rooms on this server that the person is not
284
+ in (`{ id, name, topic?, memberCount }`, by name); a room from another
285
+ server, an invite-only room and a sub-space never appear.
286
+ `chat.joinBrowsableRoom(roomId)` joins one of them and rejects for any other
287
+ id. `chat.createRoom({ name, topic?, visibility: 'public' | 'private' })`
288
+ creates a channel through `apps/chat-service`'s `POST /_chat/rooms` (the
289
+ homeserver refuses a named room from a member), under the same rules as the
290
+ admin API, with the creator as its admin, and resolves with the room id once
291
+ it is in `rooms()`.
292
+
265
293
  **Pinned messages** ([#8](https://github.com/wtfalch/chat/issues/8)).
266
294
  `chat.pinMessage(roomId, eventId)` and `chat.unpinMessage(roomId, eventId)` add
267
295
  to and take from Matrix's own `m.room.pinned_events` state, one list the whole
@@ -21,7 +21,10 @@ export type AdminChannel = {
21
21
  };
22
22
  export type ChannelPage = {
23
23
  channels: AdminChannel[];
24
- next_cursor: string | null;
24
+ nextCursor: string | null;
25
+ /** @deprecated Use `nextCursor`; the server stops sending this alias after
26
+ * one minor (contracts#11, chat#76). */
27
+ next_cursor?: string | null;
25
28
  };
26
29
  export type ChannelInput = {
27
30
  name: string;
@@ -40,7 +43,10 @@ export type AuditRow = {
40
43
  };
41
44
  export type AuditPage = {
42
45
  rows: AuditRow[];
43
- next_cursor: string | null;
46
+ nextCursor: string | null;
47
+ /** @deprecated Use `nextCursor`; the server stops sending this alias after
48
+ * one minor (contracts#11, chat#76). */
49
+ next_cursor?: string | null;
44
50
  };
45
51
  /** One Matrix session the exchange minted for a person -- one per device. */
46
52
  export type PersonSession = {
@@ -58,6 +64,8 @@ export type ContentReport = {
58
64
  reporter: string | null;
59
65
  sender: string | null;
60
66
  reason: string | null;
67
+ /** The report's room is a channel this service manages, so a ban can apply. */
68
+ manageable: boolean;
61
69
  };
62
70
  export type PageInput = {
63
71
  limit?: number;
@@ -122,7 +130,7 @@ export declare function createChatAdmin(options: ChatAdminOptions): {
122
130
  /** What members reported with `reportMessage`, newest first. */
123
131
  listReports: (input?: PageInput) => Promise<{
124
132
  reports: ContentReport[];
125
- next_cursor: string | null;
133
+ nextCursor: string | null;
126
134
  }>;
127
135
  deactivatePerson: (subject: string) => Promise<{
128
136
  user_id: string;
@@ -33,6 +33,24 @@ export function chatJoinUrl(agoraUrl, agoraId, roomId, threadId) {
33
33
  : `${origin(agoraUrl)}${path}`;
34
34
  }
35
35
  const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ /** Reads a page from a service of either vintage: a page carrying only the
37
+ * deprecated `next_cursor` is read as `nextCursor`, and a report with no
38
+ * `manageable` (a service from before it existed) is read as `false`, so
39
+ * Ban is not offered for it. Mutates `data`, which `request` just parsed. */
40
+ function readPageDefaults(data) {
41
+ if (!record(data))
42
+ return data;
43
+ if (data.nextCursor === undefined && data.next_cursor !== undefined) {
44
+ data.nextCursor = data.next_cursor;
45
+ }
46
+ if (Array.isArray(data.reports)) {
47
+ for (const report of data.reports) {
48
+ if (record(report) && report.manageable === undefined)
49
+ report.manageable = false;
50
+ }
51
+ }
52
+ return data;
53
+ }
36
54
  const nullableString = (value) => value === null || typeof value === 'string';
37
55
  function channel(value) {
38
56
  return (record(value) &&
@@ -97,6 +115,7 @@ export function createChatAdmin(options) {
97
115
  : 'request_failed';
98
116
  throw new ChatAdminError(response.status, code);
99
117
  }
118
+ readPageDefaults(data);
100
119
  if (!valid(data))
101
120
  throw new ChatAdminError(502, 'invalid_response');
102
121
  return data;
@@ -108,7 +127,7 @@ export function createChatAdmin(options) {
108
127
  listChannels: (input) => request('GET', `/channels${pageQuery(100, input)}`, (data) => record(data) &&
109
128
  Array.isArray(data.channels) &&
110
129
  data.channels.every(channel) &&
111
- nullableString(data.next_cursor)),
130
+ nullableString(data.nextCursor)),
112
131
  getChannel: (roomId) => request('GET', roomPath(roomId), channel),
113
132
  createChannel: (input) => request('POST', '/channels', roomResult, input),
114
133
  updateChannel: (roomId, input) => request('PATCH', roomPath(roomId), roomResult, input),
@@ -130,8 +149,9 @@ export function createChatAdmin(options) {
130
149
  Array.isArray(data.reports) &&
131
150
  data.reports.every((report) => record(report) &&
132
151
  typeof report.id === 'string' &&
133
- ['received_at', 'room_id', 'event_id', 'reporter', 'sender', 'reason'].every((key) => nullableString(report[key]))) &&
134
- nullableString(data.next_cursor)),
152
+ ['received_at', 'room_id', 'event_id', 'reporter', 'sender', 'reason'].every((key) => nullableString(report[key])) &&
153
+ typeof report.manageable === 'boolean') &&
154
+ nullableString(data.nextCursor)),
135
155
  deactivatePerson: (subject) => request('DELETE', `/people/${identifier(subject)}`, (data) => record(data) && typeof data.user_id === 'string' && data.deactivated === true),
136
156
  /** Every Matrix session signed in as `subject` (#30). */
137
157
  listSessions: (subject) => request('GET', `/people/${identifier(subject)}/sessions`, (data) => record(data) &&
@@ -153,7 +173,7 @@ export function createChatAdmin(options) {
153
173
  audit: (input) => request('GET', `/audit${pageQuery(200, input)}`, (data) => record(data) &&
154
174
  Array.isArray(data.rows) &&
155
175
  data.rows.every(auditRow) &&
156
- nullableString(data.next_cursor)),
176
+ nullableString(data.nextCursor)),
157
177
  };
158
178
  }
159
179
  /** For a host's visibility gate, using claims ALREADY verified by its auth
@@ -44,7 +44,10 @@ export type AdminOverview = ChannelPage & {
44
44
  };
45
45
  export type ReportPage = {
46
46
  reports: ContentReport[];
47
- next_cursor: string | null;
47
+ nextCursor: string | null;
48
+ /** @deprecated Use `nextCursor`; the server stops sending this alias after
49
+ * one minor (contracts#11, chat#76). */
50
+ next_cursor?: string | null;
48
51
  };
49
52
  export type ChatAdminActions = {
50
53
  load: (cursor?: string) => Promise<AdminOverview>;
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { Button, Field, Input, Select, Textarea } from '@wtfalch/design';
4
- import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
4
+ import { useEffect, useId, useLayoutEffect, useRef, useState, } from 'react';
5
5
  /** The SDK owns the controls. Hosts pass authenticated actions, not tokens;
6
6
  * every action must authorize its own caller before reaching the service. */
7
7
  export function ChatAdminPanel({ actions }) {
@@ -91,7 +91,7 @@ export function ChatAdminPanel({ actions }) {
91
91
  return (_jsxs("section", { className: "chat-admin", "aria-label": "Chat settings", "aria-busy": busy, children: [message && _jsx("p", { role: failed ? 'alert' : 'status', children: message }), _jsxs("div", { className: "chat-admin-toolbar", children: [_jsx("h2", { ref: heading, tabIndex: -1, children: "Channels" }), _jsx(Button, { disabled: busy, onPress: () => void load(cursor), children: "Refresh" })] }), !view ? (_jsx("p", { children: busy ? 'Loading chat settings…' : 'Settings are unavailable.' })) : (_jsx(_Fragment, { children: _jsxs("fieldset", { disabled: busy, className: "chat-admin-fields", children: [_jsxs("details", { children: [_jsx("summary", { children: "Create a channel" }), _jsx(ChannelForm, { onSubmit: (input) => run({ operation: 'create', input }) })] }), view.channels.length === 0 ? (_jsx("p", { children: "No managed channels on this page. The default general channel stays in Agora." })) : (_jsx(Field, { label: "Channel", children: _jsxs(Select, { value: selected ?? '', onChange: (event) => {
92
92
  if (mayDiscard())
93
93
  setSelected(event.target.value);
94
- }, children: [_jsx("option", { value: "", children: "Choose a channel" }), view.channels.map((item) => (_jsx("option", { value: item.room_id, children: `${item.name}${item.archived ? ' · Archived' : ''}${item.visibility === 'private' ? ' · Private' : ''}` }, item.room_id)))] }) })), _jsxs("div", { className: "chat-admin-toolbar", children: [cursor && _jsx(Button, { onPress: () => void load(), children: "First page" }), view.next_cursor && (_jsx(Button, { onPress: () => void load(view.next_cursor ?? undefined), children: "Next channels" }))] }), channel && (_jsx(ChannelSettings, { channel: channel, people: view.people, run: run, onDirty: (value) => {
94
+ }, children: [_jsx("option", { value: "", children: "Choose a channel" }), view.channels.map((item) => (_jsx("option", { value: item.room_id, children: `${item.name}${item.archived ? ' · Archived' : ''}${item.visibility === 'private' ? ' · Private' : ''}` }, item.room_id)))] }) })), _jsxs("div", { className: "chat-admin-toolbar", children: [cursor && _jsx(Button, { onPress: () => void load(), children: "First page" }), view.nextCursor && (_jsx(Button, { onPress: () => void load(view.nextCursor ?? undefined), children: "Next channels" }))] }), channel && (_jsx(ChannelSettings, { channel: channel, people: view.people, run: run, onDirty: (value) => {
95
95
  dirty.current = value;
96
96
  } }, `${channel.room_id}:${channel.name}:${channel.topic}`)), _jsxs("details", { children: [_jsx("summary", { children: "Remove a person from Chat" }), _jsx("p", { children: "This ends their Chat sessions. Their existing messages remain." }), _jsx(RemovePerson, { people: view.people, run: run })] }), _jsxs("details", { children: [_jsx("summary", { children: "Sessions" }), _jsx("p", { children: "End one of a person's signed-in Chat sessions on a single device." }), _jsx(SessionsPanel, { people: view.people, loadSessions: actions.loadSessions, run: run })] }), _jsxs("details", { children: [_jsx("summary", { children: "Reports" }), _jsx("p", { children: "What members have reported. Banning removes the sender from that channel." }), _jsx(ReportsPanel, { loadReports: actions.loadReports, run: run })] })] }) }))] }));
97
97
  }
@@ -202,12 +202,27 @@ function SessionsPanel({ people, loadSessions, run, }) {
202
202
  }
203
203
  /** Lists what members have reported and bans a report's sender from the
204
204
  * channel it happened in (#29, #58). Never shows the reported message's
205
- * text -- `ContentReport` never carries it. */
205
+ * text -- `ContentReport` never carries it.
206
+ *
207
+ * A report's `room_id` can name a room this service does not manage --
208
+ * a direct message, the general channel, the company space itself --
209
+ * where `ban` always refuses with "channel not found" (#94). the server
210
+ * marks each report `manageable` (its room is a channel this service owns),
211
+ * and a room that is not gets no Ban control rather than one that fails
212
+ * every time it is pressed. The flag is per report, so it holds on every
213
+ * page of reports and for channels on any page of the channel list.
214
+ *
215
+ * Banning has no server-side "already banned" flag to read back, so this
216
+ * component remembers, for its own lifetime, which (room, subject) pairs
217
+ * it has banned and hides their Ban control -- the report itself stays
218
+ * in Synapse's list forever, so a refresh alone would show the same
219
+ * button again. */
206
220
  function ReportsPanel({ loadReports, run, }) {
207
221
  const [page, setPage] = useState(null);
208
222
  const [cursor, setCursor] = useState();
209
223
  const [loading, setLoading] = useState(false);
210
224
  const [failed, setFailed] = useState(false);
225
+ const [banned, setBanned] = useState(new Set());
211
226
  const started = useRef(false);
212
227
  const latest = useRef(0);
213
228
  const requested = useRef(undefined);
@@ -243,20 +258,31 @@ function ReportsPanel({ loadReports, run, }) {
243
258
  return (_jsxs("div", { className: "chat-admin-form", children: [loading && _jsx("p", { children: "Loading reports\u2026" }), !loading && failed && (_jsxs("p", { role: "alert", children: ["Reports could not be loaded.", ' ', _jsx(Button, { onPress: () => void refresh(requested.current), children: "Try again" })] })), !loading && page && page.reports.length === 0 && _jsx("p", { children: "No open reports." }), !loading && page && page.reports.length > 0 && (_jsx("ul", { className: "chat-admin-people", children: page.reports.map((report) => {
244
259
  const roomId = report.room_id;
245
260
  const subject = report.sender;
246
- return (_jsxs("li", { children: [_jsxs("span", { children: [subject ?? 'Unknown sender', report.reason ? ` · ${report.reason}` : ''] }), roomId && subject && (_jsx(Confirm, { label: "Ban", consequence: `Ban ${subject} from this channel?`, onConfirm: async () => {
247
- const ok = await run({
248
- operation: 'ban',
249
- roomId,
250
- subject,
251
- reason: report.reason ?? undefined,
252
- });
253
- if (ok)
261
+ const pairId = roomId && subject ? `${roomId}:${subject}` : null;
262
+ const canBan = Boolean(roomId && subject && report.manageable);
263
+ const alreadyBanned = pairId !== null && banned.has(pairId);
264
+ return (_jsxs("li", { children: [_jsxs("span", { children: [subject ?? 'Unknown sender', report.reason ? ` · ${report.reason}` : ''] }), roomId && subject && canBan && !alreadyBanned && (_jsx(BanControl, { subject: subject, initialReason: report.reason, onConfirm: async (reason) => {
265
+ const ok = await run({ operation: 'ban', roomId, subject, reason });
266
+ if (ok) {
267
+ setBanned((prev) => new Set(prev).add(`${roomId}:${subject}`));
254
268
  await refresh(cursor);
269
+ }
255
270
  return ok;
256
271
  } }))] }, report.id));
257
- }) })), _jsxs("div", { className: "chat-admin-toolbar", children: [cursor && _jsx(Button, { onPress: () => void refresh(), children: "First page" }), page?.next_cursor && (_jsx(Button, { onPress: () => void refresh(page.next_cursor ?? undefined), children: "Next reports" }))] })] }));
272
+ }) })), _jsxs("div", { className: "chat-admin-toolbar", children: [cursor && _jsx(Button, { onPress: () => void refresh(), children: "First page" }), page?.nextCursor && (_jsx(Button, { onPress: () => void refresh(page.nextCursor ?? undefined), children: "Next reports" }))] })] }));
258
273
  }
259
- function Confirm({ label, consequence, onConfirm, }) {
274
+ /** `apps/chat-service`'s `banPersonOp` refuses a reason over 500 characters
275
+ * with a 400 -- a report's own `reason` came from whoever filed it, over
276
+ * an endpoint this package does not cap, so it can already be longer. This
277
+ * mirrors that limit in the form (`maxLength` plus a counter) so a long
278
+ * reason fails here, editably, rather than as an opaque server error after
279
+ * "Confirm ban" (#94). */
280
+ const BAN_REASON_MAX_LENGTH = 500;
281
+ function BanControl({ subject, initialReason, onConfirm, }) {
282
+ const [reason, setReason] = useState((initialReason ?? '').slice(0, BAN_REASON_MAX_LENGTH));
283
+ return (_jsx(Confirm, { label: "Ban", consequence: `Ban ${subject} from this channel?`, onConfirm: () => onConfirm(reason.trim() ? reason : undefined), children: _jsx(Field, { label: "Reason", hint: `${reason.length}/${BAN_REASON_MAX_LENGTH} characters`, children: _jsx(Textarea, { value: reason, onChange: (event) => setReason(event.target.value.slice(0, BAN_REASON_MAX_LENGTH)), maxLength: BAN_REASON_MAX_LENGTH }) }) }));
284
+ }
285
+ function Confirm({ label, consequence, onConfirm, children, }) {
260
286
  const [confirming, setConfirming] = useState(false);
261
287
  const trigger = useRef(null);
262
288
  const cancelControl = useRef(null);
@@ -276,7 +302,7 @@ function Confirm({ label, consequence, onConfirm, }) {
276
302
  }
277
303
  return (_jsx("fieldset", { className: "chat-admin-confirm", "aria-label": label, "aria-describedby": confirming ? descriptionId : undefined, children: !confirming ? (_jsx("span", { ref: (node) => {
278
304
  trigger.current = node?.querySelector('button') ?? null;
279
- }, children: _jsx(Button, { kind: "danger", onPress: () => setConfirming(true), children: label }) })) : (_jsxs(_Fragment, { children: [_jsx("p", { id: descriptionId, children: consequence }), _jsxs(Button, { kind: "danger", onPress: () => void onConfirm().then((ok) => {
305
+ }, children: _jsx(Button, { kind: "danger", onPress: () => setConfirming(true), children: label }) })) : (_jsxs(_Fragment, { children: [_jsx("p", { id: descriptionId, children: consequence }), children, _jsxs(Button, { kind: "danger", onPress: () => void onConfirm().then((ok) => {
280
306
  if (ok)
281
307
  cancel();
282
308
  }), children: ["Confirm ", label.toLowerCase()] }), _jsx("span", { ref: cancelControl, children: _jsx(Button, { onPress: cancel, children: "Cancel" }) })] })) }));
@@ -4,6 +4,13 @@ import type { ChatClient, CreateChatClientOptions } from './types.ts';
4
4
  * so at once, rather than after the whole thing has gone up and Synapse
5
5
  * has refused it. */
6
6
  export declare const MAX_UPLOAD_BYTES: number;
7
+ /** The longest topic this package shows or sends, in characters. */
8
+ export declare const MAX_TOPIC_LENGTH = 250;
9
+ /** The longest room name this package shows from a room it has not joined. */
10
+ export declare const MAX_ROOM_NAME_LENGTH = 100;
11
+ /** A topic is whatever its setter wrote, so it is normalised on the way in
12
+ * from a room and on the way out to one. */
13
+ export declare function normaliseTopic(raw: string): string;
7
14
  /**
8
15
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
9
16
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -77,12 +77,51 @@ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
77
77
  url.searchParams.set('eventId', eventId);
78
78
  return url.toString();
79
79
  }
80
+ /** The longest topic this package shows or sends, in characters. */
81
+ export const MAX_TOPIC_LENGTH = 250;
82
+ /** The longest room name this package shows from a room it has not joined. */
83
+ export const MAX_ROOM_NAME_LENGTH = 100;
84
+ const BROWSE_PAGE_SIZE = 50;
85
+ const BROWSE_MAX_PAGES = 10;
86
+ const BROWSE_TIMEOUT_MS = 15_000;
87
+ const CREATE_ROOM_TIMEOUT_MS = 20_000;
88
+ /** Untrusted text made plain: control characters out (a line break becomes
89
+ * a space, runs of space collapse), trimmed, capped to `max` characters. */
90
+ function normaliseText(raw, max) {
91
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point
92
+ const plain = raw.replace(/[\s\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, ' ').trim();
93
+ return [...plain].slice(0, max).join('').trim();
94
+ }
95
+ /** A topic is whatever its setter wrote, so it is normalised on the way in
96
+ * from a room and on the way out to one. */
97
+ export function normaliseTopic(raw) {
98
+ return normaliseText(raw, MAX_TOPIC_LENGTH);
99
+ }
100
+ function withTimeout(call, ms, what) {
101
+ let timer;
102
+ const timeout = new Promise((_, reject) => {
103
+ timer = setTimeout(() => reject(new Error(`chat: ${what} timed out`)), ms);
104
+ });
105
+ return Promise.race([call, timeout]).finally(() => clearTimeout(timer));
106
+ }
80
107
  /** Where a thread's follow state lives: `apps/chat-service`'s
81
108
  * `/_chat/threads/...`, next to `exchangeUrl` like the media proxy. */
82
109
  function threadFollowUrl(exchangeUrl, roomId, threadId) {
83
110
  const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
84
111
  return `${base}/_chat/threads/${encodeURIComponent(roomId)}/${encodeURIComponent(threadId)}/follow`;
85
112
  }
113
+ /** Where a member creates a channel: `apps/chat-service`'s
114
+ * `POST /_chat/rooms`, next to `exchangeUrl`. */
115
+ function createRoomUrl(exchangeUrl) {
116
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
117
+ return `${base}/_chat/rooms`;
118
+ }
119
+ /** Where the automatic status overlay a person's call pushed is read back:
120
+ * `apps/chat-service`'s `GET /_chat/status/{userId}`, next to `exchangeUrl`. */
121
+ function automaticStatusUrl(exchangeUrl, userId) {
122
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
123
+ return `${base}/_chat/status/${encodeURIComponent(userId)}`;
124
+ }
86
125
  function setDraftAccountData(target, roomId, content) {
87
126
  return target.setRoomAccountData(roomId, DRAFT_EVENT_TYPE, content);
88
127
  }
@@ -93,6 +132,10 @@ function setDraftAccountData(target, roomId, content) {
93
132
  * wanting the far end to keep seeing "typing" through a long pause calls
94
133
  * this again itself; nothing here renews it on a timer. */
95
134
  const TYPING_TIMEOUT_MS = 20_000;
135
+ /** How long a fetched automatic-status overlay is trusted before `status()`
136
+ * reads it again. The overlay is ephemeral and nothing pushes it here, so
137
+ * without this a "meeting" would show until the session ended. */
138
+ const AUTOMATIC_STATUS_TTL_MS = 60_000;
96
139
  /** How many *matching* events `roomFiles` asks Synapse for per request.
97
140
  * Unlike `paginate`'s 30 (which bounds how much plain conversation a
98
141
  * person scrolls through at once), this only ever counts events that
@@ -191,6 +234,15 @@ export function createChatClient(options) {
191
234
  * the first is still in flight. */
192
235
  const chatStatusCache = new Map();
193
236
  const chatStatusListeners = new Set();
237
+ /** See `ChatClient.applyAutomaticStatus`. Kept apart from
238
+ * `chatStatusCache` -- the person's own durable, explicit choice --
239
+ * because this is the ephemeral overlay that composes over it rather
240
+ * than replacing it; `effectiveStatus` is the one place the two are
241
+ * read together. */
242
+ const automaticStatusCache = new Map();
243
+ /** When the service was last asked for each person's overlay (attempt,
244
+ * not success, so a failing service is not asked on every read). */
245
+ const automaticStatusAskedAt = new Map();
194
246
  /** Who is currently typing, per room -- built up from `RoomMemberEvent.
195
247
  * Typing` one member at a time, the signed-in person's own id never
196
248
  * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
@@ -476,6 +528,8 @@ export function createChatClient(options) {
476
528
  markedUnread: isMarkedUnread(room),
477
529
  archived: roomArchived(room),
478
530
  starred: FAVOURITE_TAG in room.tags,
531
+ topic: roomTopic(room),
532
+ canSetTopic: canSetTopic(target, room),
479
533
  };
480
534
  });
481
535
  }
@@ -1468,9 +1522,14 @@ export function createChatClient(options) {
1468
1522
  .filter((upload) => (upload.threadId ?? null) === threadId)
1469
1523
  .map((upload) => toUploadEvent(room, upload));
1470
1524
  }
1525
+ /** `room.findEventById` only walks threads matrix-js-sdk has already
1526
+ * built a `Thread` for -- the same gap `findEvent` above exists to
1527
+ * cover -- so a reply that failed before any reply of its thread ever
1528
+ * synced is invisible to it. Falling back to `findEvent`'s walk is what
1529
+ * lets a failed thread reply be found at all, for retry or cancel. */
1471
1530
  function findPendingEvent(roomId, localId) {
1472
1531
  const room = client?.getRoom(roomId);
1473
- const event = room?.findEventById(localId);
1532
+ const event = room ? findEvent(room, localId) : undefined;
1474
1533
  return room && event ? { room, event } : undefined;
1475
1534
  }
1476
1535
  function retryMessage(roomId, localId) {
@@ -1493,7 +1552,17 @@ export function createChatClient(options) {
1493
1552
  const found = findPendingEvent(roomId, localId);
1494
1553
  if (!found)
1495
1554
  return;
1496
- client.resendEvent(found.event, found.room).catch(() => { });
1555
+ // The event's own relation, not the options a caller no longer has:
1556
+ // `threadRootId` reads straight off its `m.relates_to`, so it is right
1557
+ // whether or not matrix-js-sdk has built a `Thread` around it yet.
1558
+ const threadId = found.event.threadRootId;
1559
+ client
1560
+ .resendEvent(found.event, found.room)
1561
+ .then(() => {
1562
+ if (threadId)
1563
+ autoFollowThread(roomId, threadId);
1564
+ })
1565
+ .catch(() => { });
1497
1566
  }
1498
1567
  function cancelMessage(roomId, localId) {
1499
1568
  if (!client)
@@ -1579,6 +1648,188 @@ export function createChatClient(options) {
1579
1648
  ?.getContent()?.events_default;
1580
1649
  return Number(eventsDefault ?? 0) >= 100;
1581
1650
  }
1651
+ function roomTopic(room) {
1652
+ const raw = room.currentState
1653
+ .getStateEvents(EventType.RoomTopic, '')
1654
+ ?.getContent().topic;
1655
+ const topic = typeof raw === 'string' ? normaliseTopic(raw) : '';
1656
+ return topic === '' ? undefined : topic;
1657
+ }
1658
+ function canSetTopic(target, room) {
1659
+ const userId = target.getUserId();
1660
+ return (userId !== null &&
1661
+ room.getMyMembership() === KnownMembership.Join &&
1662
+ room.currentState.maySendStateEvent(EventType.RoomTopic, userId));
1663
+ }
1664
+ /** The company space(s): joined `m.space` rooms hosted on this person's
1665
+ * own homeserver. */
1666
+ function companySpaces(target) {
1667
+ const server = homeserverName(target.getUserId());
1668
+ return target
1669
+ .getRooms()
1670
+ .filter((room) => room.isSpaceRoom() &&
1671
+ room.getMyMembership() === KnownMembership.Join &&
1672
+ server !== undefined &&
1673
+ homeserverName(room.roomId) === server);
1674
+ }
1675
+ function homeserverName(id) {
1676
+ const at = id?.indexOf(':') ?? -1;
1677
+ return id && at > 0 ? id.slice(at + 1) : undefined;
1678
+ }
1679
+ /** See `ChatClient.browseRooms`. */
1680
+ async function browseRooms() {
1681
+ const target = client;
1682
+ if (!target)
1683
+ return [];
1684
+ const server = homeserverName(target.getUserId());
1685
+ const found = new Map();
1686
+ for (const space of companySpaces(target)) {
1687
+ let from;
1688
+ for (let page = 0; page < BROWSE_MAX_PAGES; page += 1) {
1689
+ const result = await withTimeout(target.getRoomHierarchy(space.roomId, BROWSE_PAGE_SIZE, 1, false, from), BROWSE_TIMEOUT_MS, 'browseRooms');
1690
+ for (const child of result.rooms ?? []) {
1691
+ if (child.room_id === space.roomId || child.room_type !== undefined)
1692
+ continue;
1693
+ if (homeserverName(child.room_id) !== server)
1694
+ continue;
1695
+ // matrix-js-sdk types `join_rule` as `Knock` only; the wire carries any rule.
1696
+ const joinRule = child.join_rule;
1697
+ if (joinRule !== 'public' && joinRule !== 'restricted')
1698
+ continue;
1699
+ const membership = target.getRoom(child.room_id)?.getMyMembership();
1700
+ if (membership === KnownMembership.Join || membership === KnownMembership.Invite) {
1701
+ continue;
1702
+ }
1703
+ const name = normaliseText(child.name ?? '', MAX_ROOM_NAME_LENGTH);
1704
+ const topic = normaliseTopic(child.topic ?? '');
1705
+ found.set(child.room_id, {
1706
+ id: child.room_id,
1707
+ name: name === '' ? child.room_id : name,
1708
+ ...(topic === '' ? {} : { topic }),
1709
+ memberCount: Number.isFinite(child.num_joined_members)
1710
+ ? Math.max(0, child.num_joined_members)
1711
+ : 0,
1712
+ });
1713
+ }
1714
+ from = result.next_batch;
1715
+ if (!from)
1716
+ break;
1717
+ }
1718
+ }
1719
+ return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1720
+ }
1721
+ /** See `ChatClient.joinBrowsableRoom`. */
1722
+ async function joinBrowsableRoom(roomId) {
1723
+ const target = client;
1724
+ if (!target)
1725
+ throw new Error('chat: joinBrowsableRoom called before start()');
1726
+ const listed = await browseRooms();
1727
+ if (!listed.some((room) => room.id === roomId)) {
1728
+ throw new Error(`chat: ${roomId} is not a room of this company that can be joined`);
1729
+ }
1730
+ await target.joinRoom(roomId);
1731
+ if (client === target)
1732
+ notify();
1733
+ }
1734
+ /** See `ChatClient.createRoom`. The service is the only way: the
1735
+ * homeserver refuses a named room from a member. The rules a channel is
1736
+ * made under (naming, join rule, encryption, power levels) are the
1737
+ * service's, shared with the admin API. */
1738
+ async function createRoom(input) {
1739
+ if (!client)
1740
+ throw new Error('chat: createRoom called before start()');
1741
+ const target = client;
1742
+ const name = normaliseText(String(input.name ?? ''), Number.POSITIVE_INFINITY);
1743
+ if (name === '')
1744
+ throw new Error('chat: a room needs a name');
1745
+ if ([...name].length > MAX_ROOM_NAME_LENGTH) {
1746
+ throw new Error(`chat: a room name is at most ${MAX_ROOM_NAME_LENGTH} characters`);
1747
+ }
1748
+ if (input.visibility !== 'public' && input.visibility !== 'private') {
1749
+ throw new Error('chat: a room is either public or private');
1750
+ }
1751
+ const topic = normaliseTopic(String(input.topic ?? ''));
1752
+ const body = JSON.stringify({
1753
+ name,
1754
+ ...(topic === '' ? {} : { topic }),
1755
+ visibility: input.visibility,
1756
+ });
1757
+ const request = () => fetch(createRoomUrl(exchangeUrl), {
1758
+ method: 'POST',
1759
+ headers: {
1760
+ Authorization: `Bearer ${target.getAccessToken() ?? ''}`,
1761
+ 'Content-Type': 'application/json',
1762
+ },
1763
+ body,
1764
+ redirect: 'error',
1765
+ credentials: 'omit',
1766
+ signal: AbortSignal.timeout(CREATE_ROOM_TIMEOUT_MS),
1767
+ });
1768
+ let response = await request();
1769
+ if (response.status === 401 && client === target) {
1770
+ await refreshToken();
1771
+ response = await request();
1772
+ }
1773
+ if (!response.ok)
1774
+ throw new Error(`chat: room creation refused: ${response.status}`);
1775
+ const roomId = (await response.json()).room_id;
1776
+ if (typeof roomId !== 'string' || roomId === '') {
1777
+ throw new Error('chat: room creation answered without a room id');
1778
+ }
1779
+ await awaitJoinedRoom(target, roomId);
1780
+ return roomId;
1781
+ }
1782
+ /** Resolves once `target` has the room as joined. Bounded by
1783
+ * `CREATE_ROOM_TIMEOUT_MS`, rejects when `target` is no longer the live
1784
+ * client (`stop()` or a swap disposed it), and leaves no listener behind
1785
+ * on any path. */
1786
+ async function awaitJoinedRoom(target, roomId) {
1787
+ const ready = () => target.getRoom(roomId)?.getMyMembership() === KnownMembership.Join;
1788
+ if (ready())
1789
+ return;
1790
+ let check;
1791
+ try {
1792
+ await withTimeout(new Promise((resolve, reject) => {
1793
+ check = () => {
1794
+ if (client !== target) {
1795
+ reject(new Error('chat: the client was replaced while the room was being created'));
1796
+ }
1797
+ else if (ready())
1798
+ resolve();
1799
+ };
1800
+ target.on(ClientEvent.Room, check);
1801
+ target.on(RoomEvent.MyMembership, check);
1802
+ target.on(ClientEvent.Sync, check);
1803
+ }), CREATE_ROOM_TIMEOUT_MS, 'waiting for the new room');
1804
+ }
1805
+ catch (error) {
1806
+ // `stop()` / a swap removes every listener, so the wait can only end
1807
+ // by timing out: say why.
1808
+ if (client !== target) {
1809
+ throw new Error('chat: the client was replaced while the room was being created');
1810
+ }
1811
+ throw error;
1812
+ }
1813
+ finally {
1814
+ if (check) {
1815
+ target.off(ClientEvent.Room, check);
1816
+ target.off(RoomEvent.MyMembership, check);
1817
+ target.off(ClientEvent.Sync, check);
1818
+ }
1819
+ }
1820
+ }
1821
+ /** See `ChatClient.setRoomTopic`. */
1822
+ async function setRoomTopic(roomId, topic) {
1823
+ if (!client)
1824
+ throw new Error('chat: setRoomTopic called before start()');
1825
+ const room = client.getRoom(roomId);
1826
+ if (!room)
1827
+ throw new Error(`chat: not in room ${roomId}`);
1828
+ if (!canSetTopic(client, room)) {
1829
+ throw new Error(`chat: not allowed to set the topic of ${roomId}`);
1830
+ }
1831
+ await client.sendStateEvent(roomId, EventType.RoomTopic, { topic: normaliseTopic(topic) }, '');
1832
+ }
1582
1833
  function pinnedEventIds(room) {
1583
1834
  const content = room.currentState
1584
1835
  .getStateEvents(EventType.RoomPinnedEvents, '')
@@ -2089,6 +2340,8 @@ export function createChatClient(options) {
2089
2340
  // and the cache is cheap to rebuild: `personStatus` refetches on the
2090
2341
  // next read for anyone still of interest.
2091
2342
  chatStatusCache.clear();
2343
+ automaticStatusCache.clear();
2344
+ automaticStatusAskedAt.clear();
2092
2345
  starting = undefined;
2093
2346
  clearTimeout(refreshTimer);
2094
2347
  refreshTimer = undefined;
@@ -2224,12 +2477,66 @@ export function createChatClient(options) {
2224
2477
  kind === 'vacation' ||
2225
2478
  kind === 'sick');
2226
2479
  }
2227
- function notifyStatusChanged(userId, next) {
2228
- chatStatusCache.set(userId, next);
2229
- const changed = new Map([[userId, next]]);
2480
+ /** `automatic ?? explicit` -- the one place the ephemeral overlay
2481
+ * (`automaticStatusCache`) and the person's own durable choice
2482
+ * (`chatStatusCache`) are composed. The overlay never touches the
2483
+ * explicit cache, so clearing it (`kind: null`) only ever reveals
2484
+ * whatever the person had already set. See `ChatClient.status`. */
2485
+ function effectiveStatus(userId) {
2486
+ const automatic = automaticStatusCache.get(userId)?.kind;
2487
+ return automatic ? { kind: automatic } : (chatStatusCache.get(userId) ?? null);
2488
+ }
2489
+ function notifyEffectiveStatusChanged(userId) {
2490
+ const changed = new Map([[userId, effectiveStatus(userId)]]);
2230
2491
  for (const listener of chatStatusListeners)
2231
2492
  listener(changed);
2232
2493
  }
2494
+ function notifyStatusChanged(userId, next) {
2495
+ chatStatusCache.set(userId, next);
2496
+ notifyEffectiveStatusChanged(userId);
2497
+ }
2498
+ /** See `ChatClient.applyAutomaticStatus`. */
2499
+ function applyAutomaticStatus(userId, automatic) {
2500
+ const existing = automaticStatusCache.get(userId);
2501
+ if (existing && automatic.sequence <= existing.sequence)
2502
+ return;
2503
+ automaticStatusCache.set(userId, automatic);
2504
+ notifyEffectiveStatusChanged(userId);
2505
+ }
2506
+ /** Reads the automatic overlay `apps/chat-service` holds for `userId` and
2507
+ * composes it in. Best effort: a service without the route mounted, or
2508
+ * any failure, leaves the person's explicit status showing. */
2509
+ async function fetchAutomaticStatus(userId) {
2510
+ const target = client;
2511
+ if (!target)
2512
+ return;
2513
+ automaticStatusAskedAt.set(userId, Date.now());
2514
+ try {
2515
+ const response = await fetch(automaticStatusUrl(exchangeUrl, userId), {
2516
+ headers: { Authorization: `Bearer ${target.getAccessToken() ?? ''}` },
2517
+ redirect: 'error',
2518
+ credentials: 'omit',
2519
+ });
2520
+ if (!response.ok || client !== target)
2521
+ return;
2522
+ const body = (await response.json());
2523
+ if ((body.kind !== 'meeting' && body.kind !== null) || typeof body.sequence !== 'number') {
2524
+ return;
2525
+ }
2526
+ // The service is the source of truth, so its answer replaces the
2527
+ // cache even at a lower sequence: after a service restart its
2528
+ // sequences start over, and keeping the old higher one would leave a
2529
+ // stale overlay up forever.
2530
+ const before = effectiveStatus(userId);
2531
+ automaticStatusCache.set(userId, { kind: body.kind, sequence: body.sequence });
2532
+ const after = effectiveStatus(userId);
2533
+ if (JSON.stringify(before) !== JSON.stringify(after))
2534
+ notifyEffectiveStatusChanged(userId);
2535
+ }
2536
+ catch {
2537
+ // Nothing to show beyond the explicit status.
2538
+ }
2539
+ }
2233
2540
  /** See `ChatClient.status`. `getExtendedProfileProperty` already checks
2234
2541
  * matrix-js-sdk's own store before reaching the network (populated only
2235
2542
  * by a sync filter this package does not set up, so in practice this
@@ -2240,6 +2547,7 @@ export function createChatClient(options) {
2240
2547
  const target = client;
2241
2548
  if (!target)
2242
2549
  return;
2550
+ void fetchAutomaticStatus(userId);
2243
2551
  try {
2244
2552
  const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2245
2553
  notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
@@ -2256,7 +2564,10 @@ export function createChatClient(options) {
2256
2564
  chatStatusCache.set(userId, null);
2257
2565
  void fetchPersonStatus(userId);
2258
2566
  }
2259
- return chatStatusCache.get(userId) ?? null;
2567
+ else if (Date.now() - (automaticStatusAskedAt.get(userId) ?? 0) > AUTOMATIC_STATUS_TTL_MS) {
2568
+ void fetchAutomaticStatus(userId);
2569
+ }
2570
+ return effectiveStatus(userId);
2260
2571
  }
2261
2572
  /** See `ChatClient.setOwnStatus`. The optimistic write is rolled back on
2262
2573
  * a rejection -- unlike `starRoom`/`muteRoom`, a write here fails for an
@@ -2573,6 +2884,10 @@ export function createChatClient(options) {
2573
2884
  toggleReaction,
2574
2885
  pinMessage,
2575
2886
  unpinMessage,
2887
+ setRoomTopic,
2888
+ createRoom,
2889
+ browseRooms,
2890
+ joinBrowsableRoom,
2576
2891
  pinnedMessages,
2577
2892
  startDirectMessage,
2578
2893
  hideDirectMessage,
@@ -2605,6 +2920,7 @@ export function createChatClient(options) {
2605
2920
  status: personStatus,
2606
2921
  setOwnStatus,
2607
2922
  onStatusChanged,
2923
+ applyAutomaticStatus,
2608
2924
  sendTyping,
2609
2925
  onTypingChanged,
2610
2926
  };
@@ -1,7 +1,7 @@
1
1
  import type { ChatClient } from '../types.ts';
2
2
  import { FakeChatServer, type FakeChatServerOptions } from './server.ts';
3
3
  export { FakeChatServer } from './server.ts';
4
- export type { FakeChatServerOptions, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
4
+ export type { FakeChatServerOptions, FakeHierarchyChild, FakeMember, FakeMessageSeed, FakeRoomSeed, } from './server.ts';
5
5
  export { SAMPLE_ROOMS } from './sample.ts';
6
6
  export type FakeChatOptions = FakeChatServerOptions & {
7
7
  storeName?: string;
@@ -33,6 +33,15 @@ export type FakeRoomSeed = {
33
33
  * defaults to `0` in real Matrix, same as the client and admin reads
34
34
  * treat it). */
35
35
  archived?: boolean;
36
+ /** For a space: the children its `GET .../hierarchy` lists. Joining one
37
+ * through `POST /join` makes it a joined room. */
38
+ children?: FakeHierarchyChild[];
39
+ /** Seeds an `m.room.topic` state event. Defaults to none. */
40
+ topic?: string;
41
+ /** Seeds the content of `m.room.power_levels` (`users`, `state_default`,
42
+ * ...), merged over `archived`'s `events_default`. Defaults to none,
43
+ * which seeds no such event. */
44
+ powerLevels?: Record<string, unknown>;
36
45
  /** Seeds this room as an unanswered invitation to the fake account
37
46
  * itself, rather than a room it has joined -- a `rooms.invite` entry
38
47
  * with the stripped state real Matrix delivers one in, the one shape
@@ -43,6 +52,20 @@ export type FakeRoomSeed = {
43
52
  inviter?: string;
44
53
  };
45
54
  };
55
+ /** One child the fake company space lists in `GET .../hierarchy`. Fields
56
+ * the homeserver would send are passed through as given, so a test can
57
+ * seed a federated room, a sub-space or an invite-only room. */
58
+ export type FakeHierarchyChild = {
59
+ id: string;
60
+ name?: string;
61
+ topic?: string;
62
+ /** Defaults to `restricted`, how the company's channels are created. */
63
+ joinRule?: string;
64
+ /** `m.space` for a sub-space. Omitted for a room. */
65
+ roomType?: string;
66
+ /** Defaults to `0`. */
67
+ memberCount?: number;
68
+ };
46
69
  export type FakeMessageSeed = {
47
70
  /** Defaults to a minted `$seeded-<n>`. Give one to reply to it. */
48
71
  id?: string;
@@ -118,6 +141,28 @@ export declare class FakeChatServer {
118
141
  * gives a member, which `pinMessage`/`unpinMessage` must reject on
119
142
  * rather than resolve quietly. */
120
143
  pinStatus: number;
144
+ /** Every `m.room.topic` the client has written, in order -- for a test
145
+ * that asserts what went on the wire, or that nothing did. */
146
+ readonly topicWrites: Array<{
147
+ roomId: string;
148
+ content: Record<string, unknown>;
149
+ }>;
150
+ /** What `POST /_chat/rooms` answers with -- anything but 201 fails the
151
+ * creation, with nothing made. */
152
+ createRoomStatus: number;
153
+ /** Every `POST /_chat/rooms` the client made, with the bearer token and
154
+ * the exact body it sent. */
155
+ readonly createRoomRequests: Array<{
156
+ authorised: boolean;
157
+ body: unknown;
158
+ }>;
159
+ /** Every room the client joined through `POST /join`, in order. */
160
+ readonly joinedThroughApi: string[];
161
+ /** Every `GET .../hierarchy` the client made, with its `from` token. */
162
+ readonly hierarchyRequests: Array<{
163
+ roomId: string;
164
+ from: string | null;
165
+ }>;
121
166
  /** What `PUT .../send/...` answers with -- anything but 200 fails the
122
167
  * send, with nothing stored. */
123
168
  sendStatus: number;
@@ -126,6 +171,9 @@ export declare class FakeChatServer {
126
171
  threadFollowReadBarrier: Promise<void> | null;
127
172
  /** What a thread follow `GET` answers with. */
128
173
  threadFollowReadStatus: number;
174
+ /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
175
+ * fails the follow or unfollow, with nothing stored. */
176
+ threadFollowWriteStatus: number;
129
177
  /** Every call to the thread follow route, in arrival order. */
130
178
  readonly threadFollowRequests: Array<{
131
179
  method: string;
@@ -189,6 +237,13 @@ export declare class FakeChatServer {
189
237
  readonly threadFollows: Map<string, {
190
238
  muted: boolean;
191
239
  }>;
240
+ /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
241
+ * person: the automatic `meeting` overlay a call pushed. No entry reads
242
+ * as `{ kind: null, sequence: 0 }`, as the real route does. */
243
+ readonly automaticStatuses: Map<string, {
244
+ kind: "meeting" | null;
245
+ sequence: number;
246
+ }>;
192
247
  /** Every `PUT .../typing/...` this server has answered, in order -- for a
193
248
  * test that asserts `sendTyping` actually reached the wire, with what
194
249
  * it sent. */
@@ -36,6 +36,19 @@ export class FakeChatServer {
36
36
  * gives a member, which `pinMessage`/`unpinMessage` must reject on
37
37
  * rather than resolve quietly. */
38
38
  pinStatus = 200;
39
+ /** Every `m.room.topic` the client has written, in order -- for a test
40
+ * that asserts what went on the wire, or that nothing did. */
41
+ topicWrites = [];
42
+ /** What `POST /_chat/rooms` answers with -- anything but 201 fails the
43
+ * creation, with nothing made. */
44
+ createRoomStatus = 201;
45
+ /** Every `POST /_chat/rooms` the client made, with the bearer token and
46
+ * the exact body it sent. */
47
+ createRoomRequests = [];
48
+ /** Every room the client joined through `POST /join`, in order. */
49
+ joinedThroughApi = [];
50
+ /** Every `GET .../hierarchy` the client made, with its `from` token. */
51
+ hierarchyRequests = [];
39
52
  /** What `PUT .../send/...` answers with -- anything but 200 fails the
40
53
  * send, with nothing stored. */
41
54
  sendStatus = 200;
@@ -44,6 +57,9 @@ export class FakeChatServer {
44
57
  threadFollowReadBarrier = null;
45
58
  /** What a thread follow `GET` answers with. */
46
59
  threadFollowReadStatus = 200;
60
+ /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
61
+ * fails the follow or unfollow, with nothing stored. */
62
+ threadFollowWriteStatus = 200;
47
63
  /** Every call to the thread follow route, in arrival order. */
48
64
  threadFollowRequests = [];
49
65
  userId;
@@ -79,6 +95,10 @@ export class FakeChatServer {
79
95
  * route keeps it: `roomId rootId` -> whether the person unfollowed. A
80
96
  * thread with no entry is not followed. */
81
97
  threadFollows = new Map();
98
+ /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
99
+ * person: the automatic `meeting` overlay a call pushed. No entry reads
100
+ * as `{ kind: null, sequence: 0 }`, as the real route does. */
101
+ automaticStatuses = new Map();
82
102
  /** Every `PUT .../typing/...` this server has answered, in order -- for a
83
103
  * test that asserts `sendTyping` actually reached the wire, with what
84
104
  * it sent. */
@@ -509,14 +529,24 @@ export class FakeChatServer {
509
529
  content: { algorithm: 'm.megolm.v1.aes-sha2' },
510
530
  });
511
531
  }
512
- if (seed.archived) {
532
+ if (seed.topic !== undefined) {
533
+ events.push({
534
+ type: 'm.room.topic',
535
+ state_key: '',
536
+ event_id: `$topic-${seed.id}`,
537
+ sender: this.userId,
538
+ origin_server_ts: now,
539
+ content: { topic: seed.topic },
540
+ });
541
+ }
542
+ if (seed.archived || seed.powerLevels) {
513
543
  events.push({
514
544
  type: 'm.room.power_levels',
515
545
  state_key: '',
516
546
  event_id: `$power-levels-${seed.id}`,
517
547
  sender: this.userId,
518
548
  origin_server_ts: now,
519
- content: { events_default: 100 },
549
+ content: { ...(seed.archived ? { events_default: 100 } : {}), ...seed.powerLevels },
520
550
  });
521
551
  }
522
552
  return {
@@ -1263,6 +1293,81 @@ export class FakeChatServer {
1263
1293
  this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1264
1294
  return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1265
1295
  }
1296
+ const hierarchy = url.pathname.match(/^\/_matrix\/client\/v1\/rooms\/([^/]+)\/hierarchy$/);
1297
+ if (hierarchy && this.#authorised(init)) {
1298
+ const roomId = decodeURIComponent(hierarchy[1]);
1299
+ const from = url.searchParams.get('from');
1300
+ this.hierarchyRequests.push({ roomId, from });
1301
+ const space = this.#rooms.find((room) => room.id === roomId && room.isSpace);
1302
+ if (!space) {
1303
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'unknown' }));
1304
+ }
1305
+ const children = space.children ?? [];
1306
+ const limit = Number(url.searchParams.get('limit') ?? children.length + 1) || 1;
1307
+ const start = from ? Number(from) : 0;
1308
+ const page = children.slice(start, start + limit);
1309
+ const next = start + limit < children.length ? String(start + limit) : undefined;
1310
+ const toRoom = (child) => ({
1311
+ room_id: child.id,
1312
+ name: child.name,
1313
+ topic: child.topic,
1314
+ join_rule: child.joinRule ?? 'restricted',
1315
+ num_joined_members: child.memberCount ?? 0,
1316
+ world_readable: false,
1317
+ guest_can_join: false,
1318
+ ...(child.roomType ? { room_type: child.roomType } : {}),
1319
+ children_state: [],
1320
+ });
1321
+ return Promise.resolve(jsonResponse(200, {
1322
+ rooms: [
1323
+ ...(start === 0
1324
+ ? [{ ...toRoom({ id: space.id, name: space.name, roomType: 'm.space' }) }]
1325
+ : []),
1326
+ ...page.map(toRoom),
1327
+ ],
1328
+ ...(next ? { next_batch: next } : {}),
1329
+ }));
1330
+ }
1331
+ const join = url.pathname.match(/^\/_matrix\/client\/v3\/join\/([^/]+)$/);
1332
+ if (join && init?.method === 'POST' && this.#authorised(init)) {
1333
+ const roomId = decodeURIComponent(join[1]);
1334
+ const child = this.#rooms
1335
+ .flatMap((room) => room.children ?? [])
1336
+ .find((candidate) => candidate.id === roomId);
1337
+ if (!child) {
1338
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'unknown' }));
1339
+ }
1340
+ this.joinedThroughApi.push(roomId);
1341
+ const seed = { id: roomId, name: child.name ?? roomId, topic: child.topic };
1342
+ this.#rooms.push(seed);
1343
+ this.#materialise(seed);
1344
+ this.#deliverOrQueue({ [roomId]: this.#joinEntry(seed) });
1345
+ return Promise.resolve(jsonResponse(200, { room_id: roomId }));
1346
+ }
1347
+ const topicState = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/state\/m\.room\.topic\/?$/);
1348
+ if (topicState && this.#authorised(init)) {
1349
+ let content = {};
1350
+ try {
1351
+ content = JSON.parse(String(init?.body ?? '{}'));
1352
+ }
1353
+ catch {
1354
+ // Same tolerance as every other route here.
1355
+ }
1356
+ const roomId = decodeURIComponent(topicState[1]);
1357
+ this.topicWrites.push({ roomId, content });
1358
+ this.#eventSeq += 1;
1359
+ const event = {
1360
+ type: 'm.room.topic',
1361
+ state_key: '',
1362
+ event_id: `$topic-${this.#eventSeq}`,
1363
+ sender: this.userId,
1364
+ origin_server_ts: this.#now(),
1365
+ content,
1366
+ };
1367
+ this.#record(roomId, event);
1368
+ this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
1369
+ return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
1370
+ }
1266
1371
  // Uploads go to `/_matrix/media/v3/upload`, which is still the
1267
1372
  // upload endpoint under authenticated media -- only *downloads* moved
1268
1373
  // to `/_matrix/client/v1/media`.
@@ -1291,8 +1396,42 @@ export class FakeChatServer {
1291
1396
  return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
1292
1397
  })();
1293
1398
  }
1399
+ const chatStatus = url.pathname.match(/^\/_chat\/status\/([^/]+)$/);
1400
+ if (chatStatus) {
1401
+ if (!this.#authorised(init)) {
1402
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1403
+ }
1404
+ const found = this.automaticStatuses.get(decodeURIComponent(chatStatus[1]));
1405
+ return Promise.resolve(jsonResponse(200, found ?? { kind: null, sequence: 0 }));
1406
+ }
1294
1407
  // `apps/chat-service`'s thread follow route: the same rule the real one
1295
1408
  // has -- an automatic follow never undoes an unfollow.
1409
+ if (url.pathname === '/_chat/rooms' && init?.method === 'POST') {
1410
+ const authorised = this.#authorised(init);
1411
+ let body = {};
1412
+ try {
1413
+ body = JSON.parse(String(init?.body ?? '{}'));
1414
+ }
1415
+ catch {
1416
+ // Recorded as an empty body below.
1417
+ }
1418
+ this.createRoomRequests.push({ authorised, body });
1419
+ if (!authorised)
1420
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1421
+ if (this.createRoomStatus !== 201) {
1422
+ return Promise.resolve(jsonResponse(this.createRoomStatus, { error: 'refused' }));
1423
+ }
1424
+ this.#roomSeq += 1;
1425
+ const seed = {
1426
+ id: `!channel-${this.#roomSeq}:${this.serverName}`,
1427
+ name: String(body.name),
1428
+ topic: body.topic,
1429
+ };
1430
+ this.#rooms.push(seed);
1431
+ this.#materialise(seed);
1432
+ this.#deliverOrQueue({ [seed.id]: this.#joinEntry(seed) });
1433
+ return Promise.resolve(jsonResponse(201, { room_id: seed.id }));
1434
+ }
1296
1435
  const chatThread = url.pathname.match(/^\/_chat\/threads\/([^/]+)\/([^/]+)\/follow$/);
1297
1436
  if (chatThread) {
1298
1437
  if (!this.#authorised(init)) {
@@ -1319,6 +1458,9 @@ export class FakeChatServer {
1319
1458
  return jsonResponse(200, { following: found !== undefined && !found.muted });
1320
1459
  })();
1321
1460
  }
1461
+ if (this.threadFollowWriteStatus !== 200) {
1462
+ return Promise.resolve(jsonResponse(this.threadFollowWriteStatus, { error: 'internal_error' }));
1463
+ }
1322
1464
  if (method === 'DELETE')
1323
1465
  this.threadFollows.set(key, { muted: true });
1324
1466
  if (method === 'PUT') {
@@ -6,5 +6,5 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_UPLOAD_BYTES } from './client.ts';
10
- export type { ChatAttachment, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
9
+ export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from './client.ts';
10
+ export type { ChatAttachment, ChatBrowsableRoom, ChatNewRoom, ChatRoomFilesPage, ChatClient, ChatConnectionStatus, ChatPerson, ChatRoomLastMessage, ChatRoomSummary, ChatSearchResults, ChatTimelineEvent, ChatUploadProgress, CreateChatClientOptions, ExchangeBody, } from './types.ts';
@@ -6,4 +6,4 @@
6
6
  * everything it returns is this package's own small, typed surface. See
7
7
  * `README.md` and the chat plan, section 9.
8
8
  */
9
- export { createChatClient, MAX_UPLOAD_BYTES } from "./client.js";
9
+ export { createChatClient, MAX_ROOM_NAME_LENGTH, MAX_TOPIC_LENGTH, MAX_UPLOAD_BYTES, normaliseTopic, } from "./client.js";
@@ -1,26 +1,3 @@
1
- /**
2
- * The composer's Markdown shortcuts, turned into HTML for `formatted_body`
3
- * (chat plan section 9, ticket #15). Bold, italic, inline code, inline
4
- * links, lists, block quotes and fenced code blocks -- the set the ticket
5
- * asks for, nothing wider.
6
- *
7
- * **Matrix-agnostic on purpose.** `msgtype`, `format` and `body` are a
8
- * Matrix event's concern, not this module's -- `client.ts` is the only file
9
- * in this package that touches matrix-js-sdk (see `index.ts`'s module
10
- * comment), and it shapes this output into a `RoomMessageEventContent` with
11
- * `ContentHelpers.makeHtmlMessage`/`makeTextMessage`.
12
- *
13
- * **Safe by construction, not by a second pass.** Every character of the
14
- * typed text is HTML-escaped before any shortcut is applied, so a message
15
- * that reads `<script>` or `onerror=` as plain text can never become a tag
16
- * or an attribute here -- there is no HTML in the input for a shortcut to
17
- * misread. A link's `href` is parsed and scheme-checked (`http:`, `https:`,
18
- * `mailto:` only) before it is ever written into an attribute; anything
19
- * else -- `javascript:`, `data:`, a bare word -- leaves the `[text](url)`
20
- * as escaped literal text instead. Nothing here reaches `sanitize.ts`,
21
- * which cleans a *stranger's* `formatted_body`; this one has no stranger in
22
- * it to clean up after.
23
- */
24
1
  /** `text`, as a plain body and -- only when a shortcut was actually used --
25
2
  * the HTML `formatted_body` to send alongside it. */
26
3
  export declare function toFormattedBody(text: string): {
@@ -21,16 +21,7 @@
21
21
  * which cleans a *stranger's* `formatted_body`; this one has no stranger in
22
22
  * it to clean up after.
23
23
  */
24
- /** Characters that must never reach the DOM unescaped. Order matters: `&`
25
- * first, or every entity this inserts would itself be re-escaped. */
26
- function escapeHtml(text) {
27
- return text
28
- .replace(/&/g, '&amp;')
29
- .replace(/</g, '&lt;')
30
- .replace(/>/g, '&gt;')
31
- .replace(/"/g, '&quot;')
32
- .replace(/'/g, '&#39;');
33
- }
24
+ import { escapeHtml } from '@wtfalch/utils/html';
34
25
  /** `http:`/`https:`/`mailto:` only -- never `javascript:`, never `data:`,
35
26
  * never a scheme this has not heard of. `URL` is the parser, not a
36
27
  * pattern: it is what decides a scheme, not a regular expression a typo
@@ -46,15 +46,28 @@ export function ThreadPanel({ client, roomId, threadId, onClose, onGoToRoot, now
46
46
  };
47
47
  }, [roomId, threadId]);
48
48
  const toggleFollow = () => {
49
- // The state is not known yet, or the read failed: read it again.
49
+ version.current += 1;
50
+ const started = version.current;
51
+ // The state is not known yet, or the read failed: the button reads
52
+ // "Follow" either way, so a click follows rather than reading again --
53
+ // following twice is a no-op on the service, so this is safe even when
54
+ // the real state turns out to already be followed. Failing back to
55
+ // `null` (not `false`) keeps the next click taking the same path,
56
+ // rather than quietly turning into an unfollow.
50
57
  if (following === null) {
51
- read();
58
+ setFollowing(true);
59
+ client.followThread(roomId, threadId).catch(() => {
60
+ if (version.current === started)
61
+ setFollowing(null);
62
+ });
52
63
  return;
53
64
  }
54
- version.current += 1;
55
65
  const next = !following;
56
66
  setFollowing(next);
57
- (next ? client.followThread(roomId, threadId) : client.unfollowThread(roomId, threadId)).catch(() => setFollowing(!next));
67
+ (next ? client.followThread(roomId, threadId) : client.unfollowThread(roomId, threadId)).catch(() => {
68
+ if (version.current === started)
69
+ setFollowing(!next);
70
+ });
58
71
  };
59
72
  return (_jsxs("aside", { className: "chat-thread", "aria-label": "Thread", children: [_jsxs("header", { className: "chat-thread-bar", children: [_jsxs(Button, { kind: "ghost", size: "sm", onPress: onClose, children: [_jsx(Icon, { name: "back", size: 16 }), "Back"] }), _jsx("span", { className: "chat-thread-heading", children: "Thread" }), _jsx(Button, { kind: "ghost", size: "sm", onPress: toggleFollow, children: following ? 'Unfollow' : 'Follow' }), _jsx(Button, { kind: "ghost", size: "sm", onPress: onGoToRoot, children: "Go to message" })] }), _jsx(Timeline, { client: client, roomId: roomId, threadId: threadId, now: now }, threadId), _jsx(Composer, { client: client, roomId: roomId, threadId: threadId, sendOnEnter: sendOnEnter }, `composer-${threadId}`)] }));
60
73
  }
@@ -109,6 +109,33 @@ export type ChatRoomSummary = {
109
109
  * `m.favourite` room tag, synced across every device on the account
110
110
  * the same way `hideDirectMessage`'s tag is (agora#27). */
111
111
  readonly starred: boolean;
112
+ /** The room's `m.room.topic`, as plain text: trimmed and capped (see
113
+ * `normaliseTopic`), because a topic is whatever its setter wrote.
114
+ * Absent when the room has none. */
115
+ readonly topic?: string;
116
+ /** Whether the signed-in person's power level lets them change this
117
+ * room's topic with `setRoomTopic`. A list or room header shows its
118
+ * edit control off this instead of letting the write fail. */
119
+ readonly canSetTopic: boolean;
120
+ };
121
+ /** A room of this company the person is not in yet and may join: a child
122
+ * of the company space with a `public` or `restricted` join rule. Name and
123
+ * topic are plain text, normalised like `ChatRoomSummary.topic`. */
124
+ export type ChatBrowsableRoom = {
125
+ readonly id: string;
126
+ readonly name: string;
127
+ readonly topic?: string;
128
+ /** Joined members, as the homeserver counts them. */
129
+ readonly memberCount: number;
130
+ };
131
+ /** What `createRoom` takes. */
132
+ export type ChatNewRoom = {
133
+ /** Trimmed; must not be empty. */
134
+ name: string;
135
+ topic?: string;
136
+ /** `public`: any member of the company may find and join it (the admin
137
+ * API's own word for it). `private`: invite only. */
138
+ visibility: 'public' | 'private';
112
139
  };
113
140
  /** Someone this person can start a direct message with: a member of the
114
141
  * company space, or a guest sharing a room with them (docs/guests.md,
@@ -804,6 +831,35 @@ export type ChatClient = {
804
831
  * safe against another client writing to the same room's pinned list
805
832
  * at once. */
806
833
  unpinMessage: (roomId: string, eventId: string) => Promise<void>;
834
+ /** Sets `roomId`'s topic. `topic` is trimmed and capped to
835
+ * `MAX_TOPIC_LENGTH` characters, control characters removed; an empty
836
+ * result clears the topic. Rejects, with nothing sent, when the room is
837
+ * unknown or this person's power level cannot send `m.room.topic`
838
+ * (`ChatRoomSummary.canSetTopic` is false). The homeserver stays the
839
+ * authority: a refusal from it rejects too. */
840
+ setRoomTopic: (roomId: string, topic: string) => Promise<void>;
841
+ /** Creates a company channel and resolves with its room id once it is in
842
+ * `rooms()`. Goes through `apps/chat-service` (`POST /_chat/rooms`),
843
+ * because the homeserver refuses a named room from a member; the
844
+ * service applies the admin API's rules (join rule, power levels,
845
+ * encryption default, the link to the company space) and makes the
846
+ * creator an admin (power level 100) of the new room. `name` is trimmed
847
+ * and must be non-empty and at most `MAX_ROOM_NAME_LENGTH` characters;
848
+ * `topic` is normalised and capped like `setRoomTopic`'s. Rejects, with
849
+ * nothing made, on a bad name or visibility, or when the service
850
+ * refuses. */
851
+ createRoom: (input: ChatNewRoom) => Promise<string>;
852
+ /** The company's rooms this person is not in and may join, name order:
853
+ * the children of the company space (the joined `m.space` on this
854
+ * homeserver) whose join rule is `public` or `restricted`, minus rooms
855
+ * already joined or invited, minus rooms hosted on another server and
856
+ * minus sub-spaces. A room federated in from elsewhere never appears,
857
+ * whatever the space lists. Empty before `start()` resolves. */
858
+ browseRooms: () => Promise<ChatBrowsableRoom[]>;
859
+ /** Joins one room `browseRooms` lists. Rejects for any other room id,
860
+ * without calling the homeserver's join -- this is not a way to join
861
+ * an arbitrary room. */
862
+ joinBrowsableRoom: (roomId: string) => Promise<void>;
807
863
  /** `roomId`'s currently pinned messages, in the order `m.room.pinned_
808
864
  * events` lists them, each reduced the same way `timeline()` reduces a
809
865
  * message. A pinned id this client cannot find an event for -- paginated
@@ -909,6 +965,23 @@ export type ChatClient = {
909
965
  * `onPresenceChanged`: read `status(userId)` for anyone already of
910
966
  * interest before relying on this for what changes next. */
911
967
  onStatusChanged: (listener: (changed: ReadonlyMap<string, ChatStatus | null>) => void) => () => void;
968
+ /** `wtfalch/calls`' automatic "in a meeting" overlay for `userId`
969
+ * (chat#46, calls#39's own decision doc) -- ephemeral, unlike
970
+ * `setOwnStatus`'s durable write, and never written into the explicit
971
+ * status's own profile field. `status()`/`onStatusChanged()` compose it
972
+ * over the person's explicit status rather than replacing it:
973
+ * `automatic ?? explicit`, so clearing it (`kind: null`) only ever
974
+ * reveals whatever the person had already set, never `here`.
975
+ *
976
+ * `sequence` is the sender's own monotonic counter for `userId`; a call
977
+ * whose `sequence` is not strictly greater than the last one applied
978
+ * for that `userId` is dropped without effect, so a retried or
979
+ * out-of-order delivery can never erase a fresher value with a stale
980
+ * one. */
981
+ applyAutomaticStatus: (userId: string, automatic: {
982
+ kind: 'meeting' | null;
983
+ sequence: number;
984
+ }) => void;
912
985
  /** Tells `roomId` the signed-in person has started, or stopped, typing --
913
986
  * `m.typing`, which is not an event: nothing lands in `timeline()`, and
914
987
  * nothing is retried if this fails, the same as any other presence-like
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/chat",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "A Matrix chat client behind the agora's token exchange.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,7 +48,7 @@
48
48
  "test:acceptance": "vitest run --config vitest.acceptance.config.ts"
49
49
  },
50
50
  "peerDependencies": {
51
- "@wtfalch/design": ">=0.16.0",
51
+ "@wtfalch/design": ">=0.28.0 <0.31.0",
52
52
  "react": "^19.0.0",
53
53
  "react-dom": "^19.0.0"
54
54
  },
@@ -83,6 +83,7 @@
83
83
  "node": ">=22.0.0"
84
84
  },
85
85
  "dependencies": {
86
+ "@wtfalch/utils": "0.1.0",
86
87
  "matrix-js-sdk": "42.4.0"
87
88
  }
88
89
  }