@wtfalch/chat 0.7.0 → 0.8.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
@@ -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" }) })] })) }));
@@ -1,5 +1,5 @@
1
1
  import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEvent, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
2
- import { CryptoEvent, decodeRecoveryKey, } from 'matrix-js-sdk/lib/crypto-api';
2
+ import { CryptoEvent, decodeRecoveryKey, } from 'matrix-js-sdk/lib/crypto-api/index.js';
3
3
  import { exchange } from "./exchange.js";
4
4
  import { toFormattedBody } from "./markdown.js";
5
5
  import { createChatStore, cryptoStoreDbPrefix, purgeStaleChatStores } from "./store.js";
@@ -83,6 +83,12 @@ function threadFollowUrl(exchangeUrl, roomId, threadId) {
83
83
  const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
84
84
  return `${base}/_chat/threads/${encodeURIComponent(roomId)}/${encodeURIComponent(threadId)}/follow`;
85
85
  }
86
+ /** Where the automatic status overlay a person's call pushed is read back:
87
+ * `apps/chat-service`'s `GET /_chat/status/{userId}`, next to `exchangeUrl`. */
88
+ function automaticStatusUrl(exchangeUrl, userId) {
89
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
90
+ return `${base}/_chat/status/${encodeURIComponent(userId)}`;
91
+ }
86
92
  function setDraftAccountData(target, roomId, content) {
87
93
  return target.setRoomAccountData(roomId, DRAFT_EVENT_TYPE, content);
88
94
  }
@@ -93,6 +99,10 @@ function setDraftAccountData(target, roomId, content) {
93
99
  * wanting the far end to keep seeing "typing" through a long pause calls
94
100
  * this again itself; nothing here renews it on a timer. */
95
101
  const TYPING_TIMEOUT_MS = 20_000;
102
+ /** How long a fetched automatic-status overlay is trusted before `status()`
103
+ * reads it again. The overlay is ephemeral and nothing pushes it here, so
104
+ * without this a "meeting" would show until the session ended. */
105
+ const AUTOMATIC_STATUS_TTL_MS = 60_000;
96
106
  /** How many *matching* events `roomFiles` asks Synapse for per request.
97
107
  * Unlike `paginate`'s 30 (which bounds how much plain conversation a
98
108
  * person scrolls through at once), this only ever counts events that
@@ -191,6 +201,15 @@ export function createChatClient(options) {
191
201
  * the first is still in flight. */
192
202
  const chatStatusCache = new Map();
193
203
  const chatStatusListeners = new Set();
204
+ /** See `ChatClient.applyAutomaticStatus`. Kept apart from
205
+ * `chatStatusCache` -- the person's own durable, explicit choice --
206
+ * because this is the ephemeral overlay that composes over it rather
207
+ * than replacing it; `effectiveStatus` is the one place the two are
208
+ * read together. */
209
+ const automaticStatusCache = new Map();
210
+ /** When the service was last asked for each person's overlay (attempt,
211
+ * not success, so a failing service is not asked on every read). */
212
+ const automaticStatusAskedAt = new Map();
194
213
  /** Who is currently typing, per room -- built up from `RoomMemberEvent.
195
214
  * Typing` one member at a time, the signed-in person's own id never
196
215
  * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
@@ -1468,9 +1487,14 @@ export function createChatClient(options) {
1468
1487
  .filter((upload) => (upload.threadId ?? null) === threadId)
1469
1488
  .map((upload) => toUploadEvent(room, upload));
1470
1489
  }
1490
+ /** `room.findEventById` only walks threads matrix-js-sdk has already
1491
+ * built a `Thread` for -- the same gap `findEvent` above exists to
1492
+ * cover -- so a reply that failed before any reply of its thread ever
1493
+ * synced is invisible to it. Falling back to `findEvent`'s walk is what
1494
+ * lets a failed thread reply be found at all, for retry or cancel. */
1471
1495
  function findPendingEvent(roomId, localId) {
1472
1496
  const room = client?.getRoom(roomId);
1473
- const event = room?.findEventById(localId);
1497
+ const event = room ? findEvent(room, localId) : undefined;
1474
1498
  return room && event ? { room, event } : undefined;
1475
1499
  }
1476
1500
  function retryMessage(roomId, localId) {
@@ -1493,7 +1517,17 @@ export function createChatClient(options) {
1493
1517
  const found = findPendingEvent(roomId, localId);
1494
1518
  if (!found)
1495
1519
  return;
1496
- client.resendEvent(found.event, found.room).catch(() => { });
1520
+ // The event's own relation, not the options a caller no longer has:
1521
+ // `threadRootId` reads straight off its `m.relates_to`, so it is right
1522
+ // whether or not matrix-js-sdk has built a `Thread` around it yet.
1523
+ const threadId = found.event.threadRootId;
1524
+ client
1525
+ .resendEvent(found.event, found.room)
1526
+ .then(() => {
1527
+ if (threadId)
1528
+ autoFollowThread(roomId, threadId);
1529
+ })
1530
+ .catch(() => { });
1497
1531
  }
1498
1532
  function cancelMessage(roomId, localId) {
1499
1533
  if (!client)
@@ -2089,6 +2123,8 @@ export function createChatClient(options) {
2089
2123
  // and the cache is cheap to rebuild: `personStatus` refetches on the
2090
2124
  // next read for anyone still of interest.
2091
2125
  chatStatusCache.clear();
2126
+ automaticStatusCache.clear();
2127
+ automaticStatusAskedAt.clear();
2092
2128
  starting = undefined;
2093
2129
  clearTimeout(refreshTimer);
2094
2130
  refreshTimer = undefined;
@@ -2224,12 +2260,66 @@ export function createChatClient(options) {
2224
2260
  kind === 'vacation' ||
2225
2261
  kind === 'sick');
2226
2262
  }
2227
- function notifyStatusChanged(userId, next) {
2228
- chatStatusCache.set(userId, next);
2229
- const changed = new Map([[userId, next]]);
2263
+ /** `automatic ?? explicit` -- the one place the ephemeral overlay
2264
+ * (`automaticStatusCache`) and the person's own durable choice
2265
+ * (`chatStatusCache`) are composed. The overlay never touches the
2266
+ * explicit cache, so clearing it (`kind: null`) only ever reveals
2267
+ * whatever the person had already set. See `ChatClient.status`. */
2268
+ function effectiveStatus(userId) {
2269
+ const automatic = automaticStatusCache.get(userId)?.kind;
2270
+ return automatic ? { kind: automatic } : (chatStatusCache.get(userId) ?? null);
2271
+ }
2272
+ function notifyEffectiveStatusChanged(userId) {
2273
+ const changed = new Map([[userId, effectiveStatus(userId)]]);
2230
2274
  for (const listener of chatStatusListeners)
2231
2275
  listener(changed);
2232
2276
  }
2277
+ function notifyStatusChanged(userId, next) {
2278
+ chatStatusCache.set(userId, next);
2279
+ notifyEffectiveStatusChanged(userId);
2280
+ }
2281
+ /** See `ChatClient.applyAutomaticStatus`. */
2282
+ function applyAutomaticStatus(userId, automatic) {
2283
+ const existing = automaticStatusCache.get(userId);
2284
+ if (existing && automatic.sequence <= existing.sequence)
2285
+ return;
2286
+ automaticStatusCache.set(userId, automatic);
2287
+ notifyEffectiveStatusChanged(userId);
2288
+ }
2289
+ /** Reads the automatic overlay `apps/chat-service` holds for `userId` and
2290
+ * composes it in. Best effort: a service without the route mounted, or
2291
+ * any failure, leaves the person's explicit status showing. */
2292
+ async function fetchAutomaticStatus(userId) {
2293
+ const target = client;
2294
+ if (!target)
2295
+ return;
2296
+ automaticStatusAskedAt.set(userId, Date.now());
2297
+ try {
2298
+ const response = await fetch(automaticStatusUrl(exchangeUrl, userId), {
2299
+ headers: { Authorization: `Bearer ${target.getAccessToken() ?? ''}` },
2300
+ redirect: 'error',
2301
+ credentials: 'omit',
2302
+ });
2303
+ if (!response.ok || client !== target)
2304
+ return;
2305
+ const body = (await response.json());
2306
+ if ((body.kind !== 'meeting' && body.kind !== null) || typeof body.sequence !== 'number') {
2307
+ return;
2308
+ }
2309
+ // The service is the source of truth, so its answer replaces the
2310
+ // cache even at a lower sequence: after a service restart its
2311
+ // sequences start over, and keeping the old higher one would leave a
2312
+ // stale overlay up forever.
2313
+ const before = effectiveStatus(userId);
2314
+ automaticStatusCache.set(userId, { kind: body.kind, sequence: body.sequence });
2315
+ const after = effectiveStatus(userId);
2316
+ if (JSON.stringify(before) !== JSON.stringify(after))
2317
+ notifyEffectiveStatusChanged(userId);
2318
+ }
2319
+ catch {
2320
+ // Nothing to show beyond the explicit status.
2321
+ }
2322
+ }
2233
2323
  /** See `ChatClient.status`. `getExtendedProfileProperty` already checks
2234
2324
  * matrix-js-sdk's own store before reaching the network (populated only
2235
2325
  * by a sync filter this package does not set up, so in practice this
@@ -2240,6 +2330,7 @@ export function createChatClient(options) {
2240
2330
  const target = client;
2241
2331
  if (!target)
2242
2332
  return;
2333
+ void fetchAutomaticStatus(userId);
2243
2334
  try {
2244
2335
  const raw = await target.getExtendedProfileProperty(userId, STATUS_PROFILE_KEY);
2245
2336
  notifyStatusChanged(userId, isChatStatus(raw) ? raw : null);
@@ -2256,7 +2347,10 @@ export function createChatClient(options) {
2256
2347
  chatStatusCache.set(userId, null);
2257
2348
  void fetchPersonStatus(userId);
2258
2349
  }
2259
- return chatStatusCache.get(userId) ?? null;
2350
+ else if (Date.now() - (automaticStatusAskedAt.get(userId) ?? 0) > AUTOMATIC_STATUS_TTL_MS) {
2351
+ void fetchAutomaticStatus(userId);
2352
+ }
2353
+ return effectiveStatus(userId);
2260
2354
  }
2261
2355
  /** See `ChatClient.setOwnStatus`. The optimistic write is rolled back on
2262
2356
  * a rejection -- unlike `starRoom`/`muteRoom`, a write here fails for an
@@ -2605,6 +2699,7 @@ export function createChatClient(options) {
2605
2699
  status: personStatus,
2606
2700
  setOwnStatus,
2607
2701
  onStatusChanged,
2702
+ applyAutomaticStatus,
2608
2703
  sendTyping,
2609
2704
  onTypingChanged,
2610
2705
  };
@@ -126,6 +126,9 @@ export declare class FakeChatServer {
126
126
  threadFollowReadBarrier: Promise<void> | null;
127
127
  /** What a thread follow `GET` answers with. */
128
128
  threadFollowReadStatus: number;
129
+ /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
130
+ * fails the follow or unfollow, with nothing stored. */
131
+ threadFollowWriteStatus: number;
129
132
  /** Every call to the thread follow route, in arrival order. */
130
133
  readonly threadFollowRequests: Array<{
131
134
  method: string;
@@ -189,6 +192,13 @@ export declare class FakeChatServer {
189
192
  readonly threadFollows: Map<string, {
190
193
  muted: boolean;
191
194
  }>;
195
+ /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
196
+ * person: the automatic `meeting` overlay a call pushed. No entry reads
197
+ * as `{ kind: null, sequence: 0 }`, as the real route does. */
198
+ readonly automaticStatuses: Map<string, {
199
+ kind: "meeting" | null;
200
+ sequence: number;
201
+ }>;
192
202
  /** Every `PUT .../typing/...` this server has answered, in order -- for a
193
203
  * test that asserts `sendTyping` actually reached the wire, with what
194
204
  * it sent. */
@@ -44,6 +44,9 @@ export class FakeChatServer {
44
44
  threadFollowReadBarrier = null;
45
45
  /** What a thread follow `GET` answers with. */
46
46
  threadFollowReadStatus = 200;
47
+ /** What a thread follow `PUT`/`DELETE` answers with -- anything but 200
48
+ * fails the follow or unfollow, with nothing stored. */
49
+ threadFollowWriteStatus = 200;
47
50
  /** Every call to the thread follow route, in arrival order. */
48
51
  threadFollowRequests = [];
49
52
  userId;
@@ -79,6 +82,10 @@ export class FakeChatServer {
79
82
  * route keeps it: `roomId rootId` -> whether the person unfollowed. A
80
83
  * thread with no entry is not followed. */
81
84
  threadFollows = new Map();
85
+ /** What `apps/chat-service`'s `GET /_chat/status/{userId}` holds per
86
+ * person: the automatic `meeting` overlay a call pushed. No entry reads
87
+ * as `{ kind: null, sequence: 0 }`, as the real route does. */
88
+ automaticStatuses = new Map();
82
89
  /** Every `PUT .../typing/...` this server has answered, in order -- for a
83
90
  * test that asserts `sendTyping` actually reached the wire, with what
84
91
  * it sent. */
@@ -1291,6 +1298,14 @@ export class FakeChatServer {
1291
1298
  return jsonResponse(200, { content_uri: `mxc://${this.serverName}/${mediaId}` });
1292
1299
  })();
1293
1300
  }
1301
+ const chatStatus = url.pathname.match(/^\/_chat\/status\/([^/]+)$/);
1302
+ if (chatStatus) {
1303
+ if (!this.#authorised(init)) {
1304
+ return Promise.resolve(jsonResponse(401, { error: 'token_invalid' }));
1305
+ }
1306
+ const found = this.automaticStatuses.get(decodeURIComponent(chatStatus[1]));
1307
+ return Promise.resolve(jsonResponse(200, found ?? { kind: null, sequence: 0 }));
1308
+ }
1294
1309
  // `apps/chat-service`'s thread follow route: the same rule the real one
1295
1310
  // has -- an automatic follow never undoes an unfollow.
1296
1311
  const chatThread = url.pathname.match(/^\/_chat\/threads\/([^/]+)\/([^/]+)\/follow$/);
@@ -1319,6 +1334,9 @@ export class FakeChatServer {
1319
1334
  return jsonResponse(200, { following: found !== undefined && !found.muted });
1320
1335
  })();
1321
1336
  }
1337
+ if (this.threadFollowWriteStatus !== 200) {
1338
+ return Promise.resolve(jsonResponse(this.threadFollowWriteStatus, { error: 'internal_error' }));
1339
+ }
1322
1340
  if (method === 'DELETE')
1323
1341
  this.threadFollows.set(key, { muted: true });
1324
1342
  if (method === 'PUT') {
@@ -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
  }
@@ -1,4 +1,4 @@
1
- import type { BackupTrustInfo, BootstrapCrossSigningOpts, CreateSecretStorageOpts, CryptoApi, DeviceVerificationStatus, GeneratedSecretStorageKey, KeyBackupCheck, KeyBackupInfo, SecretStorageStatus, UserVerificationStatus, VerificationRequest } from 'matrix-js-sdk/lib/crypto-api';
1
+ import type { BackupTrustInfo, BootstrapCrossSigningOpts, CreateSecretStorageOpts, CryptoApi, DeviceVerificationStatus, GeneratedSecretStorageKey, KeyBackupCheck, KeyBackupInfo, SecretStorageStatus, UserVerificationStatus, VerificationRequest } from 'matrix-js-sdk/lib/crypto-api/index.js';
2
2
  /**
3
3
  * The exchange contract, as `apps/chat-service`'s README and
4
4
  * `src/exchange.ts` define it: `POST <exchangeUrl>` with a ZITADEL bearer
@@ -909,6 +909,23 @@ export type ChatClient = {
909
909
  * `onPresenceChanged`: read `status(userId)` for anyone already of
910
910
  * interest before relying on this for what changes next. */
911
911
  onStatusChanged: (listener: (changed: ReadonlyMap<string, ChatStatus | null>) => void) => () => void;
912
+ /** `wtfalch/calls`' automatic "in a meeting" overlay for `userId`
913
+ * (chat#46, calls#39's own decision doc) -- ephemeral, unlike
914
+ * `setOwnStatus`'s durable write, and never written into the explicit
915
+ * status's own profile field. `status()`/`onStatusChanged()` compose it
916
+ * over the person's explicit status rather than replacing it:
917
+ * `automatic ?? explicit`, so clearing it (`kind: null`) only ever
918
+ * reveals whatever the person had already set, never `here`.
919
+ *
920
+ * `sequence` is the sender's own monotonic counter for `userId`; a call
921
+ * whose `sequence` is not strictly greater than the last one applied
922
+ * for that `userId` is dropped without effect, so a retried or
923
+ * out-of-order delivery can never erase a fresher value with a stale
924
+ * one. */
925
+ applyAutomaticStatus: (userId: string, automatic: {
926
+ kind: 'meeting' | null;
927
+ sequence: number;
928
+ }) => void;
912
929
  /** Tells `roomId` the signed-in person has started, or stopped, typing --
913
930
  * `m.typing`, which is not an event: nothing lands in `timeline()`, and
914
931
  * 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.0",
3
+ "version": "0.8.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
  }