@alexsun-top/opencode-chat-room 0.5.4 → 0.6.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +13 -1
  3. package/README.zh-CN.md +13 -1
  4. package/docs/administrator-rooms.md +7 -16
  5. package/package.json +3 -1
  6. package/server/admin-auth.ts +2 -7
  7. package/server/admin-routes.ts +8 -69
  8. package/server/assets/base.css +8 -0
  9. package/server/assets/chat/admin.js +56 -108
  10. package/server/assets/chat/editor.js +28 -3
  11. package/server/assets/chat/events.js +40 -13
  12. package/server/assets/chat/history-loader.js +65 -0
  13. package/server/assets/chat/index.js +2 -0
  14. package/server/assets/chat/markdown.js +11 -4
  15. package/server/assets/chat/message-cache.js +51 -0
  16. package/server/assets/chat/messages.js +69 -33
  17. package/server/assets/chat/questions.js +12 -9
  18. package/server/assets/chat/reminders.js +1 -1
  19. package/server/assets/chat/replies.js +11 -6
  20. package/server/assets/chat/room-watcher.js +10 -6
  21. package/server/assets/chat/rooms.js +59 -16
  22. package/server/assets/chat/state.js +17 -15
  23. package/server/assets/chat/system-messages.js +2 -1
  24. package/server/assets/conversation.css +13 -3
  25. package/server/assets/responsive.css +1 -0
  26. package/server/chat-server.ts +22 -19
  27. package/server/chat.html +14 -18
  28. package/server/json-body.ts +8 -0
  29. package/server/newrooms.ts +53 -27
  30. package/server/room-payload.ts +29 -0
  31. package/skills/chatroom/SKILL.md +5 -2
  32. package/src/agent-receipts.ts +3 -3
  33. package/src/center-inbox.ts +2 -0
  34. package/src/plugin-notifications.ts +2 -0
  35. package/src/room-service.ts +1 -0
  36. package/src/sqlite-state.ts +47 -10
  37. package/src/store.ts +9 -4
  38. package/src/v2-plugin.ts +17 -0
@@ -1,5 +1,6 @@
1
1
  import { LS } from "./state.js";
2
2
  import { copyTextToClipboard } from "./markdown.js";
3
+ import { isUnreadMessage } from "./messages.js";
3
4
 
4
5
  export function initEvents(app) {
5
6
  const $ = app.$;
@@ -19,9 +20,16 @@ export function initEvents(app) {
19
20
  const anchor = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((row) => row.getBoundingClientRect().bottom > top);
20
21
  readingPosition = { roomId: app.state.room?.id, messageId: anchor?.dataset.msgId, offset: anchor ? anchor.getBoundingClientRect().top - top : 0,
21
22
  atBottom: thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 4 };
22
- const missing = app.state.readAnchorGuard?.roomId === readingPosition.roomId && app.state.readAnchorGuard.missing;
23
+ const guard = app.state.readAnchorGuard;
24
+ let missing = guard?.roomId === readingPosition.roomId && guard.missing;
25
+ // A failed restore keeps its anchor while the landing stays put; scrolling to a
26
+ // different message means the reader chose a new position and the old one is stale.
27
+ if (missing) {
28
+ if (!guard.landingId) guard.landingId = readingPosition.messageId;
29
+ else if (readingPosition.messageId !== guard.landingId) missing = guard.missing = false;
30
+ }
23
31
  if (readingPosition.roomId && anchor && (!missing || performance.now() <= app.state.userScrollIntentUntil)) {
24
- app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId, offset: readingPosition.offset });
32
+ app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId, offset: readingPosition.offset, atBottom: readingPosition.atBottom });
25
33
  }
26
34
  }
27
35
  app.captureReadingPosition = captureReadingPosition;
@@ -50,17 +58,25 @@ export function initEvents(app) {
50
58
  };
51
59
  app.restoreReadingPosition = (roomId) => {
52
60
  const thread = $("#thread"), saved = app.state.positions.get(roomId), entry = app.state.rooms.get(roomId);
61
+ const atBottom = () => thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 4;
53
62
  const align = (messageId, offset) => {
54
63
  const row = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((item) => item.dataset.msgId === messageId);
55
64
  if (!row) return false;
56
65
  thread.scrollTop += row.getBoundingClientRect().top - (thread.getBoundingClientRect().top + thread.clientTop + offset);
57
66
  captureReadingPosition(); return true;
58
67
  };
59
- if (typeof saved === "number") { thread.scrollTop = saved; captureReadingPosition(); return { messageId: readingPosition?.messageId }; }
60
- if (saved?.messageId && align(saved.messageId, Number(saved.offset) || 0)) return { messageId: saved.messageId };
68
+ if (typeof saved === "number") { thread.scrollTop = saved; captureReadingPosition(); return { messageId: readingPosition?.messageId, atBottom: atBottom() }; }
61
69
  const readTs = entry?.readTs || app.state.lastReadTs.get(roomId) || 0;
62
- const boundary = readTs && entry?.room.messages.find((message) => message.createdAt > readTs);
63
- if (boundary && align(boundary.id, 0)) return { messageId: boundary.id };
70
+ // Own messages never form an unread boundary; landing on them hides the newest activity.
71
+ const boundary = readTs && entry?.room.messages.find((message) => message.createdAt > readTs && isUnreadMessage(message, app, entry.room, entry.name));
72
+ // Leaving at the bottom and returning to new messages lands on the first unread;
73
+ // a deliberate scroll position is restored exactly.
74
+ if ((entry?.unreadIds.size || entry?.unreadOverflow) && saved?.atBottom !== false && boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
75
+ // Left at the bottom with nothing unread: land on the live bottom, not the
76
+ // old anchor — late-loading cards can grow content below the saved row.
77
+ if (saved?.atBottom === true && !entry?.unreadIds.size && !entry?.unreadOverflow) { thread.scrollTop = thread.scrollHeight; captureReadingPosition(); return { messageId: readingPosition?.messageId, atBottom: atBottom() }; }
78
+ if (saved?.messageId && align(saved.messageId, Number(saved.offset) || 0)) return { messageId: saved.messageId, atBottom: atBottom() };
79
+ if (boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
64
80
  if (!saved && !boundary) return false;
65
81
  return saved?.messageId || readTs ? { messageId: saved?.messageId || null, missing: true } : false;
66
82
  };
@@ -100,7 +116,8 @@ export function initEvents(app) {
100
116
  }
101
117
  syncRoomDrawer();
102
118
  window.addEventListener("resize", preserveReadingPosition);
103
- window.addEventListener("pagehide", captureReadingPosition);
119
+ window.addEventListener("pagehide", () => { captureReadingPosition(); app.flushReadOnHide?.(); });
120
+ document.addEventListener("visibilitychange", () => { if (document.hidden) { captureReadingPosition(); app.flushReadOnHide?.(); } });
104
121
  drawerTrigger.addEventListener("click", () => {
105
122
  if (roomRail.classList.contains("drawer-open")) return closeRoomDrawer();
106
123
  app.closePanels(); roomRail.inert = false; roomRail.removeAttribute("aria-hidden"); roomRail.classList.add("drawer-open");
@@ -205,7 +222,14 @@ export function initEvents(app) {
205
222
  }
206
223
  if (!event.isComposing) app.recomputeMention();
207
224
  });
208
- input.addEventListener("compositionend", () => app.recomputeMention(input));
225
+ input.addEventListener("compositionend", () => {
226
+ // An ESC-cancelled composition next to a chip can leave the caret inside the
227
+ // non-editable chip, which blocks typing; re-seat it in a real text node.
228
+ const anchor = getSelection()?.anchorNode;
229
+ const element = anchor?.nodeType === Node.ELEMENT_NODE ? anchor : anchor?.parentElement;
230
+ if (element?.closest(".editor-mention")) input.setCaret(input.selectionStart);
231
+ app.recomputeMention(input);
232
+ });
209
233
  input.addEventListener("keydown", (event) => handleMessageKey(event, app));
210
234
  input.addEventListener("keyup", (event) => {
211
235
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention();
@@ -242,6 +266,7 @@ export function initEvents(app) {
242
266
  app.queueReceiptRefresh();
243
267
  if (!adjusting) app.queueReceiptObservation();
244
268
  app.updateJump();
269
+ if (!adjusting && thread.scrollTop < 160) void app.loadOlderHistory?.();
245
270
  });
246
271
  document.addEventListener("visibilitychange", () => {
247
272
  if (!document.hidden) {
@@ -255,7 +280,7 @@ export function initEvents(app) {
255
280
  });
256
281
  $("#msgList").addEventListener("click", (event) => {
257
282
  const messageButton = event.target.closest("[data-copy-message]");
258
- if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
283
+ if (messageButton) void copyTextToClipboard(messageButton._copyText, true).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
259
284
  });
260
285
  ["#inRoomId", "#inName", "#inRoomName"].forEach((selector) => {
261
286
  $(selector).addEventListener("input", app.hideJoinError);
@@ -299,12 +324,12 @@ export function initEvents(app) {
299
324
  app.applyLocale();
300
325
  $("#inToken").value = LS.token;
301
326
  $("#inTokenChat").value = LS.token;
302
- void app.refreshRoomList();
327
+ void app.seedFromCache?.().finally(() => app.refreshRoomList());
303
328
  if (!$("#joinView").hidden) $("#inRoomId").focus();
304
329
  }
305
330
 
306
331
  async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, signal) {
307
- let beforeSeq;
332
+ let beforeSeq, reachedStart = false;
308
333
  const messages = [];
309
334
  while (!signal?.aborted) {
310
335
  const query = new URLSearchParams({ limit: "100" });
@@ -314,12 +339,15 @@ async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, sign
314
339
  messages.push(...(result.messages || []));
315
340
  const found = messageId ? messages.some((message) => message.id === messageId)
316
341
  : messages.some((message) => message.createdAt > readTs) && messages.some((message) => message.createdAt <= readTs);
317
- if (found || !result.hasMore || !result.nextBeforeSeq || result.nextBeforeSeq === beforeSeq) break;
342
+ if (found || !result.hasMore || !result.nextBeforeSeq || result.nextBeforeSeq === beforeSeq) { reachedStart = !result.hasMore; break; }
318
343
  beforeSeq = result.nextBeforeSeq;
319
344
  }
320
345
  if (messageId ? !messages.some((message) => message.id === messageId) : !messages.some((message) => message.createdAt > readTs)) return;
321
346
  const merged = new Map([...entry.room.messages, ...messages].map((message) => [message.id, { ...message, roomId }]));
322
347
  entry.room.messages = [...merged.values()].sort((left, right) => left.createdAt - right.createdAt);
348
+ // Keep the upward-pagination cursor aligned with what the anchor load fetched.
349
+ if (typeof entry.room.messages[0]?.seq === "number") entry.historyBeforeSeq = entry.room.messages[0].seq;
350
+ if (reachedStart) entry.historyComplete = true;
323
351
  }
324
352
 
325
353
  function saveAccessToken(button, app) {
@@ -331,7 +359,6 @@ function saveAccessToken(button, app) {
331
359
  try { persistent = localStorage.getItem("chat.token") === LS.token; } catch { /* Memory fallback is tab-scoped. */ }
332
360
  app.flash(button, persistent ? "saved" : "savedMemory");
333
361
  void app.refreshRoomList();
334
- void app.verifyAdminToken?.();
335
362
  app.retryPendingAction();
336
363
  }
337
364
 
@@ -0,0 +1,65 @@
1
+ import { LOADED_MESSAGE_LIMIT } from "./state.js";
2
+
3
+ // IM-style upward pagination: near the top of the thread, fetch the previous
4
+ // history page and prepend it without moving the reader's viewport.
5
+ export function initHistoryLoader(app) {
6
+ const $ = app.$;
7
+ let loading = false;
8
+ const spinner = document.createElement("li");
9
+ spinner.className = "history-loading";
10
+ spinner.setAttribute("role", "status");
11
+ const wheel = document.createElement("span");
12
+ wheel.className = "history-spinner";
13
+ wheel.setAttribute("aria-hidden", "true");
14
+ const label = document.createElement("span");
15
+ label.dataset.i18n = "loadingHistory";
16
+ label.textContent = app.t("loadingHistory");
17
+ spinner.append(wheel, label);
18
+
19
+ app.loadOlderHistory = async () => {
20
+ const room = app.state.room, entry = room && app.state.rooms.get(room.id);
21
+ const thread = $("#thread"), list = $("#msgList");
22
+ if (!room || !entry || loading || entry.historyComplete || entry.historyBeforeSeq == null) return;
23
+ loading = true;
24
+ const generation = app.state.pollGeneration;
25
+ list.prepend(spinner);
26
+ try {
27
+ const page = await app.api(`/rooms/${encodeURIComponent(room.id)}/history?beforeSeq=${entry.historyBeforeSeq}&limit=100`);
28
+ if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
29
+ const known = new Set(entry.room.messages.map((message) => message.id));
30
+ const older = (page.messages || []).filter((message) => !known.has(message.id));
31
+ entry.historyComplete = !page.hasMore;
32
+ spinner.remove();
33
+ if (older.length) {
34
+ const tailSep = list.firstElementChild;
35
+ const fragment = document.createDocumentFragment();
36
+ let day = null;
37
+ for (const message of older) {
38
+ const messageDay = new Date(message.createdAt).toDateString();
39
+ if (messageDay !== day) {
40
+ const separator = document.createElement("li");
41
+ separator.className = "day-sep";
42
+ separator.dataset.day = messageDay;
43
+ separator.textContent = app.dayText(message.createdAt);
44
+ fragment.append(separator);
45
+ day = messageDay;
46
+ }
47
+ const row = app.renderMessage(message, false);
48
+ row.dataset.day = messageDay;
49
+ fragment.append(row);
50
+ }
51
+ // Baseline after the fetch: polls may have grown the tail meanwhile.
52
+ const beforeHeight = thread.scrollHeight, beforeTop = thread.scrollTop;
53
+ list.prepend(fragment);
54
+ if (tailSep?.classList.contains("day-sep") && new Date(older.at(-1).createdAt).toDateString() === tailSep.dataset.day) tailSep.remove();
55
+ entry.room.messages = [...older, ...entry.room.messages].sort((left, right) => left.createdAt - right.createdAt);
56
+ if (entry.room.messages.length > LOADED_MESSAGE_LIMIT) entry.room.messages.splice(0, entry.room.messages.length - LOADED_MESSAGE_LIMIT);
57
+ thread.scrollTop = beforeTop + (thread.scrollHeight - beforeHeight);
58
+ app.cacheRoomSoon?.(room.id);
59
+ app.queueReceiptRefresh?.();
60
+ }
61
+ entry.historyBeforeSeq = page.hasMore ? (page.nextBeforeSeq ?? entry.room.messages[0]?.seq ?? null) : null;
62
+ } catch { /* the next scroll toward the top retries */ }
63
+ finally { loading = false; spinner.remove(); }
64
+ };
65
+ }
@@ -10,6 +10,7 @@ import { initAnnouncements } from "./announcements.js";
10
10
  import { initAdmin } from "./admin.js";
11
11
  import { initAttachments } from "./attachments.js";
12
12
  import { initReplies } from "./replies.js";
13
+ import { initHistoryLoader } from "./history-loader.js";
13
14
  import { initReminders } from "./reminders.js";
14
15
 
15
16
  initMentions(app);
@@ -18,6 +19,7 @@ initAttachments(app);
18
19
  initReceipts(app);
19
20
  initMembers(app);
20
21
  initRooms(app);
22
+ initHistoryLoader(app);
21
23
  initQuestions(app);
22
24
  initReplies(app);
23
25
  initEvents(app);
@@ -273,20 +273,27 @@ function replaceMentionTokens(fragment, mentions, app) {
273
273
  }
274
274
  }
275
275
 
276
- export async function copyTextToClipboard(text) {
276
+ export async function copyTextToClipboard(text, mentionSource = false) {
277
+ // The HTML marker lets a later paste rebuild mention chips; unmarked external text stays literal.
278
+ const html = mentionSource ? `<div data-chatroom-mentions>${String(text).replace(/[&<>"]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[char])}</div>` : "";
277
279
  try {
280
+ if (html && navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
281
+ await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([text], { type: "text/plain" }), "text/html": new Blob([html], { type: "text/html" }) })]);
282
+ return true;
283
+ }
278
284
  if (navigator.clipboard?.writeText) {
279
285
  await navigator.clipboard.writeText(text);
280
286
  return true;
281
287
  }
282
288
  } catch { /* Use the legacy clipboard command when permission is unavailable. */ }
283
- const field = document.createElement("textarea"), selection = getSelection(), active = document.activeElement;
289
+ const field = document.createElement(html ? "div" : "textarea"), selection = getSelection(), active = document.activeElement;
284
290
  const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) : [];
285
- field.value = text;
291
+ if (html) { field.contentEditable = "true"; field.innerHTML = html; } else field.value = text;
286
292
  field.setAttribute("readonly", "");
287
293
  field.style.cssText = "position:fixed;left:-9999px;top:0";
288
294
  document.body.append(field);
289
- field.select();
295
+ if (html && selection) { const range = document.createRange(); range.selectNodeContents(field); selection.removeAllRanges(); selection.addRange(range); }
296
+ else if (!html) field.select();
290
297
  let copied = false;
291
298
  try { copied = document.execCommand("copy"); } catch { /* Clipboard access may be disabled. */ }
292
299
  field.remove();
@@ -0,0 +1,51 @@
1
+ // IndexedDB snapshots of joined rooms so a reopen renders from local history
2
+ // and only the delta comes from the server. Every failure degrades to the
3
+ // normal remote fetch; the cache never blocks the chat.
4
+ const DB_NAME = "chat-room-history";
5
+ const STORE = "rooms";
6
+ const CACHE_LIMIT = 2000;
7
+
8
+ let opening;
9
+ function open() {
10
+ opening ??= new Promise((resolve, reject) => {
11
+ if (!globalThis.indexedDB) { reject(new Error("IndexedDB unavailable")); return; }
12
+ const request = indexedDB.open(DB_NAME, 1);
13
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: "roomId" });
14
+ request.onsuccess = () => resolve(request.result);
15
+ request.onerror = () => reject(request.error);
16
+ request.onblocked = () => reject(new Error("IndexedDB blocked"));
17
+ });
18
+ return opening;
19
+ }
20
+
21
+ async function withStore(mode, run) {
22
+ const db = await open();
23
+ return new Promise((resolve, reject) => {
24
+ const transaction = db.transaction(STORE, mode);
25
+ const request = run(transaction.objectStore(STORE));
26
+ transaction.oncomplete = () => resolve(request?.result);
27
+ transaction.onerror = () => reject(transaction.error);
28
+ transaction.onabort = () => reject(transaction.error);
29
+ });
30
+ }
31
+
32
+ export async function loadCachedRooms() {
33
+ try { return (await withStore("readonly", (store) => store.getAll())) || []; }
34
+ catch { return []; }
35
+ }
36
+
37
+ export async function deleteCachedRoom(roomId) {
38
+ try { await withStore("readwrite", (store) => store.delete(roomId)); } catch { /* optional cache */ }
39
+ }
40
+
41
+ const pending = new Map();
42
+ export function cacheRoomSoon(app, roomId) {
43
+ if (pending.has(roomId)) return;
44
+ pending.set(roomId, setTimeout(() => {
45
+ pending.delete(roomId);
46
+ const entry = app.state.rooms.get(roomId);
47
+ if (!entry?.room) return;
48
+ const snapshot = { ...entry.room, messages: entry.room.messages.slice(-CACHE_LIMIT) };
49
+ void withStore("readwrite", (store) => store.put({ roomId, name: entry.name, savedAt: Date.now(), room: snapshot })).catch(() => {});
50
+ }, 800));
51
+ }
@@ -1,4 +1,4 @@
1
- import { createRandomId, LS } from "./state.js";
1
+ import { createRandomId, LS, LOADED_MESSAGE_LIMIT } from "./state.js";
2
2
  import { renderMarkdown } from "./markdown.js";
3
3
  import { hasMessageSelection, pruneMessageRows, trimMessages } from "./message-window.js";
4
4
  import { formatSystemMessage, setRoomPreview } from "./system-messages.js";
@@ -107,7 +107,8 @@ export function initMessages(app) {
107
107
  };
108
108
  app.updateJump = () => {
109
109
  const thread = $("#thread");
110
- const away = thread.scrollHeight - thread.scrollTop - thread.clientHeight > 160;
110
+ // Match the distance that already counts as read, so unread never hides the button.
111
+ const away = thread.scrollHeight - thread.scrollTop - thread.clientHeight > 80;
111
112
  $("#btnJump").hidden = !away;
112
113
  };
113
114
  app.updateBadge = () => {
@@ -116,20 +117,42 @@ export function initMessages(app) {
116
117
  badge.hidden = app.state.unread === 0;
117
118
  app.updateTitle();
118
119
  };
120
+ // Stop at the first message that failed to render: a later readable message
121
+ // must not push the watermark past one we still cannot show.
122
+ const readTimestamp = (room, entry) => {
123
+ let timestamp = entry.readTs;
124
+ for (const message of room.messages) {
125
+ if (app.failedRenderIds.has(message.id)) break;
126
+ timestamp = Math.max(timestamp, message.createdAt);
127
+ }
128
+ return timestamp;
129
+ };
130
+ // Persist the watermark with a keepalive request so it survives the tab
131
+ // closing before the normal async read acknowledgement completes.
132
+ app.flushReadOnHide = () => {
133
+ const room = app.state.room, entry = room && app.state.rooms.get(room.id);
134
+ const thread = $("#thread");
135
+ if (!room || !entry || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
136
+ const timestamp = readTimestamp(room, entry);
137
+ if (timestamp <= entry.readTs) return;
138
+ void app.api("/read", { method: "POST", keepalive: true, body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }) }).catch(() => {});
139
+ };
119
140
  app.markActiveRoomRead = async (interactive = false) => {
120
141
  const room = app.state.room, entry = room && app.state.rooms.get(room.id);
121
142
  const generation = app.state.pollGeneration;
122
143
  const thread = $("#thread");
123
144
  if (!room || !entry || document.hidden || (!interactive && !document.hasFocus())
124
145
  || thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
125
- if (app.state.readAnchorGuard?.roomId === room.id) {
126
- if (!interactive && performance.now() > app.state.userScrollIntentUntil) return;
127
- app.state.readAnchorGuard = null;
128
- }
129
- const timestamp = room.messages.reduce((latest, message) => Math.max(latest, message.createdAt), entry.readTs);
146
+ // Reaching this point means the room is within the read distance of the bottom,
147
+ // so the restore guard has done its job even without a user scroll.
148
+ if (app.state.readAnchorGuard?.roomId === room.id) app.state.readAnchorGuard = null;
149
+ const timestamp = readTimestamp(room, entry);
130
150
  const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
131
151
  let advanced = false;
132
- if (timestamp > entry.readTs) {
152
+ app.state.readRequests ||= new Set();
153
+ // One acknowledgement at a time; scrolling fires this on every frame near the bottom.
154
+ if (timestamp > entry.readTs && !app.state.readRequests.has(room.id)) {
155
+ app.state.readRequests.add(room.id);
133
156
  try {
134
157
  await app.api("/read", {
135
158
  method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
@@ -140,24 +163,17 @@ export function initMessages(app) {
140
163
  entry.unreadOverflow = false;
141
164
  advanced = true;
142
165
  } catch { return; /* The next active poll will retry the read watermark. */ }
166
+ finally { app.state.readRequests.delete(room.id); }
143
167
  }
144
- // Unanswered questions stay unread until answered.
168
+ // Unread means "not seen": the read watermark clears everything it covers,
169
+ // including questions. Pending answers are surfaced by the Questions panel.
145
170
  const known = new Map(room.messages.map((message) => [message.id, message]));
146
- const answered = new Set(room.messages.filter((message) => message.answerToMessageID).map((message) => message.answerToMessageID));
147
- const listed = app.unansweredQuestionIds?.();
148
- const open = (message) => {
149
- if (!message.isQuestion || message.answeredByMessageID) return false;
150
- // A question outside the message window is judged by the server list.
151
- return known.has(message.id) ? !answered.has(message.id) : !listed || listed.has(message.id);
152
- };
153
171
  for (const [id, message] of entry.unreadIds) {
154
172
  const current = known.get(id) || message;
155
- if (current.createdAt <= entry.readTs && !open(current)) entry.unreadIds.delete(id);
173
+ // Clear what the watermark covers, plus own messages the watcher misread.
174
+ if (current.createdAt <= entry.readTs || !isUnreadMessage(current, app, room)) entry.unreadIds.delete(id);
156
175
  else if (known.has(id)) entry.unreadIds.set(id, current);
157
176
  }
158
- for (const message of room.messages) {
159
- if (open(message) && !isOwnMessage(message, app, room)) entry.unreadIds.set(message.id, message);
160
- }
161
177
  app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
162
178
  if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
163
179
  app.updateBadge();
@@ -318,11 +334,11 @@ export function initMessages(app) {
318
334
 
319
335
  app.send = async () => {
320
336
  const input = $("#msgInput"), room = app.state.room, replyTarget = room && app.replyTargetFor?.(room.id);
321
- const isQuestion = !replyTarget && Boolean(app.isQuestionSending?.());
322
337
  if (!room || app.state.sendingRooms?.has(room.id)) return;
323
338
  const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
324
339
  if (!message.ready) return;
325
340
  const text = message.text;
341
+ const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
326
342
  const revision = app.state.draftRevision.get(room.id) || 0;
327
343
  app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
328
344
  app.closeMention();
@@ -337,7 +353,7 @@ export function initMessages(app) {
337
353
  let updated;
338
354
  if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
339
355
  else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
340
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, isQuestion, ...(!isQuestion && replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
356
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
341
357
  });
342
358
  app.completeAttachments?.(room.id, message.ids);
343
359
  if (app.state.room?.id !== room.id) return;
@@ -348,7 +364,8 @@ export function initMessages(app) {
348
364
  if (entry) {
349
365
  const merged = new Map([...entry.room.messages, ...updated.messages].map((item) => [item.id, { ...item, roomId: updated.id }]));
350
366
  const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
351
- if (messages.length > 500) messages.splice(0, messages.length - 500);
367
+ if (messages.length > LOADED_MESSAGE_LIMIT) messages.splice(0, messages.length - LOADED_MESSAGE_LIMIT);
368
+ app.cacheRoomSoon?.(room.id);
352
369
  current = { ...updated, messages };
353
370
  }
354
371
  app.state.room = current;
@@ -358,7 +375,8 @@ export function initMessages(app) {
358
375
  if (latest) setRoomPreview(entry, latest);
359
376
  }
360
377
  app.renderMessages(true);
361
- $("#thread").scrollTop = $("#thread").scrollHeight;
378
+ // Reading history and sending must not teleport to the newest message or mark it read.
379
+ if (followedBottom) $("#thread").scrollTop = $("#thread").scrollHeight;
362
380
  app.renderMembers();
363
381
  app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
364
382
  app.updateBadge();
@@ -367,12 +385,19 @@ export function initMessages(app) {
367
385
  app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
368
386
  } catch (error) {
369
387
  const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
370
- const failures = app.state.failedMessages.get(room.id) || [];
371
- app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, isQuestion, ...(!isQuestion && replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
388
+ // Someone answered the question first; retrying the answer can never succeed,
389
+ // so keep the text as a draft instead of a failed message.
390
+ const staleReply = Boolean(replyTarget?.isQuestion) && (error.status === 409 || error.status === 404);
391
+ if (staleReply) app.saveDraft(room.id, text);
392
+ else {
393
+ const failures = app.state.failedMessages.get(room.id) || [];
394
+ app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
395
+ app.renderFailedMessages();
396
+ }
372
397
  app.completeAttachments?.(room.id, message.ids);
373
- app.renderFailedMessages();
374
398
  if (app.state.room?.id !== room.id) return;
375
- if (unchanged) app.clearDraft(room.id);
399
+ if (unchanged && !staleReply) app.clearDraft(room.id);
400
+ if (staleReply) input.draftValue = text;
376
401
  app.autoGrow(input);
377
402
  app.updateSendState();
378
403
  app.updateDraftCount();
@@ -437,13 +462,18 @@ export function initMessages(app) {
437
462
  if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
438
463
  added++;
439
464
  }
440
- if (entry && item.createdAt > entry.readTs && !isOwnMessage(item, app) && !entry.unreadIds.has(item.id)) {
465
+ if (entry && item.createdAt > entry.readTs && isUnreadMessage(item, app) && !entry.unreadIds.has(item.id)) {
441
466
  entry.unreadIds.set(item.id, item); unreadChanged = true;
442
467
  }
468
+ // An answer to a question clears that question even before the room is read.
469
+ if (entry && item.answerToMessageID && entry.unreadIds.get(item.answerToMessageID)?.isQuestion) {
470
+ entry.unreadIds.delete(item.answerToMessageID); unreadChanged = true;
471
+ }
443
472
  }
444
473
  if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
445
474
  if (entry) entry.unreadOverflow = Boolean(data.hasMore);
446
- if (messages.length > 500) { const anchorId = app.state.positions.get(roomId)?.messageId, anchor = anchorId && messages.find((item) => item.id === anchorId); messages.splice(0, messages.length - 500); if (anchor && !messages.includes(anchor)) messages.unshift(anchor); }
475
+ if (messages.length > LOADED_MESSAGE_LIMIT) { const anchorId = app.state.positions.get(roomId)?.messageId, anchor = anchorId && messages.find((item) => item.id === anchorId); messages.splice(0, messages.length - LOADED_MESSAGE_LIMIT); if (anchor && !messages.includes(anchor)) messages.unshift(anchor); }
476
+ app.cacheRoomSoon?.(roomId);
447
477
  const rendered = app.renderMessages(true);
448
478
  if (sawSystem) {
449
479
  await app.refreshRoomMeta(roomId, generation);
@@ -500,7 +530,7 @@ export function initMessages(app) {
500
530
  const index = current.findIndex((item) => item.createdAt > message.createdAt);
501
531
  current.splice(index < 0 ? current.length : index, 0, message);
502
532
  }
503
- if (current.length > 500) current.splice(0, current.length - 500);
533
+ if (current.length > LOADED_MESSAGE_LIMIT) current.splice(0, current.length - LOADED_MESSAGE_LIMIT);
504
534
  const result = app.rerenderMessages();
505
535
  if (result.skipped === 0) void app.markActiveRoomRead();
506
536
  } catch { /* Try again during the next reconciliation. */ }
@@ -519,15 +549,21 @@ export function initMessages(app) {
519
549
 
520
550
  function mergeRoom(current, updated) {
521
551
  const messages = new Map([...(current?.messages || []), ...updated.messages].map((message) => [message.id, message]));
522
- return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
552
+ return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-LOADED_MESSAGE_LIMIT) };
523
553
  }
524
554
 
525
555
  }
526
556
 
557
+ // Unread means a person said something you have not seen; join/leave notices are not a badge.
558
+ export function isUnreadMessage(message, app, room = app.state.room, myName = app.state.myName) {
559
+ return message.senderId !== "system" && !isOwnMessage(message, app, room, myName);
560
+ }
561
+
527
562
  export function isOwnMessage(message, app, room = app.state.room, myName = app.state.myName) {
528
563
  const direct = room.kind === "direct";
529
564
  const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
530
565
  return direct ? message.senderId === LS.sessionID
531
566
  : message.senderSessionID ? message.senderSessionID === LS.sessionID
532
- : message.senderId === myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
567
+ // Without a recorded sender session, fall back to the name unless a namesake is known.
568
+ : message.senderId === myName && (!sameName || sameName.every((member) => member.sessionID === LS.sessionID));
533
569
  }
@@ -1,19 +1,15 @@
1
- import { LS } from "./state.js";
1
+ import { LS, LOADED_MESSAGE_LIMIT } from "./state.js";
2
2
  import { autoMentionDraft, installEditor } from "./editor.js";
3
3
  import { copyTextToClipboard, renderMarkdown } from "./markdown.js";
4
4
 
5
5
  export function initQuestions(app) {
6
- const $ = app.$, pending = new Map(), selected = new Map(), drafts = new Map(), questionMode = new Map(), submitting = new Set(), unsupported = new Set();
6
+ const $ = app.$, pending = new Map(), selected = new Map(), drafts = new Map(), submitting = new Set(), unsupported = new Set();
7
7
  let request = 0;
8
8
  const panel = $("#questionPanel"), trigger = $("#btnQuestions"), list = $("#questionList"), status = $("#questionStatus");
9
- app.isQuestionSending = () => Boolean(questionMode.get(app.state.room?.id));
10
9
  // Undefined until the server list for this room has loaded; callers must not
11
10
  // treat that as "no open questions".
12
11
  app.unansweredQuestionIds = (roomId = app.state.room?.id) => pending.has(roomId)
13
12
  ? new Set((pending.get(roomId) || []).map((item) => item.id)) : undefined;
14
- $("#questionToggle").addEventListener("change", (event) => {
15
- if (app.state.room) questionMode.set(app.state.room.id, event.target.checked);
16
- });
17
13
 
18
14
  const renderMessage = app.renderMessage;
19
15
  app.renderMessage = (message, live) => {
@@ -31,6 +27,14 @@ export function initQuestions(app) {
31
27
 
32
28
  function render(roomId) {
33
29
  const items = pending.get(roomId) || [];
30
+ const entry = app.state.rooms.get(roomId);
31
+ // Keep the room's question-mark badge in sync with the loaded question list.
32
+ if (entry && pending.has(roomId) && Number(entry.room.openQuestions) !== items.length) {
33
+ entry.room.openQuestions = items.length;
34
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
35
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
36
+ if (app.state.room?.id === roomId) app.renderHead();
37
+ }
34
38
  const active = app.state.room?.id === roomId;
35
39
  if (active) {
36
40
  const signature = `${roomId}\0${app.locale}\0${selected.get(roomId) || ""}\0${items.map((question) => `${question.id}\0${question.text}`).join("\u0001")}`;
@@ -77,7 +81,7 @@ export function initQuestions(app) {
77
81
  copy.type = "button"; copy.className = "btn ghost small question-copy"; copy.textContent = app.t("copyQuestion");
78
82
  feedback.className = "question-copy-feedback"; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite");
79
83
  copy.addEventListener("click", async () => {
80
- feedback.dataset.copyState = await copyTextToClipboard(question.text) ? "questionCopied" : "questionCopyFailed";
84
+ feedback.dataset.copyState = await copyTextToClipboard(question.text, true) ? "questionCopied" : "questionCopyFailed";
81
85
  feedback.textContent = app.t(feedback.dataset.copyState);
82
86
  });
83
87
  form.className = "question-reply-form";
@@ -231,7 +235,7 @@ export function initQuestions(app) {
231
235
  }
232
236
  if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
233
237
  entry.room.messages.push({ ...result.answer, roomId }); entry.room.messages.sort((a, b) => a.createdAt - b.createdAt);
234
- if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
238
+ if (entry.room.messages.length > LOADED_MESSAGE_LIMIT) entry.room.messages.splice(0, entry.room.messages.length - LOADED_MESSAGE_LIMIT);
235
239
  if (app.state.room?.id === roomId) app.renderMessages(true);
236
240
  }
237
241
  pending.set(roomId, (pending.get(roomId) || []).filter((item) => item.id !== (result.questionID || questionId)));
@@ -275,7 +279,6 @@ export function initQuestions(app) {
275
279
  const activateRoom = app.activateRoom;
276
280
  app.activateRoom = (roomId, preserveRoomListGeneration = false) => {
277
281
  activateRoom(roomId, preserveRoomListGeneration);
278
- $("#questionToggle").checked = Boolean(questionMode.get(roomId));
279
282
  void load(roomId);
280
283
  };
281
284
  const applyLocale = app.applyLocale;
@@ -29,7 +29,7 @@ export function initReminders(app) {
29
29
  status("");
30
30
  for (const reminder of reminders) {
31
31
  const row = document.createElement("li"), text = document.createElement("p"), detail = document.createElement("p");
32
- text.textContent = reminder.text; detail.className = "hint";
32
+ text.textContent = String(reminder.text).replace(/<at>([\s\S]*?)<\/at>/g, "$1"); detail.className = "hint";
33
33
  const timezone = reminder.schedule.timezone;
34
34
  const schedule = reminder.schedule.type === "once" ? formatTime(reminder.schedule.at, timezone) : `${reminder.schedule.expression} · ${timezone}`;
35
35
  const next = reminder.schedule.type === "cron" && reminder.nextRunAt ? ` · ${app.t("reminderNext", { time: formatTime(reminder.nextRunAt, timezone) })}` : "";
@@ -13,9 +13,6 @@ export function initReplies(app) {
13
13
  app.clearReplyTarget = (roomId) => app.setReplyTarget(roomId, null);
14
14
  app.renderReplyPreview = () => {
15
15
  const roomId = app.state.room?.id, target = roomId && targets.get(roomId), box = $("#replyPreview");
16
- const questionToggle = $("#questionToggle");
17
- questionToggle.disabled = Boolean(target);
18
- if (target && questionToggle.checked) { questionToggle.checked = false; questionToggle.dispatchEvent(new Event("change")); }
19
16
  box.hidden = !target;
20
17
  if (!target) return;
21
18
  $("#replyPreviewName").textContent = senderName(target, app);
@@ -69,7 +66,6 @@ function selectReply(message, app) {
69
66
  replaceEditorRange(input, 0, 0, prefix); input.setCaret(prefix.length);
70
67
  input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
71
68
  }
72
- const toggle = app.$("#questionToggle"); toggle.checked = false; toggle.dispatchEvent(new Event("change"));
73
69
  app.setReplyTarget(roomId, target);
74
70
  input.focus({ preventScroll: true });
75
71
  }
@@ -129,15 +125,24 @@ async function jumpToOriginal(roomId, messageId, app) {
129
125
  original = (page.messages || []).find((item) => item.id === messageId);
130
126
  const merged = new Map([...room.messages, ...(page.messages || []).map((item) => ({ ...item, roomId }))].map((item) => [item.id, item]));
131
127
  room.messages = [...merged.values()].sort((left, right) => left.createdAt - right.createdAt);
128
+ // Keep the upward-pagination cursor aligned with what the jump loaded.
129
+ if (typeof room.messages[0]?.seq === "number") entry.historyBeforeSeq = room.messages[0].seq;
130
+ if (!page.hasMore) entry.historyComplete = true;
132
131
  if (original || !page.hasMore || !page.nextBeforeSeq || page.nextBeforeSeq === beforeSeq) break;
133
132
  beforeSeq = page.nextBeforeSeq;
134
133
  }
135
134
  } catch { return; }
136
135
  if (!original) return markUnavailable(messageId, roomId, app);
137
- app.state.positions.set(roomId, { messageId, offset: 0 }); app.savePosition(roomId, { messageId, offset: 0 });
136
+ app.state.positions.set(roomId, { messageId, offset: 0, atBottom: false }); app.savePosition(roomId, { messageId, offset: 0, atBottom: false });
138
137
  if (app.state.room?.id === roomId && app.state.navigationGeneration === generation) {
139
138
  app.state.room = app.state.rooms.get(roomId)?.room || room; app.rerenderMessages();
140
- document.querySelector(`[data-msg-id="${CSS.escape(messageId)}"]`)?.scrollIntoView({ block: "center" });
139
+ const row = document.querySelector(`[data-msg-id="${CSS.escape(messageId)}"]`), thread = app.$("#thread");
140
+ if (row && thread) {
141
+ // Land the message's top on the thread's top edge so the most context shows.
142
+ thread.scrollTop += row.getBoundingClientRect().top - (thread.getBoundingClientRect().top + thread.clientTop);
143
+ clearTimeout(row._jumpFlashTimer); row.classList.remove("jump-flash"); void row.offsetWidth; row.classList.add("jump-flash");
144
+ row._jumpFlashTimer = setTimeout(() => row.classList.remove("jump-flash"), 900);
145
+ }
141
146
  }
142
147
  const quote = document.querySelector(`[data-reply-target-id="${CSS.escape(messageId)}"]`);
143
148
  if (quote) quote.textContent = `${senderName(original, app)} · ${excerpt(original.text)}`;