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

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 (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
@@ -1,498 +1,571 @@
1
1
  import { createRandomId, LS, LOADED_MESSAGE_LIMIT } from "./state.js";
2
2
  import { renderMarkdown } from "./markdown.js";
3
- import { hasMessageSelection, pruneMessageRows, trimMessages, focusedMessage } from "./message-window.js";
3
+ import { pruneMessageRows, trimMessages, focusedMessage } from "./message-window.js";
4
4
  import { setRoomPreview } from "./system-messages.js";
5
5
  import { renderSystemRow } from "./system-events.js";
6
6
  import { installEditor } from "./editor.js";
7
7
  import { adminAgentBadge, isAdminAgent } from "./admin-badge.js";
8
8
  import { initMessagePolling } from "./message-polling.js";
9
9
  import { iconNode } from "./icons.js";
10
-
11
10
  export function initMessages(app) {
12
- const $ = app.$;
13
- installEditor($("#msgInput"));
14
- $("#msgInput").isKnownMention = (name) => app.mentionExists(name);
15
- $("#msgInput").mentionLabel = (name) => name === "all" ? app.t("allMembers") : name;
16
-
17
- app.autoGrow = (textarea) => {
18
- const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
19
- const scrollTop = textarea.scrollTop;
20
- textarea.dataset.empty = textarea.value ? "false" : "true";
21
- textarea.style.overflowY = "hidden";
22
- const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
23
- const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
24
- const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
25
- if (!textarea.value) {
26
- textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
27
- if (atBottom) thread.scrollTop = thread.scrollHeight;
28
- return;
29
- }
30
- textarea.style.height = "auto";
31
- const limit = line * 5 + padding;
32
- const overflow = textarea.scrollHeight > limit + 1;
33
- textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
34
- textarea.style.overflowY = overflow ? "auto" : "hidden";
35
- // Collapsing the height to measure content resets scrollTop; keep the caret view where it was.
36
- if (overflow) textarea.scrollTop = scrollTop;
37
- if (atBottom) thread.scrollTop = thread.scrollHeight;
38
- };
39
- app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
40
- app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
41
- app.renderFailedMessages = () => {
42
- const composer = $("#msgInput").closest(".composer");
43
- let panel = composer.querySelector(".failed-messages");
44
- if (!panel) {
45
- panel = document.createElement("section");
46
- panel.className = "failed-messages";
47
- panel.setAttribute("aria-live", "polite");
48
- composer.insertBefore(panel, $(".composer-row"));
49
- }
50
- const roomId = app.state.room?.id, items = roomId && app.state.failedMessages.get(roomId) || [];
51
- panel.textContent = "";
52
- panel.hidden = !items.length;
53
- if (!items.length) return;
54
- const heading = document.createElement("h3");
55
- heading.textContent = app.t("failedMessages");
56
- panel.append(heading);
57
- for (const item of items) {
58
- const row = document.createElement("article"), text = document.createElement("p");
59
- row.className = "failed-message";
60
- if (item.replyTarget) {
61
- const context = document.createElement("small"); context.className = "failed-reply-context";
62
- context.textContent = `${item.replyTarget.senderId}: ${String(item.replyTarget.text).slice(0, 120)}`;
63
- row.dataset.replyTargetId = item.replyToMessageID; row.append(context);
64
- }
65
- text.textContent = item.text;
66
- row.append(text, failedAction("retryFailed", roomId, item.id, app), failedAction("discardFailed", roomId, item.id, app));
67
- panel.append(row);
68
- }
69
- };
70
- app.discardFailedMessage = (roomId, failedId) => {
71
- app.saveFailedMessages(roomId, (app.state.failedMessages.get(roomId) || []).filter((item) => item.id !== failedId));
72
- app.renderFailedMessages();
73
- };
74
- // A retry reuses the first attempt's clientMessageID so a lost response
75
- // cannot create a twin.
76
- app.retryFailedMessage = async (roomId, failedId) => {
77
- const item = app.state.failedMessages.get(roomId)?.find((message) => message.id === failedId);
78
- if (!item || app.state.retryingFailedIds.has(failedId)) return;
79
- app.state.retryingFailedIds.add(failedId);
80
- app.renderFailedMessages();
81
- try {
82
- const questionTarget = item.replyTarget?.isQuestion, entry = app.state.rooms.get(roomId);
83
- const updated = questionTarget ? (await app.answerQuestionFromReply(roomId, item.replyToMessageID, item.text), entry?.room)
84
- : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.clientMessageID ? { clientMessageID: item.clientMessageID } : {}), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
85
- app.completeAttachmentsFromText?.(roomId, item.text);
86
- if (entry) {
87
- if (!questionTarget) entry.room = mergeRoom(entry.room, updated);
88
- const latest = entry.room.messages.at(-1);
89
- if (latest && latest.createdAt >= entry.previewAt) setRoomPreview(entry, latest);
90
- }
91
- app.discardFailedMessage(roomId, failedId);
92
- if (app.state.room?.id === roomId && entry) {
93
- app.state.room = entry.room;
94
- app.renderMessages(true);
95
- app.renderMembers();
96
- app.markActiveRoomRead();
97
- app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
98
- app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
99
- }
100
- } catch (error) {
101
- if (app.state.room?.id === roomId) app.showSendError(error.status === 401 ? "sendAuth" : error.network ? "sendNetwork" : "sendFailed", { message: error.message });
102
- } finally {
103
- app.state.retryingFailedIds.delete(failedId);
104
- app.renderFailedMessages();
105
- }
106
- };
107
- app.jumpToBottom = () => {
108
- app.cancelThreadScrollAnimation?.();
109
- app.state.userScrollIntentUntil = 0;
110
- app.state.readAnchorGuard = null;
111
- app.state.followBottom = true;
112
- if (app.state.focusMessageId) {
113
- app.state.focusMessageId = null;
114
- app.rerenderMessages();
115
- }
116
- $("#thread").scrollTop = $("#thread").scrollHeight;
117
- const entry = app.state.room && app.state.rooms.get(app.state.room.id);
118
- app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
119
- app.updateBadge();
120
- app.updateJump();
121
- void app.markActiveRoomRead(true);
122
- };
123
- app.updateJump = () => {
124
- const thread = $("#thread");
125
- // Match the distance that already counts as read, so unread never hides the button.
126
- const away = thread.scrollHeight - thread.scrollTop - thread.clientHeight > 80;
127
- $("#btnJump").hidden = !away;
128
- };
129
- app.updateBadge = () => {
130
- const badge = $("#jumpBadge");
131
- badge.textContent = app.state.unread > 99 ? "99+" : String(app.state.unread);
132
- badge.hidden = app.state.unread === 0;
133
- app.updateTitle();
134
- };
135
- // Stop at the first message that failed to render: a later readable message
136
- // must not push the watermark past one we still cannot show.
137
- const readTimestamp = (room, entry) => {
138
- let timestamp = entry.readTs;
139
- for (const message of room.messages) {
140
- if (message.pending) continue;
141
- if (app.failedRenderIds.has(message.id)) break;
142
- timestamp = Math.max(timestamp, message.createdAt);
143
- }
144
- return timestamp;
145
- };
146
- // Persist the watermark with a keepalive request so it survives the tab
147
- // closing before the normal async read acknowledgement completes.
148
- app.flushReadOnHide = () => {
149
- const room = app.state.room, entry = room && app.state.rooms.get(room.id);
150
- const thread = $("#thread");
151
- if (!room || !entry || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
152
- const timestamp = readTimestamp(room, entry);
153
- if (timestamp <= entry.readTs) return;
154
- void app.api("/read", { method: "POST", keepalive: true, body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }) }).catch(() => {});
155
- };
156
- app.markActiveRoomRead = async (interactive = false) => {
157
- const room = app.state.room, entry = room && app.state.rooms.get(room.id);
158
- const generation = app.state.pollGeneration;
159
- const thread = $("#thread");
160
- if (!room || !entry || document.hidden || (!interactive && !document.hasFocus())
161
- || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
162
- // Reaching this point means the room is within the read distance of the bottom,
163
- // so the restore guard has done its job even without a user scroll.
164
- if (app.state.readAnchorGuard?.roomId === room.id) app.state.readAnchorGuard = null;
165
- const timestamp = readTimestamp(room, entry);
166
- const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
167
- let advanced = false;
168
- app.state.readRequests ||= new Set();
169
- // One acknowledgement at a time; scrolling fires this on every frame near the bottom.
170
- if (timestamp > entry.readTs && !app.state.readRequests.has(room.id)) {
171
- app.state.readRequests.add(room.id);
172
- try {
173
- await app.api("/read", {
174
- method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
175
- });
176
- if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
177
- entry.readTs = timestamp;
178
- app.saveReadTs(room.id, timestamp);
179
- entry.unreadOverflow = false;
180
- advanced = true;
181
- } catch { return; /* The next active poll will retry the read watermark. */ }
182
- finally { app.state.readRequests.delete(room.id); }
183
- }
184
- // Unread means "not seen": the read watermark clears everything it covers,
185
- // including questions. Pending answers are surfaced by the Questions panel.
186
- const known = new Map(room.messages.map((message) => [message.id, message]));
187
- for (const [id, message] of entry.unreadIds) {
188
- const current = known.get(id) || message;
189
- // Clear what the watermark covers, plus own messages the watcher misread.
190
- if (current.createdAt <= entry.readTs || !isUnreadMessage(current, app, room)) entry.unreadIds.delete(id);
191
- else if (known.has(id)) entry.unreadIds.set(id, current);
192
- }
193
- app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
194
- if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
195
- app.updateBadge();
196
- app.updateJump();
197
- app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
198
- app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
199
- }
200
- };
201
-
202
- // Today keeps the compact clock; older messages carry the date because the
203
- // day separator scrolls away or gets trimmed.
204
- app.messageTime = (timestamp) => new Date(timestamp).toDateString() === new Date().toDateString()
205
- ? app.timeHM(timestamp) : app.fmtTime(timestamp);
206
-
207
- app.renderMessage = (message, live) => {
208
- const row = document.createElement("li");
209
- row.dataset.sender = message.senderId;
210
- row.dataset.ts = message.createdAt;
211
- row.dataset.msgId = message.id;
212
- if (message.senderId === "system") {
213
- renderSystemRow(row, message, app);
214
- } else {
215
- const direct = app.state.room.kind === "direct";
216
- const own = isOwnMessage(message, app);
217
- const sender = direct
218
- ? app.state.room.participants.find((person) => person.id === message.senderId)?.name || app.t("guest")
219
- : message.senderId;
220
- row.className = `msg${own ? " own" : ""}`;
221
- const meta = document.createElement("div"), name = document.createElement("span"), time = document.createElement("span");
222
- meta.className = "msg-meta";
223
- name.className = "msg-name";
224
- name.textContent = own ? app.t("you") : sender;
225
- time.className = "msg-time";
226
- time.textContent = app.messageTime(message.createdAt);
227
- meta.append(name);
228
- if (isAdminAgent(app, message.senderSessionID || message.senderId)) meta.append(adminAgentBadge(app));
229
- meta.append(time);
230
- const body = document.createElement("div");
231
- body.className = "msg-text";
232
- renderMarkdown(body, message.text, app);
233
- const content = document.createElement("div");
234
- content.className = "msg-content";
235
- content.append(body);
236
- if (!message.pending) content.append(app.createReceiptButton(message, own));
237
- row.append(meta, content);
238
- }
239
- if (message.senderId !== "system") {
240
- const copy = document.createElement("button");
241
- copy.type = "button";
242
- copy.className = "message-copy";
243
- copy.dataset.copyMessage = "";
244
- copy.setAttribute("aria-label", app.t("copyMessage"));
245
- copy.dataset.i18nAriaLabel = "copyMessage";
246
- copy.dataset.i18nTitle = "copyMessage";
247
- copy.title = app.t("copyMessage");
248
- const icon = iconNode("copy", "message-copy-icon");
249
- const feedback = document.createElement("span");
250
- feedback.className = "message-copy-feedback"; feedback.dataset.flashOutput = ""; feedback.dataset.i18n = "copyMessage";
251
- feedback.hidden = true; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite"); feedback.textContent = app.t("copyMessage");
252
- copy.append(icon, feedback);
253
- copy._copyText = String(message.text ?? "");
254
- row.append(copy);
255
- }
256
- if (message.pending) row.classList.add("pending");
257
- if (live) row.classList.add("in");
258
- return row;
259
- };
260
-
261
- app.renderMessages = (live = false, tailLimit = 0) => {
262
- const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
263
- // A palette jump renders a window around the target instead of the newest
264
- // tail. While that window is up, live appends stay off screen so the target
265
- // is not trimmed away.
266
- const focus = focusedMessage(app, list, messages);
267
- if (focus?.existing) { app.updateJump(); return { skipped: 0 }; }
268
- const nearBottom = !focus && thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 80;
269
- let skipped = 0;
270
- let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
271
- const viewport = thread.getBoundingClientRect();
272
- const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
273
- anchorId = firstVisible?.dataset.msgId || null;
274
- anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
275
- if (focus) {
276
- // Start a fresh window containing the target, wherever it sits in the
277
- // loaded state (which can hold up to LOADED_MESSAGE_LIMIT messages).
278
- list.textContent = "";
279
- app.rendered = 0;
280
- }
281
- pruneMessageRows(list, messages);
282
- let last = list.lastElementChild;
283
- const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
284
- let startIndex = 0;
285
- const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
286
- if (lastId) for (let index = messages.length - 1; index >= 0; index--) if (messages[index].id === lastId) { startIndex = index + 1; break; }
287
- const renderStart = focus ? Math.max(0, focus.index - 120) : Math.max(startIndex, tailLimit ? messages.length - tailLimit : 0);
288
- const renderEnd = focus ? Math.min(messages.length, focus.index + 120) : messages.length;
289
- for (let index = renderStart; index < renderEnd; index++) {
290
- const message = messages[index];
291
- if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id)) continue;
292
- try {
293
- const day = new Date(message.createdAt).toDateString();
294
- if (!last || last.dataset.day !== day) {
295
- const separator = document.createElement("li");
296
- separator.className = "day-sep";
297
- separator.dataset.day = day;
298
- separator.textContent = app.dayText(message.createdAt);
299
- list.append(separator);
300
- last = separator;
11
+ const $ = app.$;
12
+ installEditor($("#msgInput"));
13
+ $("#msgInput").isKnownMention = (name) => app.mentionExists(name);
14
+ $("#msgInput").mentionLabel = (name) => name === "all" ? app.t("allMembers") : name;
15
+ app.autoGrow = (textarea) => {
16
+ const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
17
+ const scrollTop = textarea.scrollTop;
18
+ textarea.dataset.empty = textarea.value ? "false" : "true";
19
+ textarea.style.overflowY = "hidden";
20
+ const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
21
+ const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
22
+ const border = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
23
+ if (!textarea.value) {
24
+ textarea.style.height = `${Math.max(line + padding + border, parseFloat(style.minHeight) || 0)}px`;
25
+ if (atBottom)
26
+ thread.scrollTop = thread.scrollHeight;
27
+ return;
301
28
  }
302
- const row = app.renderMessage(message, live);
303
- row.dataset.day = day;
304
- if (last.classList.contains("msg") && last.dataset.sender === message.senderId
305
- && message.createdAt - Number(last.dataset.ts) < 8 * 60 * 1000) row.classList.add("repeat");
306
- list.append(row);
307
- last = row;
308
- renderedIds.add(message.id);
309
- } catch (error) {
310
- console.error("[chat] Message could not render", error);
311
- skipped++;
312
- app.failedRenderIds.add(message.id);
313
- }
314
- }
315
- app.rendered = messages.length;
316
- app.firstMessageId = messages[0]?.id || app.firstMessageId;
317
- $("#msgEmpty").hidden = messages.length > 0;
318
- if (nearBottom) thread.scrollTop = thread.scrollHeight;
319
- else if (anchorId) {
320
- const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
321
- if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - viewport.top - anchorOffset;
322
- else thread.scrollTop = oldTop;
323
- } else if (!live || nearBottom) thread.scrollTop = thread.scrollHeight;
324
- app.updateJump();
325
- trimMessages(list, app);
326
- if (nearBottom) {
327
- thread.scrollTop = thread.scrollHeight;
328
- const roomId = app.state.room?.id, generation = app.state.pollGeneration;
329
- requestAnimationFrame(() => {
330
- if (app.state.room?.id === roomId && app.state.pollGeneration === generation
331
- && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) thread.scrollTop = thread.scrollHeight;
332
- });
333
- }
334
- else if (anchorId) {
335
- const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
336
- if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorOffset;
337
- else thread.scrollTop = oldTop;
338
- }
339
- // Late growth (images, diagrams, attachments) is handled by the list ResizeObserver:
340
- // it re-pins the thread while the reader is following the newest message.
341
- app.queueReceiptRefresh?.();
342
- app.queueReceiptObservation?.();
343
- return { skipped };
344
- };
345
-
346
- app.rerenderMessages = () => {
347
- if (!app.state.room) return { skipped: 0 };
348
- const thread = $("#thread"), list = $("#msgList"), oldTop = thread.scrollTop;
349
- const atBottom = thread.scrollHeight - oldTop - thread.clientHeight < 80;
350
- const edge = thread.getBoundingClientRect();
351
- const anchor = [...list.querySelectorAll("[data-msg-id]")].find((node) => node.getBoundingClientRect().bottom > edge.top);
352
- const anchorId = anchor?.dataset.msgId;
353
- const anchorOffset = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
354
- $("#msgList").textContent = "";
355
- app.rendered = 0;
356
- app.firstMessageId = null;
357
- app.failedRenderIds.clear();
358
- const result = app.renderMessages(false);
359
- const nextAnchor = anchorId && list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
360
- if (atBottom) thread.scrollTop = thread.scrollHeight;
361
- else if (nextAnchor) thread.scrollTop += nextAnchor.getBoundingClientRect().top - edge.top - anchorOffset;
362
- else thread.scrollTop = oldTop;
363
- return result;
364
- };
365
-
366
- app.send = async () => {
367
- const input = $("#msgInput"), room = app.state.room, replyTarget = room && app.replyTargetFor?.(room.id);
368
- if (!room || app.state.sendingRooms?.has(room.id)) return false;
369
- const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
370
- if (!message.ready) return false;
371
- // Clicking Send focuses the button; it is disabled when the draft clears, so
372
- // keep the caret in the composer or the next keystrokes go nowhere.
373
- input.focus({ preventScroll: true });
374
- const text = message.text;
375
- const clientMessageID = createRandomId();
376
- const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
377
- const revision = app.state.draftRevision.get(room.id) || 0;
378
- app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
379
- app.closeMention();
380
- app.clearReplyTarget?.(room.id);
381
- input.value = "";
382
- app.clearDraft(room.id);
383
- app.autoGrow(input);
384
- app.updateDraftCount();
385
- app.updateSendState();
386
- app.hideSendError();
387
- const pending = {
388
- id: `pending-${createRandomId()}`, roomId: room.id, text,
389
- senderId: room.kind === "direct" ? LS.sessionID : app.state.myName,
390
- senderSessionID: LS.sessionID, createdAt: Date.now(), pending: true,
391
- ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}),
29
+ textarea.style.height = "auto";
30
+ const limit = line * 5 + padding;
31
+ const overflow = textarea.scrollHeight > limit + 1;
32
+ textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
33
+ textarea.style.overflowY = overflow ? "auto" : "hidden";
34
+ // Collapsing the height to measure content resets scrollTop; keep the caret view where it was.
35
+ if (overflow)
36
+ textarea.scrollTop = scrollTop;
37
+ if (atBottom)
38
+ thread.scrollTop = thread.scrollHeight;
39
+ };
40
+ app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
41
+ app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
42
+ app.renderFailedMessages = () => {
43
+ const composer = $("#msgInput").closest(".composer");
44
+ let panel = composer.querySelector(".failed-messages");
45
+ if (!panel) {
46
+ panel = document.createElement("section");
47
+ panel.className = "failed-messages";
48
+ panel.setAttribute("aria-live", "polite");
49
+ composer.insertBefore(panel, $(".composer-row"));
50
+ }
51
+ const roomId = app.state.room?.id, items = roomId && app.state.failedMessages.get(roomId) || [];
52
+ panel.textContent = "";
53
+ panel.hidden = !items.length;
54
+ if (!items.length)
55
+ return;
56
+ const heading = document.createElement("h3");
57
+ heading.textContent = app.t("failedMessages");
58
+ panel.append(heading);
59
+ for (const item of items) {
60
+ const row = document.createElement("article"), text = document.createElement("p");
61
+ row.className = "failed-message";
62
+ if (item.replyTarget) {
63
+ const context = document.createElement("small");
64
+ context.className = "failed-reply-context";
65
+ context.textContent = `${item.replyTarget.senderId}: ${String(item.replyTarget.text).slice(0, 120)}`;
66
+ row.dataset.replyTargetId = item.replyToMessageID;
67
+ row.append(context);
68
+ }
69
+ text.textContent = item.text;
70
+ row.append(text, failedAction("retryFailed", roomId, item.id, app), failedAction("discardFailed", roomId, item.id, app));
71
+ panel.append(row);
72
+ }
73
+ };
74
+ app.discardFailedMessage = (roomId, failedId) => {
75
+ app.saveFailedMessages(roomId, (app.state.failedMessages.get(roomId) || []).filter((item) => item.id !== failedId));
76
+ app.renderFailedMessages();
392
77
  };
393
- room.messages.push(pending);
394
- app.renderMessages(true);
395
- if (followedBottom) thread.scrollTop = thread.scrollHeight;
396
- try {
397
- let updated;
398
- if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
399
- else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
400
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
401
- });
402
- // A successful request proves the connection is usable, even if a stale
403
- // long-poll is still waiting to time out.
404
- app.setOnline(true);
405
- app.completeAttachments?.(room.id, message.ids);
406
- const pendingIndex = room.messages.findIndex((item) => item.id === pending.id);
407
- if (pendingIndex >= 0) room.messages.splice(pendingIndex, 1);
408
- if (app.state.room?.id !== room.id) return true;
409
- const entry = app.state.rooms.get(room.id);
410
- // The POST snapshot is older than anything polling received while it was
411
- // in flight; merge instead of dropping those messages.
412
- let current = updated;
413
- if (entry) {
414
- const merged = new Map([...entry.room.messages, ...updated.messages].filter((item) => !item.pending).map((item) => [item.id, { ...item, roomId: updated.id }]));
415
- const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
416
- if (messages.length > LOADED_MESSAGE_LIMIT) messages.splice(0, messages.length - LOADED_MESSAGE_LIMIT);
417
- app.cacheRoomSoon?.(room.id);
418
- current = { ...updated, messages };
419
- }
420
- app.state.room = current;
421
- if (entry) {
422
- entry.room = current;
423
- const latest = current.messages.at(-1);
424
- if (latest) setRoomPreview(entry, latest);
425
- }
426
- app.renderMessages(true);
427
- // Reading history and sending must not teleport to the newest message or mark it read.
428
- if (followedBottom) $("#thread").scrollTop = $("#thread").scrollHeight;
429
- app.renderMembers();
430
- app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
431
- app.updateBadge();
432
- void app.markActiveRoomRead();
433
- app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
434
- app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
435
- return true;
436
- } catch (error) {
437
- const pendingIndex = room.messages.findIndex((item) => item.id === pending.id);
438
- if (pendingIndex >= 0) room.messages.splice(pendingIndex, 1);
439
- if (app.state.room?.id === room.id) app.renderMessages(false);
440
- const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
441
- // Someone answered the question first; retrying the answer can never succeed,
442
- // so keep the text as a draft instead of a failed message.
443
- const staleReply = Boolean(replyTarget?.isQuestion) && (error.status === 409 || error.status === 404);
444
- if (staleReply) app.saveDraft(room.id, text);
445
- else {
446
- const failures = app.state.failedMessages.get(room.id) || [];
447
- app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
78
+ // A retry reuses the first attempt's clientMessageID so a lost response
79
+ // cannot create a twin.
80
+ app.retryFailedMessage = async (roomId, failedId) => {
81
+ const item = app.state.failedMessages.get(roomId)?.find((message) => message.id === failedId);
82
+ if (!item || app.state.retryingFailedIds.has(failedId))
83
+ return;
84
+ app.state.retryingFailedIds.add(failedId);
448
85
  app.renderFailedMessages();
449
- }
450
- app.completeAttachments?.(room.id, message.ids);
451
- if (app.state.room?.id !== room.id) return false;
452
- if (unchanged && !staleReply) app.clearDraft(room.id);
453
- if (staleReply) input.draftValue = text;
454
- app.autoGrow(input);
455
- app.updateSendState();
456
- app.updateDraftCount();
457
- if (error.status === 401) { app.openChatSettings(); app.showSendError("sendAuth"); }
458
- else app.showSendError(error.network ? "sendNetwork" : "sendFailed", { message: error.message });
459
- return false;
460
- } finally {
461
- app.state.sendingRooms.delete(room.id);
462
- if (app.state.room?.id === room.id) app.updateSendState();
86
+ try {
87
+ const questionTarget = item.replyTarget?.isQuestion, entry = app.state.rooms.get(roomId);
88
+ const updated = questionTarget ? (await app.answerQuestionFromReply(roomId, item.replyToMessageID, item.text), entry?.room)
89
+ : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.clientMessageID ? { clientMessageID: item.clientMessageID } : {}), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
90
+ app.completeAttachmentsFromText?.(roomId, item.text);
91
+ if (entry) {
92
+ if (!questionTarget)
93
+ entry.room = mergeRoom(entry.room, updated);
94
+ const latest = entry.room.messages.at(-1);
95
+ if (latest && latest.createdAt >= entry.previewAt)
96
+ setRoomPreview(entry, latest);
97
+ }
98
+ app.discardFailedMessage(roomId, failedId);
99
+ if (app.state.room?.id === roomId && entry) {
100
+ app.state.room = entry.room;
101
+ app.renderMessages(true);
102
+ app.renderMembers();
103
+ app.markActiveRoomRead();
104
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
105
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
106
+ }
107
+ }
108
+ catch (error) {
109
+ if (app.state.room?.id === roomId)
110
+ app.showSendError(error.status === 401 ? "sendAuth" : error.network ? "sendNetwork" : "sendFailed", { message: error.message });
111
+ }
112
+ finally {
113
+ app.state.retryingFailedIds.delete(failedId);
114
+ app.renderFailedMessages();
115
+ }
116
+ };
117
+ app.jumpToBottom = () => {
118
+ app.cancelThreadScrollAnimation?.();
119
+ app.state.userScrollIntentUntil = 0;
120
+ app.state.readAnchorGuard = null;
121
+ app.state.followBottom = true;
122
+ if (app.state.focusMessageId) {
123
+ app.state.focusMessageId = null;
124
+ app.rerenderMessages();
125
+ }
126
+ $("#thread").scrollTop = $("#thread").scrollHeight;
127
+ const entry = app.state.room && app.state.rooms.get(app.state.room.id);
128
+ app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
129
+ app.updateBadge();
130
+ app.updateJump();
131
+ void app.markActiveRoomRead(true);
132
+ };
133
+ app.updateJump = () => {
134
+ const thread = $("#thread");
135
+ // Match the distance that already counts as read, so unread never hides the button.
136
+ const away = thread.scrollHeight - thread.scrollTop - thread.clientHeight > 80;
137
+ $("#btnJump").hidden = !away;
138
+ };
139
+ app.updateBadge = () => {
140
+ const badge = $("#jumpBadge");
141
+ badge.textContent = app.state.unread > 99 ? "99+" : String(app.state.unread);
142
+ badge.hidden = app.state.unread === 0;
143
+ app.updateTitle();
144
+ };
145
+ // Stop at the first message that failed to render: a later readable message
146
+ // must not push the watermark past one we still cannot show.
147
+ const readTimestamp = (room, entry) => {
148
+ let timestamp = entry.readTs;
149
+ for (const message of room.messages) {
150
+ if (message.pending)
151
+ continue;
152
+ if (app.failedRenderIds.has(message.id))
153
+ break;
154
+ timestamp = Math.max(timestamp, message.createdAt);
155
+ }
156
+ return timestamp;
157
+ };
158
+ // Persist the watermark with a keepalive request so it survives the tab
159
+ // closing before the normal async read acknowledgement completes.
160
+ app.flushReadOnHide = () => {
161
+ const room = app.state.room, entry = room && app.state.rooms.get(room.id);
162
+ const thread = $("#thread");
163
+ if (!room || !entry || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80)
164
+ return;
165
+ const timestamp = readTimestamp(room, entry);
166
+ if (timestamp <= entry.readTs)
167
+ return;
168
+ void app.api("/read", { method: "POST", keepalive: true, body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }) }).catch(() => { });
169
+ };
170
+ app.markActiveRoomRead = async (interactive = false) => {
171
+ const room = app.state.room, entry = room && app.state.rooms.get(room.id);
172
+ const generation = app.state.pollGeneration;
173
+ const thread = $("#thread");
174
+ if (!room || !entry || document.hidden || (!interactive && !document.hasFocus())
175
+ || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80)
176
+ return;
177
+ // Reaching this point means the room is within the read distance of the bottom,
178
+ // so the restore guard has done its job even without a user scroll.
179
+ if (app.state.readAnchorGuard?.roomId === room.id)
180
+ app.state.readAnchorGuard = null;
181
+ const timestamp = readTimestamp(room, entry);
182
+ const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
183
+ let advanced = false;
184
+ app.state.readRequests ||= new Set();
185
+ // One acknowledgement at a time; scrolling fires this on every frame near the bottom.
186
+ if (timestamp > entry.readTs && !app.state.readRequests.has(room.id)) {
187
+ app.state.readRequests.add(room.id);
188
+ try {
189
+ await app.api("/read", {
190
+ method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
191
+ });
192
+ if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation)
193
+ return;
194
+ entry.readTs = timestamp;
195
+ app.saveReadTs(room.id, timestamp);
196
+ entry.unreadOverflow = false;
197
+ advanced = true;
198
+ }
199
+ catch {
200
+ return; /* The next active poll will retry the read watermark. */
201
+ }
202
+ finally {
203
+ app.state.readRequests.delete(room.id);
204
+ }
205
+ }
206
+ // Unread means "not seen": the read watermark clears everything it covers,
207
+ // including questions. Pending answers are surfaced by the Questions panel.
208
+ const known = new Map(room.messages.map((message) => [message.id, message]));
209
+ for (const [id, message] of entry.unreadIds) {
210
+ const current = known.get(id) || message;
211
+ // Clear what the watermark covers, plus own messages the watcher misread.
212
+ if (current.createdAt <= entry.readTs || !isUnreadMessage(current, app, room))
213
+ entry.unreadIds.delete(id);
214
+ else if (known.has(id))
215
+ entry.unreadIds.set(id, current);
216
+ }
217
+ app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
218
+ if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
219
+ app.updateBadge();
220
+ app.updateJump();
221
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
222
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
223
+ }
224
+ };
225
+ // Today keeps the compact clock; older messages carry the date because the
226
+ // day separator scrolls away or gets trimmed.
227
+ app.messageTime = (timestamp) => new Date(timestamp).toDateString() === new Date().toDateString()
228
+ ? app.timeHM(timestamp) : app.fmtTime(timestamp);
229
+ app.renderMessage = (message, live) => {
230
+ const row = document.createElement("li");
231
+ row.dataset.sender = message.senderId;
232
+ row.dataset.ts = message.createdAt;
233
+ row.dataset.msgId = message.id;
234
+ if (message.senderId === "system") {
235
+ renderSystemRow(row, message, app);
236
+ }
237
+ else {
238
+ const direct = app.state.room.kind === "direct";
239
+ const own = isOwnMessage(message, app);
240
+ const sender = direct
241
+ ? app.state.room.participants.find((person) => person.id === message.senderId)?.name || app.t("guest")
242
+ : message.senderId;
243
+ row.className = `msg${own ? " own" : ""}`;
244
+ row.dataset.initial = Array.from((own ? app.state.myName : sender).trim())[0]?.toLocaleUpperCase() || "?";
245
+ const meta = document.createElement("div"), name = document.createElement("span"), time = document.createElement("span");
246
+ meta.className = "msg-meta";
247
+ name.className = "msg-name";
248
+ name.textContent = own ? app.t("you") : sender;
249
+ time.className = "msg-time";
250
+ time.textContent = app.messageTime(message.createdAt);
251
+ meta.append(name);
252
+ if (isAdminAgent(app, message.senderSessionID || message.senderId))
253
+ meta.append(adminAgentBadge(app));
254
+ meta.append(time);
255
+ const body = document.createElement("div");
256
+ body.className = "msg-text";
257
+ renderMarkdown(body, message.text, app);
258
+ const content = document.createElement("div");
259
+ content.className = "msg-content";
260
+ content.append(body);
261
+ if (!message.pending)
262
+ content.append(app.createReceiptButton(message, own));
263
+ row.append(meta, content);
264
+ }
265
+ if (message.senderId !== "system") {
266
+ const copy = document.createElement("button");
267
+ copy.type = "button";
268
+ copy.className = "message-copy";
269
+ copy.dataset.copyMessage = "";
270
+ copy.setAttribute("aria-label", app.t("copyMessage"));
271
+ copy.dataset.i18nAriaLabel = "copyMessage";
272
+ copy.dataset.i18nTitle = "copyMessage";
273
+ copy.title = app.t("copyMessage");
274
+ const icon = iconNode("copy", "message-copy-icon");
275
+ const feedback = document.createElement("span");
276
+ feedback.className = "message-copy-feedback";
277
+ feedback.dataset.flashOutput = "";
278
+ feedback.dataset.i18n = "copyMessage";
279
+ feedback.hidden = true;
280
+ feedback.setAttribute("role", "status");
281
+ feedback.setAttribute("aria-live", "polite");
282
+ feedback.textContent = app.t("copyMessage");
283
+ copy.append(icon, feedback);
284
+ copy._copyText = String(message.text ?? "");
285
+ row.append(copy);
286
+ }
287
+ if (message.pending)
288
+ row.classList.add("pending");
289
+ if (live)
290
+ row.classList.add("in");
291
+ return row;
292
+ };
293
+ app.renderMessages = (live = false, tailLimit = 0) => {
294
+ const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
295
+ // A palette jump renders a window around the target instead of the newest
296
+ // tail. While that window is up, live appends stay off screen so the target
297
+ // is not trimmed away.
298
+ const focus = focusedMessage(app, list, messages);
299
+ if (focus?.existing) {
300
+ app.updateJump();
301
+ return { skipped: 0 };
302
+ }
303
+ const nearBottom = !focus && thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 80;
304
+ let skipped = 0;
305
+ let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
306
+ const viewport = thread.getBoundingClientRect();
307
+ const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
308
+ anchorId = firstVisible?.dataset.msgId || null;
309
+ anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
310
+ if (focus) {
311
+ // Start a fresh window containing the target, wherever it sits in the
312
+ // loaded state (which can hold up to LOADED_MESSAGE_LIMIT messages).
313
+ list.textContent = "";
314
+ app.rendered = 0;
315
+ }
316
+ pruneMessageRows(list, messages);
317
+ let last = list.lastElementChild;
318
+ const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
319
+ let startIndex = 0;
320
+ const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
321
+ if (lastId)
322
+ for (let index = messages.length - 1; index >= 0; index--)
323
+ if (messages[index].id === lastId) {
324
+ startIndex = index + 1;
325
+ break;
326
+ }
327
+ const renderStart = focus ? Math.max(0, focus.index - 120) : Math.max(startIndex, tailLimit ? messages.length - tailLimit : 0);
328
+ const renderEnd = focus ? Math.min(messages.length, focus.index + 120) : messages.length;
329
+ for (let index = renderStart; index < renderEnd; index++) {
330
+ const message = messages[index];
331
+ if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id))
332
+ continue;
333
+ try {
334
+ const day = new Date(message.createdAt).toDateString();
335
+ if (!last || last.dataset.day !== day) {
336
+ const separator = document.createElement("li");
337
+ separator.className = "day-sep";
338
+ separator.dataset.day = day;
339
+ separator.textContent = app.dayText(message.createdAt);
340
+ list.append(separator);
341
+ last = separator;
342
+ }
343
+ const row = app.renderMessage(message, live);
344
+ row.dataset.day = day;
345
+ if (last.classList.contains("msg") && last.dataset.sender === message.senderId
346
+ && message.createdAt - Number(last.dataset.ts) < 8 * 60 * 1000)
347
+ row.classList.add("repeat");
348
+ list.append(row);
349
+ last = row;
350
+ renderedIds.add(message.id);
351
+ }
352
+ catch (error) {
353
+ console.error("[chat] Message could not render", error);
354
+ skipped++;
355
+ app.failedRenderIds.add(message.id);
356
+ }
357
+ }
358
+ app.rendered = messages.length;
359
+ app.firstMessageId = messages[0]?.id || app.firstMessageId;
360
+ $("#msgEmpty").hidden = messages.length > 0;
361
+ if (nearBottom)
362
+ thread.scrollTop = thread.scrollHeight;
363
+ else if (anchorId) {
364
+ const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
365
+ if (anchor)
366
+ thread.scrollTop += anchor.getBoundingClientRect().top - viewport.top - anchorOffset;
367
+ else
368
+ thread.scrollTop = oldTop;
369
+ }
370
+ else if (!live || nearBottom)
371
+ thread.scrollTop = thread.scrollHeight;
372
+ app.updateJump();
373
+ trimMessages(list, app);
374
+ if (nearBottom) {
375
+ thread.scrollTop = thread.scrollHeight;
376
+ const roomId = app.state.room?.id, generation = app.state.pollGeneration;
377
+ requestAnimationFrame(() => {
378
+ if (app.state.room?.id === roomId && app.state.pollGeneration === generation
379
+ && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80)
380
+ thread.scrollTop = thread.scrollHeight;
381
+ });
382
+ }
383
+ else if (anchorId) {
384
+ const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
385
+ if (anchor)
386
+ thread.scrollTop += anchor.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorOffset;
387
+ else
388
+ thread.scrollTop = oldTop;
389
+ }
390
+ // Late growth (images, diagrams, attachments) is handled by the list ResizeObserver:
391
+ // it re-pins the thread while the reader is following the newest message.
392
+ app.queueReceiptRefresh?.();
393
+ app.queueReceiptObservation?.();
394
+ return { skipped };
395
+ };
396
+ app.rerenderMessages = () => {
397
+ if (!app.state.room)
398
+ return { skipped: 0 };
399
+ const thread = $("#thread"), list = $("#msgList"), oldTop = thread.scrollTop;
400
+ const atBottom = thread.scrollHeight - oldTop - thread.clientHeight < 80;
401
+ const edge = thread.getBoundingClientRect();
402
+ const anchor = [...list.querySelectorAll("[data-msg-id]")].find((node) => node.getBoundingClientRect().bottom > edge.top);
403
+ const anchorId = anchor?.dataset.msgId;
404
+ const anchorOffset = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
405
+ $("#msgList").textContent = "";
406
+ app.rendered = 0;
407
+ app.firstMessageId = null;
408
+ app.failedRenderIds.clear();
409
+ const result = app.renderMessages(false);
410
+ const nextAnchor = anchorId && list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
411
+ if (atBottom)
412
+ thread.scrollTop = thread.scrollHeight;
413
+ else if (nextAnchor)
414
+ thread.scrollTop += nextAnchor.getBoundingClientRect().top - edge.top - anchorOffset;
415
+ else
416
+ thread.scrollTop = oldTop;
417
+ return result;
418
+ };
419
+ app.send = async () => {
420
+ const input = $("#msgInput"), room = app.state.room, replyTarget = room && app.replyTargetFor?.(room.id);
421
+ if (!room || app.state.sendingRooms?.has(room.id))
422
+ return false;
423
+ const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
424
+ if (!message.ready)
425
+ return false;
426
+ // Clicking Send focuses the button; it is disabled when the draft clears, so
427
+ // keep the caret in the composer or the next keystrokes go nowhere.
428
+ input.focus({ preventScroll: true });
429
+ const text = message.text;
430
+ const clientMessageID = createRandomId();
431
+ const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
432
+ const revision = app.state.draftRevision.get(room.id) || 0;
433
+ app.state.sendingRooms ||= new Set();
434
+ app.state.sendingRooms.add(room.id);
435
+ app.closeMention();
436
+ app.clearReplyTarget?.(room.id);
437
+ input.value = "";
438
+ app.clearDraft(room.id);
439
+ app.autoGrow(input);
440
+ app.updateDraftCount();
441
+ app.updateSendState();
442
+ app.hideSendError();
443
+ const pending = {
444
+ id: `pending-${createRandomId()}`, roomId: room.id, text,
445
+ senderId: room.kind === "direct" ? LS.sessionID : app.state.myName,
446
+ senderSessionID: LS.sessionID, createdAt: Date.now(), pending: true,
447
+ ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}),
448
+ };
449
+ room.messages.push(pending);
450
+ app.renderMessages(true);
451
+ if (followedBottom)
452
+ thread.scrollTop = thread.scrollHeight;
453
+ try {
454
+ let updated;
455
+ if (replyTarget?.isQuestion) {
456
+ await app.answerQuestionFromReply(room.id, replyTarget.id, text);
457
+ updated = app.state.rooms.get(room.id)?.room || room;
458
+ }
459
+ else
460
+ updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
461
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
462
+ });
463
+ // A successful request proves the connection is usable, even if a stale
464
+ // long-poll is still waiting to time out.
465
+ app.setOnline(true);
466
+ app.completeAttachments?.(room.id, message.ids);
467
+ const pendingIndex = room.messages.findIndex((item) => item.id === pending.id);
468
+ if (pendingIndex >= 0)
469
+ room.messages.splice(pendingIndex, 1);
470
+ if (app.state.room?.id !== room.id)
471
+ return true;
472
+ const entry = app.state.rooms.get(room.id);
473
+ // The POST snapshot is older than anything polling received while it was
474
+ // in flight; merge instead of dropping those messages.
475
+ let current = updated;
476
+ if (entry) {
477
+ const merged = new Map([...entry.room.messages, ...updated.messages].filter((item) => !item.pending).map((item) => [item.id, { ...item, roomId: updated.id }]));
478
+ const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
479
+ if (messages.length > LOADED_MESSAGE_LIMIT)
480
+ messages.splice(0, messages.length - LOADED_MESSAGE_LIMIT);
481
+ app.cacheRoomSoon?.(room.id);
482
+ current = { ...updated, messages };
483
+ }
484
+ app.state.room = current;
485
+ if (entry) {
486
+ entry.room = current;
487
+ const latest = current.messages.at(-1);
488
+ if (latest)
489
+ setRoomPreview(entry, latest);
490
+ }
491
+ app.renderMessages(true);
492
+ // Reading history and sending must not teleport to the newest message or mark it read.
493
+ if (followedBottom)
494
+ $("#thread").scrollTop = $("#thread").scrollHeight;
495
+ app.renderMembers();
496
+ app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
497
+ app.updateBadge();
498
+ void app.markActiveRoomRead();
499
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
500
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
501
+ return true;
502
+ }
503
+ catch (error) {
504
+ const pendingIndex = room.messages.findIndex((item) => item.id === pending.id);
505
+ if (pendingIndex >= 0)
506
+ room.messages.splice(pendingIndex, 1);
507
+ if (app.state.room?.id === room.id)
508
+ app.renderMessages(false);
509
+ const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
510
+ // Someone answered the question first; retrying the answer can never succeed,
511
+ // so keep the text as a draft instead of a failed message.
512
+ const staleReply = Boolean(replyTarget?.isQuestion) && (error.status === 409 || error.status === 404);
513
+ if (staleReply)
514
+ app.saveDraft(room.id, text);
515
+ else {
516
+ const failures = app.state.failedMessages.get(room.id) || [];
517
+ app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
518
+ app.renderFailedMessages();
519
+ }
520
+ app.completeAttachments?.(room.id, message.ids);
521
+ if (app.state.room?.id !== room.id)
522
+ return false;
523
+ if (unchanged && !staleReply)
524
+ app.clearDraft(room.id);
525
+ if (staleReply)
526
+ input.draftValue = text;
527
+ app.autoGrow(input);
528
+ app.updateSendState();
529
+ app.updateDraftCount();
530
+ if (error.status === 401) {
531
+ app.openChatSettings();
532
+ app.showSendError("sendAuth");
533
+ }
534
+ else
535
+ app.showSendError(error.network ? "sendNetwork" : "sendFailed", { message: error.message });
536
+ return false;
537
+ }
538
+ finally {
539
+ app.state.sendingRooms.delete(room.id);
540
+ if (app.state.room?.id === room.id)
541
+ app.updateSendState();
542
+ }
543
+ };
544
+ function failedAction(key, roomId, failedId, app) {
545
+ const button = document.createElement("button");
546
+ button.type = "button";
547
+ button.textContent = app.t(key);
548
+ button.dataset.failedAction = key === "retryFailed" ? "retry" : "discard";
549
+ button.dataset.failedRoom = roomId;
550
+ button.dataset.failedId = failedId;
551
+ button.disabled = app.state.retryingFailedIds.has(failedId);
552
+ return button;
553
+ }
554
+ function mergeRoom(current, updated) {
555
+ const messages = new Map([...(current?.messages || []), ...updated.messages].map((message) => [message.id, message]));
556
+ return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-LOADED_MESSAGE_LIMIT) };
463
557
  }
464
- };
465
-
466
-
467
- function failedAction(key, roomId, failedId, app) {
468
- const button = document.createElement("button");
469
- button.type = "button";
470
- button.textContent = app.t(key);
471
- button.dataset.failedAction = key === "retryFailed" ? "retry" : "discard";
472
- button.dataset.failedRoom = roomId;
473
- button.dataset.failedId = failedId;
474
- button.disabled = app.state.retryingFailedIds.has(failedId);
475
- return button;
476
- }
477
-
478
- function mergeRoom(current, updated) {
479
- const messages = new Map([...(current?.messages || []), ...updated.messages].map((message) => [message.id, message]));
480
- return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-LOADED_MESSAGE_LIMIT) };
481
- }
482
-
483
- initMessagePolling(app, isUnreadMessage);
558
+ initMessagePolling(app, isUnreadMessage);
484
559
  }
485
-
486
560
  // Unread means a person said something you have not seen; join/leave notices are not a badge.
487
561
  export function isUnreadMessage(message, app, room = app.state.room, myName = app.state.myName) {
488
- return message.senderId !== "system" && !isOwnMessage(message, app, room, myName);
562
+ return message.senderId !== "system" && !isOwnMessage(message, app, room, myName);
489
563
  }
490
-
491
564
  export function isOwnMessage(message, app, room = app.state.room, myName = app.state.myName) {
492
- const direct = room.kind === "direct";
493
- const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
494
- return direct ? message.senderId === LS.sessionID
495
- : message.senderSessionID ? message.senderSessionID === LS.sessionID
496
- // Without a recorded sender session, fall back to the name unless a namesake is known.
497
- : message.senderId === myName && (!sameName || sameName.every((member) => member.sessionID === LS.sessionID));
565
+ const direct = room.kind === "direct";
566
+ const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
567
+ return direct ? message.senderId === LS.sessionID
568
+ : message.senderSessionID ? message.senderSessionID === LS.sessionID
569
+ // Without a recorded sender session, fall back to the name unless a namesake is known.
570
+ : message.senderId === myName && (!sameName || sameName.every((member) => member.sessionID === LS.sessionID));
498
571
  }