@alexsun-top/opencode-chat-room 0.8.3 → 0.8.5

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.
Files changed (156) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +1 -1
  5. package/dist/cli.js +35 -16
  6. package/package.json +15 -9
  7. package/packages/chat-room-channeld/README.md +3 -2
  8. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  9. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  10. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  11. package/packages/chat-room-channeld/src/pg/worker.mjs +107 -99
  12. package/packages/chat-room-channeld/src/pg/worker.mts +166 -0
  13. package/plugin.ts +1 -1
  14. package/server/assets/chat/admin-badge.js +1 -1
  15. package/server/assets/chat/admin.js +16 -10
  16. package/server/assets/chat/announcements.js +12 -2
  17. package/server/assets/chat/attachment-store.js +15 -6
  18. package/server/assets/chat/attachments.js +48 -33
  19. package/server/assets/chat/chat-background.js +8 -14
  20. package/server/assets/chat/clipboard.js +2 -1
  21. package/server/assets/chat/confirm-dialog.js +3 -3
  22. package/server/assets/chat/copy-action.js +1 -2
  23. package/server/assets/chat/diagram-viewer.js +7 -9
  24. package/server/assets/chat/doc-preview.js +19 -12
  25. package/server/assets/chat/editor.js +87 -61
  26. package/server/assets/chat/events.js +49 -34
  27. package/server/assets/chat/files.js +45 -13
  28. package/server/assets/chat/history-loader.js +5 -3
  29. package/server/assets/chat/image-zoom.js +21 -17
  30. package/server/assets/chat/install-prompt.js +10 -9
  31. package/server/assets/chat/integration-account-schema.js +5 -3
  32. package/server/assets/chat/integration-editor.js +2 -2
  33. package/server/assets/chat/integration-values.js +17 -11
  34. package/server/assets/chat/integrations.js +138 -81
  35. package/server/assets/chat/join-requests.js +20 -13
  36. package/server/assets/chat/markdown-footnotes.js +8 -8
  37. package/server/assets/chat/markdown.js +48 -38
  38. package/server/assets/chat/members.js +48 -25
  39. package/server/assets/chat/mentions.js +39 -12
  40. package/server/assets/chat/message-cache.js +2 -2
  41. package/server/assets/chat/message-polling.js +40 -21
  42. package/server/assets/chat/message-window.js +10 -6
  43. package/server/assets/chat/messages.js +70 -46
  44. package/server/assets/chat/office-preview.js +3 -3
  45. package/server/assets/chat/palette.js +45 -29
  46. package/server/assets/chat/panels.js +19 -1
  47. package/server/assets/chat/pwa.js +5 -4
  48. package/server/assets/chat/questions.js +25 -22
  49. package/server/assets/chat/recall.js +39 -21
  50. package/server/assets/chat/receipts.js +9 -7
  51. package/server/assets/chat/reminders.js +25 -8
  52. package/server/assets/chat/replies.js +34 -15
  53. package/server/assets/chat/resource-format.js +2 -2
  54. package/server/assets/chat/room-list.js +2 -2
  55. package/server/assets/chat/room-watcher.js +8 -4
  56. package/server/assets/chat/rooms.js +51 -40
  57. package/server/assets/chat/search.js +8 -6
  58. package/server/assets/chat/settings.js +16 -14
  59. package/server/assets/chat/shiki.js +1 -1
  60. package/server/assets/chat/shortcuts.js +3 -3
  61. package/server/assets/chat/side-pane.js +4 -3
  62. package/server/assets/chat/state.js +65 -37
  63. package/server/assets/chat/system-events.js +6 -5
  64. package/server/assets/chat/system-messages.js +15 -15
  65. package/server/assets/chat/task-form.js +5 -5
  66. package/server/assets/chat/task-row.js +1 -1
  67. package/server/assets/chat/tasks.js +41 -28
  68. package/server/assets/chat/window-controls.js +3 -2
  69. package/server/assets/conversation.css +14 -2
  70. package/server/assets/doc-preview.css +6 -0
  71. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  72. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  73. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  74. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  75. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  76. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  77. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  78. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  79. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  80. package/server/chat.html +1 -0
  81. package/server/sw.js +3 -1
  82. package/skills/chatroom/SKILL.md +9 -0
  83. package/src/README.md +1 -1
  84. package/src/agent/agent-receipts.ts +12 -4
  85. package/src/center/center-client.ts +1 -1
  86. package/src/state/pg-sql.mjs +157 -142
  87. package/src/state/pg-sql.mts +175 -0
  88. package/src/state/pg-worker.mjs +107 -99
  89. package/src/state/pg-worker.mts +166 -0
  90. package/src/state/store.ts +21 -7
  91. package/src/tui/app-types.mjs +1 -0
  92. package/src/tui/app-types.mts +175 -0
  93. package/src/tui/app.mjs +426 -423
  94. package/src/tui/app.mts +500 -0
  95. package/src/tui/config.mjs +166 -158
  96. package/src/tui/config.mts +247 -0
  97. package/src/tui/http.mjs +239 -206
  98. package/src/tui/http.mts +412 -0
  99. package/src/tui/i18n.mjs +17 -20
  100. package/src/tui/i18n.mts +42 -0
  101. package/src/tui/info-app.mjs +431 -427
  102. package/src/tui/info-app.mts +500 -0
  103. package/src/tui/info-content.mjs +205 -199
  104. package/src/tui/info-content.mts +341 -0
  105. package/src/tui/join-app.mjs +75 -64
  106. package/src/tui/join-app.mts +99 -0
  107. package/src/tui/locales/en.mjs +302 -320
  108. package/src/tui/locales/en.mts +349 -0
  109. package/src/tui/locales/zh-CN.mjs +302 -320
  110. package/src/tui/locales/zh-CN.mts +349 -0
  111. package/src/tui/main.mjs +219 -213
  112. package/src/tui/main.mts +255 -0
  113. package/src/tui/markdown.mjs +128 -272
  114. package/src/tui/markdown.mts +152 -0
  115. package/src/tui/mentions.mjs +181 -184
  116. package/src/tui/mentions.mts +251 -0
  117. package/src/tui/message-app.mjs +181 -173
  118. package/src/tui/message-app.mts +213 -0
  119. package/src/tui/message-view.mjs +90 -111
  120. package/src/tui/message-view.mts +151 -0
  121. package/src/tui/messages.mjs +55 -49
  122. package/src/tui/messages.mts +106 -0
  123. package/src/tui/palette-app.mjs +364 -344
  124. package/src/tui/palette-app.mts +388 -0
  125. package/src/tui/palette.mjs +100 -98
  126. package/src/tui/palette.mts +176 -0
  127. package/src/tui/prefs.mjs +56 -63
  128. package/src/tui/prefs.mts +126 -0
  129. package/src/tui/reminder-app.mjs +191 -181
  130. package/src/tui/reminder-app.mts +228 -0
  131. package/src/tui/room-settings-app.mjs +257 -242
  132. package/src/tui/room-settings-app.mts +301 -0
  133. package/src/tui/session.mjs +30 -29
  134. package/src/tui/session.mts +51 -0
  135. package/src/tui/settings-app.mjs +151 -138
  136. package/src/tui/settings-app.mts +179 -0
  137. package/src/tui/ui-content.mjs +426 -421
  138. package/src/tui/ui-content.mts +499 -0
  139. package/src/tui/ui-help.mjs +58 -67
  140. package/src/tui/ui-help.mts +87 -0
  141. package/src/tui/ui-mentions.mjs +34 -36
  142. package/src/tui/ui-mentions.mts +60 -0
  143. package/src/tui/ui-overlay-view.mjs +259 -267
  144. package/src/tui/ui-overlay-view.mts +322 -0
  145. package/src/tui/ui-suggest-view.mjs +54 -57
  146. package/src/tui/ui-suggest-view.mts +78 -0
  147. package/src/tui/ui-suggest.mjs +164 -167
  148. package/src/tui/ui-suggest.mts +248 -0
  149. package/src/tui/ui-theme.mjs +52 -57
  150. package/src/tui/ui-theme.mts +98 -0
  151. package/src/tui/ui-view.mjs +267 -275
  152. package/src/tui/ui-view.mts +308 -0
  153. package/src/tui/ui.mjs +372 -359
  154. package/src/tui/ui.mts +440 -0
  155. package/src/tui/wire.mjs +215 -0
  156. package/src/tui/wire.mts +383 -0
@@ -0,0 +1,500 @@
1
+ // Headless chat state for the TUI. Kept free of terminal and palette code so
2
+ // the reducer can be tested against a fake api. Palette methods are attached
3
+ // from palette-app.mjs.
4
+ import { attachPalette } from "./palette-app.mjs";
5
+ import { attachInfo } from "./info-app.mjs";
6
+ import { attachSettings } from "./settings-app.mjs";
7
+ import { attachReminders } from "./reminder-app.mjs";
8
+ import { attachRoomSettings } from "./room-settings-app.mjs";
9
+ import { attachMessageActions } from "./message-app.mjs";
10
+ import { attachJoinRequests } from "./join-app.mjs";
11
+ import { canonicalizeMentions } from "./mentions.mjs";
12
+ import { mergeMessages, messageStamp, oldestSeq } from "./messages.mjs";
13
+ import type { ChatMessage } from "./messages.mjs";
14
+ import { normalizeLanguage, setLanguage, t } from "./i18n.mjs";
15
+ import { normalizeTheme } from "./prefs.mjs";
16
+ import type { ChatApi } from "./http.mjs";
17
+ import type { RoomWire } from "./wire.mjs";
18
+ import type {
19
+ AppListener,
20
+ AppPrefs,
21
+ AppSettings,
22
+ ChatAppOptions,
23
+ ChatState,
24
+ PendingSend,
25
+ RoomSummary,
26
+ SavePrefs,
27
+ Schedule,
28
+ StatusKind,
29
+ TimerHandle,
30
+ } from "./app-types.mjs";
31
+
32
+ const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];
33
+ const FIRST_BACKOFF = BACKOFF_MS[0] ?? 1000;
34
+ const MAX_BACKOFF = BACKOFF_MS.at(-1) ?? 15000;
35
+
36
+ const joinStatusOf = (result: unknown): unknown =>
37
+ typeof result === "string" ? result
38
+ : result !== null && typeof result === "object" && "status" in result ? result.status : undefined;
39
+
40
+ const errorText = (error: unknown): string => (error instanceof Error ? error.message : String(error ?? "unknown error"));
41
+
42
+ const normalizeRoom = (room: RoomWire): RoomSummary => ({
43
+ id: String(room.id ?? ""),
44
+ name: String(room.name ?? room.id ?? "room"),
45
+ participants: Array.isArray(room.participants) ? room.participants : [],
46
+ joined: room.joined === true,
47
+ });
48
+
49
+ export class ChatApp {
50
+ declare api: ChatApi;
51
+ declare sessionID: string;
52
+ declare participant: string;
53
+ declare autoPoll: boolean;
54
+ declare schedule: Schedule;
55
+ declare savePrefs: SavePrefs | null;
56
+ declare settings: AppSettings;
57
+ declare token: string;
58
+ declare prefs: AppPrefs;
59
+ declare downloadDir: string;
60
+ declare closed: boolean;
61
+ declare pollToken: number;
62
+ declare timers: Set<TimerHandle>;
63
+ declare pollAbort: AbortController | null;
64
+ declare cache: Map<string, ChatMessage[]>;
65
+ declare historyCursor: Map<string, number>;
66
+ declare historyMore: Map<string, boolean>;
67
+ declare historyPages: Map<string, number>;
68
+ declare historyInflight: Set<string>;
69
+ declare listeners: Set<AppListener>;
70
+ declare state: ChatState;
71
+ declare pendingSend: PendingSend | null;
72
+
73
+ constructor({ api, sessionID, participant, host = "", autoPoll = true, settings = {}, savePrefs = null, downloadDir = process.cwd(), schedule = (fn, ms) => setTimeout(fn, ms) }: ChatAppOptions) {
74
+ this.api = api;
75
+ this.sessionID = sessionID;
76
+ this.participant = participant;
77
+ this.autoPoll = autoPoll;
78
+ this.schedule = schedule;
79
+ this.savePrefs = typeof savePrefs === "function" ? savePrefs : null;
80
+ this.settings = { ...settings };
81
+ this.token = this.settings.token ?? "";
82
+ delete this.settings.token;
83
+ this.prefs = {
84
+ language: normalizeLanguage(this.settings.language),
85
+ theme: normalizeTheme(this.settings.theme),
86
+ participant: this.settings.participant ?? participant,
87
+ url: this.settings.server ?? "",
88
+ };
89
+ setLanguage(this.prefs.language);
90
+ this.downloadDir = downloadDir;
91
+ this.closed = false;
92
+ this.pollToken = 0;
93
+ this.timers = new Set();
94
+ this.pollAbort = null;
95
+ this.cache = new Map();
96
+ this.historyCursor = new Map();
97
+ this.historyMore = new Map();
98
+ this.historyPages = new Map();
99
+ this.historyInflight = new Set();
100
+ this.listeners = new Set();
101
+ this.state = {
102
+ host,
103
+ participant,
104
+ theme: this.prefs.theme,
105
+ language: this.prefs.language,
106
+ connection: "connecting",
107
+ rooms: [],
108
+ selected: 0,
109
+ current: null,
110
+ joined: false,
111
+ messages: [],
112
+ pending: null,
113
+ focus: "rooms",
114
+ draft: "",
115
+ highlight: null,
116
+ help: false,
117
+ status: "",
118
+ statusKind: "info",
119
+ palette: null,
120
+ quit: false,
121
+ };
122
+ }
123
+
124
+ subscribe(listener: AppListener) {
125
+ this.listeners.add(listener);
126
+ return () => this.listeners.delete(listener);
127
+ }
128
+
129
+ touch() {
130
+ for (const listener of this.listeners) listener(this.state);
131
+ }
132
+
133
+ later(fn: () => unknown, ms: number) {
134
+ if (this.closed) return undefined;
135
+ let timer: TimerHandle | undefined;
136
+ const run = () => {
137
+ if (timer !== undefined) this.timers.delete(timer);
138
+ return fn();
139
+ };
140
+ timer = this.schedule(run, ms);
141
+ if (timer !== undefined) this.timers.add(timer);
142
+ return timer;
143
+ }
144
+
145
+ setStatus(text: string, kind: StatusKind = "info") {
146
+ this.state.status = text;
147
+ this.state.statusKind = kind;
148
+ this.touch();
149
+ }
150
+
151
+ async init() {
152
+ await this.refreshRooms(true);
153
+ }
154
+
155
+ async refreshRooms(quiet = false) {
156
+ try {
157
+ const list = await this.api.listRooms(this.sessionID);
158
+ const rooms = (Array.isArray(list) ? list : []).map(normalizeRoom);
159
+ const selectedID = this.state.rooms[this.state.selected]?.id;
160
+ this.state.rooms = rooms;
161
+ const found = selectedID ? rooms.findIndex((room) => room.id === selectedID) : -1;
162
+ this.state.selected = found >= 0 ? found : Math.min(this.state.selected, Math.max(0, rooms.length - 1));
163
+ this.state.connection = "online";
164
+ if (!quiet) {
165
+ this.state.status = t("status.refreshed");
166
+ this.state.statusKind = "info";
167
+ }
168
+ this.touch();
169
+ return true;
170
+ } catch (error) {
171
+ this.state.connection = "offline";
172
+ this.state.status = t("status.refreshFailed", { error: errorText(error) });
173
+ this.state.statusKind = "error";
174
+ this.touch();
175
+ return false;
176
+ }
177
+ }
178
+
179
+ isCurrent(roomID: string) {
180
+ return this.state.current?.id === roomID;
181
+ }
182
+
183
+ async openSelected() {
184
+ return this.openRoom(this.state.selected);
185
+ }
186
+
187
+ async openRoom(indexOrRoom: number | RoomSummary) {
188
+ const index = typeof indexOrRoom === "number" ? indexOrRoom : this.state.rooms.indexOf(indexOrRoom);
189
+ const summary = this.state.rooms[index];
190
+ if (!summary) return;
191
+ this.state.selected = index;
192
+ this.stopPolling();
193
+ this.state.current = { id: summary.id, name: summary.name, participants: summary.participants };
194
+ this.state.joined = summary.joined;
195
+ this.state.messages = [];
196
+ this.state.pending = null;
197
+ this.state.highlight = null;
198
+ this.state.status = t("status.opening", { name: summary.name });
199
+ this.state.statusKind = "info";
200
+ this.touch();
201
+ if (summary.joined) await this.loadRoom(summary.id);
202
+ else await this.joinRoom(summary.id);
203
+ }
204
+
205
+ async joinRoom(roomID: string) {
206
+ try {
207
+ const result = await this.api.join(roomID, this.sessionID, this.participant);
208
+ if (!this.isCurrent(roomID)) return;
209
+ if (result.pending) {
210
+ const message = String(result.message ?? t("status.joinPending"));
211
+ this.state.pending = { roomId: roomID, message };
212
+ this.state.joined = false;
213
+ this.state.status = message;
214
+ this.state.statusKind = "info";
215
+ this.touch();
216
+ this.later(() => this.checkJoin(roomID), 1500);
217
+ return;
218
+ }
219
+ this.enterRoom(result.room, roomID, true);
220
+ } catch (error) {
221
+ if (this.isCurrent(roomID)) this.setStatus(t("status.joinFailed", { error: errorText(error) }), "error");
222
+ }
223
+ }
224
+
225
+ async checkJoin(roomID: string) {
226
+ if (this.closed || !this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
227
+ try {
228
+ const status = joinStatusOf(await this.api.joinStatus(roomID, this.sessionID));
229
+ if (!this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
230
+ if (status === "joined") {
231
+ this.state.pending = null;
232
+ this.setStatus(t("status.joinApproved"), "success");
233
+ await this.loadRoom(roomID);
234
+ return;
235
+ }
236
+ if (status === "pending") {
237
+ this.later(() => this.checkJoin(roomID), 1500);
238
+ return;
239
+ }
240
+ this.state.pending = null;
241
+ this.setStatus(t("status.joinStale"), "error");
242
+ } catch {
243
+ this.later(() => this.checkJoin(roomID), 1500);
244
+ }
245
+ }
246
+
247
+ async loadRoom(roomID: string) {
248
+ try {
249
+ const room = await this.api.getRoom(roomID);
250
+ if (!this.isCurrent(roomID) || !room) return;
251
+ if (room.joined === false) {
252
+ this.notJoined(roomID, t("status.notMember"));
253
+ return;
254
+ }
255
+ this.enterRoom(room, roomID, false);
256
+ } catch (error) {
257
+ if (this.isCurrent(roomID)) this.setStatus(t("status.openFailed", { error: errorText(error) }), "error");
258
+ }
259
+ }
260
+
261
+ enterRoom(room: RoomWire | null, roomID: string, joinedNow: boolean) {
262
+ if (!room || typeof room !== "object") {
263
+ this.setStatus(t("status.roomMissing"), "error");
264
+ return;
265
+ }
266
+ const summary = this.state.rooms.find((item) => item.id === roomID);
267
+ if (summary) {
268
+ summary.joined = true;
269
+ summary.name = String(room.name ?? summary.name);
270
+ if (Array.isArray(room.participants)) summary.participants = room.participants;
271
+ }
272
+ const cache = this.historyList(roomID);
273
+ mergeMessages(cache, room.messages);
274
+ this.state.current = {
275
+ id: roomID,
276
+ name: String(room.name ?? summary?.name ?? roomID),
277
+ participants: Array.isArray(room.participants) ? room.participants : summary?.participants ?? [],
278
+ };
279
+ this.state.joined = true;
280
+ this.state.pending = null;
281
+ this.state.messages = cache;
282
+ this.state.connection = "online";
283
+ this.state.status = joinedNow ? t("status.joined", { name: this.state.current.name }) : "";
284
+ this.state.statusKind = "success";
285
+ if (typeof room.hasMore === "boolean") this.historyMore.set(roomID, room.hasMore);
286
+ const oldest = oldestSeq(cache);
287
+ if (oldest !== undefined) this.historyCursor.set(roomID, oldest);
288
+ this.touch();
289
+ this.markRead();
290
+ if (this.autoPoll) this.startPolling();
291
+ }
292
+
293
+ historyList(roomID: string): ChatMessage[] {
294
+ let list = this.cache.get(roomID);
295
+ if (!list) {
296
+ list = [];
297
+ this.cache.set(roomID, list);
298
+ }
299
+ return list;
300
+ }
301
+
302
+ merge(items: unknown) {
303
+ mergeMessages(this.state.messages, items);
304
+ }
305
+
306
+ lastTs(): number {
307
+ return this.state.messages.reduce((max, message) => Math.max(max, messageStamp(message)), 0);
308
+ }
309
+
310
+ async pollOnce(): Promise<boolean> {
311
+ const room = this.state.current;
312
+ if (!room || !this.state.joined) return false;
313
+ const roomID = room.id;
314
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
315
+ this.pollAbort = controller;
316
+ try {
317
+ const result = await this.api.poll(
318
+ roomID,
319
+ this.sessionID,
320
+ this.lastTs(),
321
+ controller ? { signal: controller.signal } : undefined,
322
+ );
323
+ if (!this.isCurrent(roomID)) return false;
324
+ if (result === null) throw new Error("Invalid inbox response");
325
+ if (result.member === false) {
326
+ this.notJoined(roomID, t("status.memberLost"));
327
+ return false;
328
+ }
329
+ const wasOffline = this.state.connection !== "online";
330
+ this.merge(result.items);
331
+ this.state.connection = "online";
332
+ if (wasOffline) {
333
+ this.state.status = t("status.reconnected");
334
+ this.state.statusKind = "success";
335
+ }
336
+ this.touch();
337
+ this.markRead();
338
+ return true;
339
+ } catch (error) {
340
+ if (controller?.signal.aborted) return false;
341
+ this.state.connection = "reconnecting";
342
+ this.state.status = t("status.connectionLost", { error: errorText(error) });
343
+ this.state.statusKind = "error";
344
+ this.touch();
345
+ return false;
346
+ } finally {
347
+ if (this.pollAbort === controller) this.pollAbort = null;
348
+ }
349
+ }
350
+
351
+ startPolling() {
352
+ const token = ++this.pollToken;
353
+ let delay = 0;
354
+ const step = async () => {
355
+ if (this.closed || token !== this.pollToken || !this.state.joined) return;
356
+ const ok = await this.pollOnce();
357
+ if (this.closed || token !== this.pollToken || !this.state.joined) return;
358
+ delay = ok ? 0 : Math.min(delay ? delay * 2 : FIRST_BACKOFF, MAX_BACKOFF);
359
+ this.later(step, delay);
360
+ };
361
+ void step();
362
+ }
363
+
364
+ stopPolling() {
365
+ this.pollToken += 1;
366
+ this.pollAbort?.abort();
367
+ }
368
+
369
+ notJoined(roomID: string, message: string) {
370
+ if (!this.isCurrent(roomID)) return;
371
+ this.state.joined = false;
372
+ const summary = this.state.rooms.find((room) => room.id === roomID);
373
+ if (summary) summary.joined = false;
374
+ this.setStatus(message, "error");
375
+ }
376
+
377
+ markRead() {
378
+ const room = this.state.current;
379
+ const newest = this.lastTs();
380
+ if (!room || !newest) return;
381
+ try {
382
+ const result = this.api.markRead?.(room.id, this.sessionID, newest);
383
+ if (result && typeof result.catch === "function") result.catch(() => {});
384
+ } catch {
385
+ // A read receipt failure must not interrupt the UI.
386
+ }
387
+ }
388
+
389
+ async send() {
390
+ const raw = String(this.state.draft ?? "").trim();
391
+ if (!raw) return;
392
+ const room = this.state.current;
393
+ if (!room || !this.state.joined) {
394
+ this.setStatus(t("status.joinBeforeSend"), "error");
395
+ return;
396
+ }
397
+ const text = canonicalizeMentions(raw, room.participants);
398
+ // Reuse the attempt's id when the same failed text is sent again, so a lost
399
+ // response cannot produce two messages.
400
+ const attempt = this.pendingSend && this.pendingSend.text === raw
401
+ ? this.pendingSend
402
+ : { text: raw, clientMessageID: globalThis.crypto.randomUUID() };
403
+ this.pendingSend = attempt;
404
+ this.state.draft = "";
405
+ this.touch();
406
+ try {
407
+ const result = await this.api.send(room.id, this.sessionID, text, { clientMessageID: attempt.clientMessageID });
408
+ if (!this.isCurrent(room.id)) return;
409
+ this.pendingSend = null;
410
+ if (Array.isArray(result?.messages)) this.merge(result.messages);
411
+ else if (result?.id) this.merge([result]);
412
+ this.state.highlight = null;
413
+ this.state.connection = "online";
414
+ this.setStatus(t("status.sent"), "success");
415
+ this.markRead();
416
+ } catch (error) {
417
+ // Keep text typed while the request was in flight; dropping it loses work.
418
+ this.state.draft = this.state.draft ? `${raw}\n${this.state.draft}` : raw;
419
+ this.setStatus(t("status.sendFailed", { error: errorText(error) }), "error");
420
+ }
421
+ }
422
+
423
+ setDraft(text: string) {
424
+ this.state.draft = String(text ?? "");
425
+ }
426
+
427
+ appendDraft(text: string) {
428
+ this.state.draft += String(text ?? "");
429
+ this.state.focus = "composer";
430
+ this.state.help = false;
431
+ this.touch();
432
+ }
433
+
434
+ moveSelection(delta: number) {
435
+ if (!this.state.rooms.length) return;
436
+ this.state.selected = Math.min(
437
+ this.state.rooms.length - 1,
438
+ Math.max(0, this.state.selected + delta),
439
+ );
440
+ this.state.highlight = null;
441
+ this.touch();
442
+ }
443
+
444
+ selectRoom(index: number) {
445
+ if (!this.state.rooms[index]) return;
446
+ this.state.selected = index;
447
+ this.state.highlight = null;
448
+ this.touch();
449
+ }
450
+
451
+ toggleFocus() {
452
+ this.state.focus = this.state.focus === "rooms" ? "composer" : "rooms";
453
+ if (this.state.focus === "composer") this.state.help = false;
454
+ this.touch();
455
+ }
456
+
457
+ toggleHelp() {
458
+ this.state.help = !this.state.help;
459
+ this.touch();
460
+ }
461
+
462
+ clearOrBlur() {
463
+ this.state.draft = "";
464
+ this.state.focus = "rooms";
465
+ this.state.highlight = null;
466
+ this.touch();
467
+ }
468
+
469
+ clearHighlight() {
470
+ if (!this.state.highlight) return;
471
+ this.state.highlight = null;
472
+ this.touch();
473
+ }
474
+
475
+ quit() {
476
+ this.state.quit = true;
477
+ this.close();
478
+ this.touch();
479
+ }
480
+
481
+ close() {
482
+ this.closed = true;
483
+ this.pollToken += 1;
484
+ this.pollAbort?.abort();
485
+ for (const timer of this.timers) clearTimeout(timer);
486
+ this.timers.clear();
487
+ }
488
+ }
489
+
490
+ attachPalette(ChatApp);
491
+ attachInfo(ChatApp);
492
+ attachSettings(ChatApp);
493
+ attachReminders(ChatApp);
494
+ attachRoomSettings(ChatApp);
495
+ attachMessageActions(ChatApp);
496
+ attachJoinRequests(ChatApp);
497
+
498
+ export function createApp(options: ChatAppOptions) {
499
+ return new ChatApp(options);
500
+ }