@alexsun-top/opencode-chat-room 0.5.5 → 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.
@@ -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";
@@ -117,6 +117,26 @@ export function initMessages(app) {
117
117
  badge.hidden = app.state.unread === 0;
118
118
  app.updateTitle();
119
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
+ };
120
140
  app.markActiveRoomRead = async (interactive = false) => {
121
141
  const room = app.state.room, entry = room && app.state.rooms.get(room.id);
122
142
  const generation = app.state.pollGeneration;
@@ -126,13 +146,7 @@ export function initMessages(app) {
126
146
  // Reaching this point means the room is within the read distance of the bottom,
127
147
  // so the restore guard has done its job even without a user scroll.
128
148
  if (app.state.readAnchorGuard?.roomId === room.id) app.state.readAnchorGuard = null;
129
- // Stop at the first message that failed to render: a later readable message
130
- // must not push the watermark past one we still cannot show.
131
- let timestamp = entry.readTs;
132
- for (const message of room.messages) {
133
- if (app.failedRenderIds.has(message.id)) break;
134
- timestamp = Math.max(timestamp, message.createdAt);
135
- }
149
+ const timestamp = readTimestamp(room, entry);
136
150
  const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
137
151
  let advanced = false;
138
152
  app.state.readRequests ||= new Set();
@@ -151,24 +165,15 @@ export function initMessages(app) {
151
165
  } catch { return; /* The next active poll will retry the read watermark. */ }
152
166
  finally { app.state.readRequests.delete(room.id); }
153
167
  }
154
- // 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.
155
170
  const known = new Map(room.messages.map((message) => [message.id, message]));
156
- const answered = new Set(room.messages.filter((message) => message.answerToMessageID).map((message) => message.answerToMessageID));
157
- const listed = app.unansweredQuestionIds?.();
158
- const open = (message) => {
159
- if (!message.isQuestion || message.answeredByMessageID) return false;
160
- // A question outside the message window is judged by the server list.
161
- return known.has(message.id) ? !answered.has(message.id) : !listed || listed.has(message.id);
162
- };
163
171
  for (const [id, message] of entry.unreadIds) {
164
172
  const current = known.get(id) || message;
165
173
  // Clear what the watermark covers, plus own messages the watcher misread.
166
- if ((current.createdAt <= entry.readTs && !open(current)) || !isUnreadMessage(current, app, room)) entry.unreadIds.delete(id);
174
+ if (current.createdAt <= entry.readTs || !isUnreadMessage(current, app, room)) entry.unreadIds.delete(id);
167
175
  else if (known.has(id)) entry.unreadIds.set(id, current);
168
176
  }
169
- for (const message of room.messages) {
170
- if (open(message) && !isOwnMessage(message, app, room)) entry.unreadIds.set(message.id, message);
171
- }
172
177
  app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
173
178
  if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
174
179
  app.updateBadge();
@@ -359,7 +364,8 @@ export function initMessages(app) {
359
364
  if (entry) {
360
365
  const merged = new Map([...entry.room.messages, ...updated.messages].map((item) => [item.id, { ...item, roomId: updated.id }]));
361
366
  const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
362
- 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);
363
369
  current = { ...updated, messages };
364
370
  }
365
371
  app.state.room = current;
@@ -466,7 +472,8 @@ export function initMessages(app) {
466
472
  }
467
473
  if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
468
474
  if (entry) entry.unreadOverflow = Boolean(data.hasMore);
469
- 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);
470
477
  const rendered = app.renderMessages(true);
471
478
  if (sawSystem) {
472
479
  await app.refreshRoomMeta(roomId, generation);
@@ -523,7 +530,7 @@ export function initMessages(app) {
523
530
  const index = current.findIndex((item) => item.createdAt > message.createdAt);
524
531
  current.splice(index < 0 ? current.length : index, 0, message);
525
532
  }
526
- 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);
527
534
  const result = app.rerenderMessages();
528
535
  if (result.skipped === 0) void app.markActiveRoomRead();
529
536
  } catch { /* Try again during the next reconciliation. */ }
@@ -542,7 +549,7 @@ export function initMessages(app) {
542
549
 
543
550
  function mergeRoom(current, updated) {
544
551
  const messages = new Map([...(current?.messages || []), ...updated.messages].map((message) => [message.id, message]));
545
- 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) };
546
553
  }
547
554
 
548
555
  }
@@ -1,4 +1,4 @@
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
 
@@ -27,6 +27,14 @@ export function initQuestions(app) {
27
27
 
28
28
  function render(roomId) {
29
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
+ }
30
38
  const active = app.state.room?.id === roomId;
31
39
  if (active) {
32
40
  const signature = `${roomId}\0${app.locale}\0${selected.get(roomId) || ""}\0${items.map((question) => `${question.id}\0${question.text}`).join("\u0001")}`;
@@ -73,7 +81,7 @@ export function initQuestions(app) {
73
81
  copy.type = "button"; copy.className = "btn ghost small question-copy"; copy.textContent = app.t("copyQuestion");
74
82
  feedback.className = "question-copy-feedback"; feedback.setAttribute("role", "status"); feedback.setAttribute("aria-live", "polite");
75
83
  copy.addEventListener("click", async () => {
76
- feedback.dataset.copyState = await copyTextToClipboard(question.text) ? "questionCopied" : "questionCopyFailed";
84
+ feedback.dataset.copyState = await copyTextToClipboard(question.text, true) ? "questionCopied" : "questionCopyFailed";
77
85
  feedback.textContent = app.t(feedback.dataset.copyState);
78
86
  });
79
87
  form.className = "question-reply-form";
@@ -227,7 +235,7 @@ export function initQuestions(app) {
227
235
  }
228
236
  if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
229
237
  entry.room.messages.push({ ...result.answer, roomId }); entry.room.messages.sort((a, b) => a.createdAt - b.createdAt);
230
- 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);
231
239
  if (app.state.room?.id === roomId) app.renderMessages(true);
232
240
  }
233
241
  pending.set(roomId, (pending.get(roomId) || []).filter((item) => item.id !== (result.questionID || questionId)));
@@ -125,6 +125,9 @@ async function jumpToOriginal(roomId, messageId, app) {
125
125
  original = (page.messages || []).find((item) => item.id === messageId);
126
126
  const merged = new Map([...room.messages, ...(page.messages || []).map((item) => ({ ...item, roomId }))].map((item) => [item.id, item]));
127
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;
128
131
  if (original || !page.hasMore || !page.nextBeforeSeq || page.nextBeforeSeq === beforeSeq) break;
129
132
  beforeSeq = page.nextBeforeSeq;
130
133
  }
@@ -133,7 +136,13 @@ async function jumpToOriginal(roomId, messageId, app) {
133
136
  app.state.positions.set(roomId, { messageId, offset: 0, atBottom: false }); app.savePosition(roomId, { messageId, offset: 0, atBottom: false });
134
137
  if (app.state.room?.id === roomId && app.state.navigationGeneration === generation) {
135
138
  app.state.room = app.state.rooms.get(roomId)?.room || room; app.rerenderMessages();
136
- 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
+ }
137
146
  }
138
147
  const quote = document.querySelector(`[data-reply-target-id="${CSS.escape(messageId)}"]`);
139
148
  if (quote) quote.textContent = `${senderName(original, app)} · ${excerpt(original.text)}`;
@@ -1,4 +1,5 @@
1
1
  import { isUnreadMessage } from "./messages.js";
2
+ import { LOADED_MESSAGE_LIMIT } from "./state.js";
2
3
  import { setRoomPreview } from "./system-messages.js";
3
4
 
4
5
  export async function watchRoom(roomId, app) {
@@ -13,6 +14,7 @@ export async function watchRoom(roomId, app) {
13
14
  if (result.member !== true || !Array.isArray(result.items) || app.state.room?.id === roomId) return;
14
15
  const previousReceivedTs = entry.receivedTs || 0;
15
16
  const sawSystem = result.items.some((message) => message.senderId === "system");
17
+ const sawQuestion = result.items.some((message) => message.isQuestion || message.answerToMessageID);
16
18
  const before = new Set(entry.room.messages.map((message) => message.id));
17
19
  for (const message of result.items) {
18
20
  if (message.createdAt > entry.readTs && isUnreadMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
@@ -22,11 +24,12 @@ export async function watchRoom(roomId, app) {
22
24
  }
23
25
  entry.receivedTs = result.items.reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
24
26
  entry.unreadOverflow = Boolean(result.hasMore);
25
- if (sawSystem || result.hasMore) {
27
+ if (sawSystem || sawQuestion || result.hasMore) {
26
28
  const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
27
29
  if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
28
30
  entry.room.participants = latest.participants;
29
- entry.room.messages = [...new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message])).values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
31
+ entry.room.openQuestions = latest.openQuestions;
32
+ entry.room.messages = [...new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message])).values()].sort((a, b) => a.createdAt - b.createdAt).slice(-LOADED_MESSAGE_LIMIT);
30
33
  const newest = latest.messages.at(-1);
31
34
  if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
32
35
  // A full refresh pages past the inbox window; count what arrived since the last look.
@@ -36,7 +39,8 @@ export async function watchRoom(roomId, app) {
36
39
  }
37
40
  if (newest && Number.isSafeInteger(newest.createdAt)) entry.receivedTs = Math.max(entry.receivedTs, newest.createdAt);
38
41
  }
39
- if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
42
+ if (entry.room.messages.length > LOADED_MESSAGE_LIMIT) entry.room.messages.splice(0, entry.room.messages.length - LOADED_MESSAGE_LIMIT);
43
+ app.cacheRoomSoon?.(roomId);
40
44
  if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
41
45
  } catch (error) {
42
46
  if (error.status === 401) app.openChatSettings();
@@ -1,7 +1,8 @@
1
- import { LS } from "./state.js";
1
+ import { LS, LOADED_MESSAGE_LIMIT } from "./state.js";
2
2
  import { isUnreadMessage } from "./messages.js";
3
3
  import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
4
4
  import { watchRoom } from "./room-watcher.js";
5
+ import { cacheRoomSoon, deleteCachedRoom, loadCachedRooms } from "./message-cache.js";
5
6
 
6
7
  export function initRooms(app) {
7
8
  const $ = app.$;
@@ -9,6 +10,19 @@ export function initRooms(app) {
9
10
  let autoRefresh;
10
11
  const invalidateRoomList = () => { autoRefresh = undefined; return ++roomListGeneration; };
11
12
 
13
+ app.cacheRoomSoon = (roomId) => cacheRoomSoon(app, roomId);
14
+ // Render joined rooms from the local snapshot before the network round trip;
15
+ // the normal restore then validates membership and merges the server delta.
16
+ app.seedFromCache = async () => {
17
+ for (const record of await loadCachedRooms()) {
18
+ const room = record?.room;
19
+ if (!room?.id || app.state.rooms.has(room.id)) continue;
20
+ if (!app.state.joinedIds.has(room.id) && room.id !== LS.roomId) continue;
21
+ app.ensureJoinedRoom(room, record.name || app.state.roomNames.get(room.id) || LS.name || app.t("guest"));
22
+ }
23
+ if (!app.state.room && LS.roomId && app.state.rooms.has(LS.roomId)) app.activateRoom(LS.roomId);
24
+ };
25
+
12
26
  app.showJoin = (refresh = true, preserveRoomListGeneration = false) => {
13
27
  if (!preserveRoomListGeneration) invalidateRoomList();
14
28
  document.documentElement.classList.remove("session-restore");
@@ -33,6 +47,10 @@ export function initRooms(app) {
33
47
  $("#btnCopyId").setAttribute("aria-label", app.t("copyRoomId"));
34
48
  $("#railIdentity").textContent = app.state.myName;
35
49
  $("#profileAvatar").textContent = Array.from(app.state.myName.trim())[0]?.toLocaleUpperCase() || "?";
50
+ const description = app.state.room.description || "";
51
+ $("#roomDescription").textContent = description;
52
+ $("#roomDescription").hidden = !description;
53
+ $("#btnEditRoom").hidden = app.state.myName !== app.state.room.ownerId;
36
54
  app.updateTitle();
37
55
  };
38
56
 
@@ -54,13 +72,24 @@ export function initRooms(app) {
54
72
  const latest = room.messages.at(-1), savedReadTs = app.state.lastReadTs.get(room.id) ?? (typeof room.lastReadTs === "number" ? room.lastReadTs : undefined);
55
73
  if (savedReadTs !== undefined && !app.state.lastReadTs.has(room.id)) app.saveReadTs(room.id, savedReadTs);
56
74
  entry.readTs ||= savedReadTs || 0;
75
+ // A server page only carries the newest window; keep older history already
76
+ // loaded or restored from the local cache instead of dropping it.
77
+ if (existing) {
78
+ const merged = new Map([...existing.room.messages, ...room.messages].map((message) => [message.id, message]));
79
+ room = { ...room, messages: [...merged.values()].sort((left, right) => left.createdAt - right.createdAt).slice(-LOADED_MESSAGE_LIMIT) };
80
+ }
81
+ entry.historyComplete = Boolean(existing?.historyComplete) || room.hasMore === false;
82
+ entry.historyBeforeSeq = entry.historyComplete ? null : existing?.historyBeforeSeq ?? (typeof room.messages[0]?.seq === "number" ? room.messages[0].seq : null);
57
83
  entry.room = room;
58
84
  entry.name = name;
59
85
  // Only rebuild unread history when this browser already has a read watermark;
60
86
  // a never-opened room is not a burst of unread messages.
61
- if (!existing && savedReadTs !== undefined) for (const message of room.messages) {
62
- const unread = message.createdAt > entry.readTs || (message.isQuestion && !message.answeredByMessageID);
63
- if (unread && isUnreadMessage(message, app, room, name)) entry.unreadIds.set(message.id, message);
87
+ if (!existing && savedReadTs !== undefined) {
88
+ for (const message of room.messages) {
89
+ const unread = message.createdAt > entry.readTs;
90
+ if (unread && isUnreadMessage(message, app, room, name)) entry.unreadIds.set(message.id, message);
91
+ }
92
+ entry.unreadOverflow ||= Boolean(room.hasMore && entry.readTs < (room.messages[0]?.createdAt ?? Infinity));
64
93
  }
65
94
  entry.receivedTs ??= latest?.createdAt ?? 0;
66
95
  if (latest && (!existing || latest.createdAt >= entry.previewAt)) setRoomPreview(entry, latest);
@@ -70,6 +99,7 @@ export function initRooms(app) {
70
99
  app.saveJoinedIds();
71
100
  app.saveRoomNames();
72
101
  app.startRoomWatcher();
102
+ cacheRoomSoon(app, room.id);
73
103
  };
74
104
 
75
105
  app.activateRoom = (roomId, preserveRoomListGeneration = false) => {
@@ -207,6 +237,7 @@ export function initRooms(app) {
207
237
  $("#btnSend").disabled = true;
208
238
  }
209
239
  app.state.rooms.delete(roomId);
240
+ void deleteCachedRoom(roomId);
210
241
  app.state.memberSessions.delete(roomId);
211
242
  app.state.joinedIds.delete(roomId);
212
243
  app.state.roomNames.delete(roomId);
@@ -396,11 +427,15 @@ export function initRooms(app) {
396
427
  app.setText(status, entry ? "joined" : "joinAction");
397
428
  button.append(name, kind, meta, preview, status);
398
429
  const unread = entry && app.state.room?.id !== room.id ? (entry.unreadOverflow ? 100 : entry.unreadIds.size) : 0;
399
- if (unread) {
430
+ const openQuestions = Number(shownRoom.openQuestions) || 0;
431
+ // Same badge slot as unread: a pending question shows "?" instead of a count.
432
+ if (unread || openQuestions) {
400
433
  const badge = document.createElement("span");
401
- badge.className = "r-badge";
402
- badge.textContent = unread > 99 ? "99+" : String(unread);
403
- badge.setAttribute("aria-label", app.t("unreadMessages", { count: unread }));
434
+ badge.className = openQuestions ? "r-badge r-badge-question" : "r-badge";
435
+ badge.textContent = openQuestions ? "?" : (unread > 99 ? "99+" : String(unread));
436
+ const label = openQuestions ? app.t("openQuestions", { count: openQuestions }) : app.t("unreadMessages", { count: unread });
437
+ badge.title = label;
438
+ badge.setAttribute("aria-label", label);
404
439
  button.append(badge);
405
440
  }
406
441
  button.addEventListener("click", () => app.joinRoom(room.id, app.state.myName || $("#inName").value.trim() || app.t("guest")));
@@ -447,19 +482,23 @@ export function initRooms(app) {
447
482
  try {
448
483
  await app.api(`/rooms/${encodeURIComponent(room.id)}`, {
449
484
  method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }),
450
- headers: LS.adminToken ? { "X-Chat-Admin-Token": LS.adminToken } : {},
451
485
  });
452
486
  await app.removeJoinedRoom(room.id);
453
487
  app.clearDraft(room.id);
454
488
  app.clearPosition(room.id);
455
489
  app.saveFailedMessages(room.id, []);
456
- } catch (error) { app.showSendError(error.status === 403 && error.message.includes("operator token required") ? "adminRoomDeleteDenied" : "sendFailed", { message: error.message }); }
490
+ } catch (error) { app.showSendError("sendFailed", { message: error.message }); }
457
491
  };
458
492
 
459
493
  app.copyRoomId = async () => {
494
+ const button = $("#btnCopyId");
460
495
  try {
461
496
  await navigator.clipboard.writeText(app.state.room.id);
462
- app.flash($("#btnCopyId"), "copied");
497
+ // Swap a class so the ID span survives; flash() would overwrite the whole
498
+ // button and then restore it to "undefined" (the button has no data-i18n).
499
+ clearTimeout(button._copiedTimer);
500
+ button.classList.add("copied");
501
+ button._copiedTimer = setTimeout(() => button.classList.remove("copied"), 1200);
463
502
  } catch { app.showSendError("copyFailed", { id: app.state.room.id }); }
464
503
  };
465
504
 
@@ -489,7 +528,7 @@ function syncCachedRooms(rooms, app) {
489
528
  if (!fresh || fresh.joined === false) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId, reconcile: true }); continue; }
490
529
  if (app.state.room?.id === roomId) continue;
491
530
  const messages = new Map([...entry.room.messages, ...fresh.messages].map((message) => [message.id, message]));
492
- entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
531
+ entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-LOADED_MESSAGE_LIMIT) };
493
532
  const latest = entry.room.messages.at(-1);
494
533
  if (latest) setRoomPreview(entry, latest);
495
534
  }
@@ -1,3 +1,6 @@
1
+ // Upper bound on messages kept in memory per open room; older pages load on scroll.
2
+ export const LOADED_MESSAGE_LIMIT = 5000;
3
+
1
4
  export const app = {
2
5
  $: (selector) => document.querySelector(selector),
3
6
  state: {
@@ -132,7 +135,6 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
132
135
  get name() { return ensureIdentity().name; },
133
136
  set name(value) { ensureIdentity(); browserIdentity.name = String(value ?? "").slice(0, 64); writeSession("chat.name", browserIdentity.name || null); saveIdentity(); },
134
137
  get token() { return read("chat.token") || ""; }, set token(value) { write("chat.token", value || null); },
135
- get adminToken() { return readSession("chat.adminToken") || ""; }, set adminToken(value) { writeSession("chat.adminToken", value || null); },
136
138
  get locale() { return read("chat.locale") || "en"; }, set locale(value) { write("chat.locale", value || null); },
137
139
  get joinedRoomIds() {
138
140
  try {
@@ -190,13 +192,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
190
192
  const response = await apiResponse(url, options), blob = await response.blob();
191
193
  assertIdentity(); return blob;
192
194
  };
193
- const adminApi = async (url, options = {}) => {
194
- if (!url.startsWith("/admin/") || !auth.adminToken) throw new Error("Administration token is required");
195
- const response = await apiResponse(url, { ...options, headers: { ...options.headers, "X-Chat-Admin-Token": auth.adminToken } });
196
- const data = await response.json().catch(() => ({}));
197
- assertIdentity(); return data;
198
- };
199
- return { LS: auth, saveToken, api, apiBlob, adminApi };
195
+ return { LS: auth, saveToken, api, apiBlob };
200
196
  }
201
197
 
202
198
  const messages = {
@@ -211,7 +207,10 @@ const messages = {
211
207
  createRoom: "Create room", tokenOptional: "Access token (optional)", bearerToken: "Bearer token",
212
208
  tokenPlaceholder: "Enter if the server requires it", save: "Save",
213
209
  tokenHint: "If the server requires an access token (401), all requests will include it.",
214
- existingRooms: "Rooms", noRooms: "No rooms yet. Create one.", copyRoomId: "Copy room ID",
210
+ existingRooms: "Rooms", noRooms: "No rooms yet. Create one.", copyRoomId: "Copy room ID", loadingHistory: "Loading earlier messages",
211
+ editRoom: "Edit room", roomNameLabel: "Room name", roomDescriptionLabel: "Description", adminAgentLabel: "Administrator agent",
212
+ adminAgentHint: "The designated agent can inspect all rooms and their history with the admin tool. Leave empty for none.",
213
+ noAdminAgent: "None", roomNameRequired: "Room name is required", openQuestions: ({ count }) => `${count} unanswered question${count === 1 ? "" : "s"}`,
215
214
  newRoom: "Create a room",
216
215
  copyRoomIdTitle: ({ id }) => `Click to copy the full room ID: ${id}`, copied: "Copied",
217
216
  members: "Members", membersCount: ({ count }) => `Members (${count})`, noMembers: "No members yet.", profileMenu: "Your profile and settings",
@@ -286,7 +285,10 @@ const messages = {
286
285
  newRoomNamePlaceholder: "例如:周末电影夜", createRoom: "创建新房间", tokenOptional: "访问令牌(可选)",
287
286
  bearerToken: "Bearer Token", tokenPlaceholder: "服务器要求时填写", save: "保存",
288
287
  tokenHint: "若服务器设置了访问令牌(401),所有请求都会带上它。", existingRooms: "房间",
289
- noRooms: "还没有房间,创建一个吧。", copyRoomId: "复制房间 ID",
288
+ noRooms: "还没有房间,创建一个吧。", copyRoomId: "复制房间 ID", loadingHistory: "正在加载更早的消息",
289
+ editRoom: "编辑房间", roomNameLabel: "房间名称", roomDescriptionLabel: "描述", adminAgentLabel: "管理员 Agent",
290
+ adminAgentHint: "被指定的 Agent 可用 admin 工具查看所有房间及其历史。留空表示不指定。",
291
+ noAdminAgent: "不指定", roomNameRequired: "房间名称不能为空", openQuestions: ({ count }) => `${count} 个待回答的问题`,
290
292
  newRoom: "创建房间",
291
293
  copyRoomIdTitle: ({ id }) => `点击复制完整房间 ID:${id}`, copied: "已复制", members: "成员",
292
294
  membersCount: ({ count }) => `成员 ${count}`, noMembers: "暂无成员", settings: "设置", profileMenu: "个人资料和设置",
@@ -354,11 +356,10 @@ app.t = (key, values = {}) => {
354
356
  const text = typeof entry === "function" ? entry(values) : entry;
355
357
  return String(text).replace(/\{(\w+)\}/g, (_, name) => values[name] ?? "");
356
358
  };
357
- export const { LS, saveToken, api, apiBlob, adminApi } = createAuth(undefined, undefined, (key, values) => app.t(key, values));
359
+ export const { LS, saveToken, api, apiBlob } = createAuth(undefined, undefined, (key, values) => app.t(key, values));
358
360
  app.LS = LS;
359
361
  app.api = api;
360
362
  app.apiBlob = apiBlob;
361
- app.adminApi = adminApi;
362
363
  app.setToken = saveToken;
363
364
  app.locale = LS.locale === "zh-CN" ? "zh-CN" : "en";
364
365
  app.state.joinedIds = new Set(LS.joinedRoomIds);
@@ -14,6 +14,7 @@
14
14
  .rooms-drawer-trigger { display: none; }
15
15
  .room-drawer-backdrop { position: fixed; inset: 0; z-index: 49; border: 0; background: rgb(9 16 22 / .38); }
16
16
  .room-meta { margin: 4px 0 0; font-size: 11px; color: var(--ink-3); }
17
+ .room-description { margin: 4px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-2); white-space: pre-wrap; overflow-wrap: anywhere; }
17
18
  .mono { font-family: var(--font-mono); }
18
19
  .copy-id {
19
20
  appearance: none;
@@ -222,6 +223,12 @@
222
223
  }
223
224
  .msg-text::selection, .msg-text *::selection { color: var(--accent-ink); background: var(--accent); }
224
225
  .msg.own .msg-text { background: linear-gradient(145deg, color-mix(in srgb, var(--accent-soft) 86%, var(--surface)), var(--accent-soft)); border-color: color-mix(in srgb, var(--accent) 12%, transparent); border-bottom-left-radius: 16px; border-bottom-right-radius: 5px; }
226
+ .msg.jump-flash .msg-text { animation: jump-flash .4s ease-in-out 2; }
227
+ @keyframes jump-flash {
228
+ 0%, 100% { box-shadow: 0 1px 2px rgb(20 40 32 / .035); }
229
+ 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 55%, transparent); }
230
+ }
231
+ @media (prefers-reduced-motion: reduce) { .msg.jump-flash .msg-text { animation-duration: .8s; animation-iteration-count: 1; } }
225
232
  .msg-content { position: relative; display: flex; align-items: flex-end; gap: 6px; width: 100%; max-width: 100%; }
226
233
  .msg.own .msg-content { flex-direction: row-reverse; }
227
234
  .message-copy {
@@ -418,6 +425,11 @@
418
425
  }
419
426
  .day-sep::before, .day-sep::after { content: ""; flex: 1; height: 1px; background: var(--line); }
420
427
 
428
+ .history-loading { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 0 4px; font-size: 12px; color: var(--ink-3); }
429
+ .history-spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--line); border-top-color: var(--accent); animation: history-spin .8s linear infinite; }
430
+ @keyframes history-spin { to { transform: rotate(360deg); } }
431
+ @media (prefers-reduced-motion: reduce) { .history-spinner { animation-duration: 1.6s; } }
432
+
421
433
  .gap { padding: 6px 0 2px; text-align: center; font-size: 12px; color: var(--ink-3); }
422
434
 
423
435
  .chat-empty { padding: 64px 0 44px; text-align: center; font-family: var(--font-display); font-size: 16px; color: var(--ink-3); }
@@ -52,6 +52,7 @@
52
52
  .r-status { color: var(--accent); font-size: 10px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
53
53
  .r-preview { overflow: hidden; color: var(--ink-3); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
54
54
  .r-badge { position: absolute; top: 8px; right: 9px; display: grid; place-items: center; min-width: 20px; height: 20px; padding: 0 5px; border-radius: 999px; background: var(--accent); color: var(--accent-ink); font-size: 10px; font-weight: 700; }
55
+ .r-badge-question { background: var(--warning); color: var(--warning-ink); font-size: 12px; }
55
56
  .rail-foot { display: flex; align-items: center; gap: 8px; margin-top: auto; padding: 12px 4px 0; border-top: 1px solid color-mix(in srgb, var(--line) 80%, transparent); font-size: 12px; color: var(--ink-3); }
56
57
  .rail-foot .anchor { width: 100%; }
57
58
  .user-menu-trigger { display: flex; align-items: center; gap: 10px; width: 100%; min-width: 0; padding: 7px; border: 1px solid transparent; border-radius: 12px; color: var(--ink); background: transparent; font: inherit; text-align: left; cursor: pointer; transition: border-color .16s, background .16s, box-shadow .16s; }