@alexsun-top/opencode-chat-room 0.5.3 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/README.md +13 -1
- package/README.zh-CN.md +13 -1
- package/docs/administrator-rooms.md +6 -8
- package/package.json +2 -1
- package/server/admin-auth.ts +4 -2
- package/server/assets/base.css +5 -1
- package/server/assets/chat/admin.js +4 -9
- package/server/assets/chat/announcements.js +17 -1
- package/server/assets/chat/attachments.js +4 -1
- package/server/assets/chat/editor.js +15 -2
- package/server/assets/chat/events.js +25 -7
- package/server/assets/chat/markdown.js +31 -11
- package/server/assets/chat/mentions.js +3 -1
- package/server/assets/chat/messages.js +96 -32
- package/server/assets/chat/questions.js +12 -6
- package/server/assets/chat/reminders.js +4 -4
- package/server/assets/chat/replies.js +1 -5
- package/server/assets/chat/room-watcher.js +12 -4
- package/server/assets/chat/rooms.js +17 -6
- package/server/assets/chat/state.js +8 -7
- package/server/assets/chat/system-messages.js +2 -1
- package/server/assets/conversation.css +1 -3
- package/server/chat-server.ts +39 -38
- package/server/chat.html +2 -3
- package/server/json-body.ts +8 -0
- package/server/member-routes.ts +9 -11
- package/server/wake.ts +11 -2
- package/skills/chatroom/SKILL.md +5 -2
- package/src/admin-client.ts +3 -3
- package/src/agent-receipts.ts +3 -3
- package/src/center-inbox.ts +2 -2
- package/src/plugin-notifications.ts +6 -3
- package/src/resources.ts +4 -1
- package/src/sqlite-state.ts +56 -5
- package/src/store.ts +11 -4
- package/src/v2-plugin.ts +17 -0
- package/src/supervision-inbox.ts +0 -50
|
@@ -11,6 +11,7 @@ export function initMessages(app) {
|
|
|
11
11
|
|
|
12
12
|
app.autoGrow = (textarea) => {
|
|
13
13
|
const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
14
|
+
const scrollTop = textarea.scrollTop;
|
|
14
15
|
textarea.style.overflowY = "hidden";
|
|
15
16
|
const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
|
|
16
17
|
const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
|
|
@@ -25,6 +26,8 @@ export function initMessages(app) {
|
|
|
25
26
|
const overflow = textarea.scrollHeight > limit + 1;
|
|
26
27
|
textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
|
|
27
28
|
textarea.style.overflowY = overflow ? "auto" : "hidden";
|
|
29
|
+
// Collapsing the height to measure content resets scrollTop; keep the caret view where it was.
|
|
30
|
+
if (overflow) textarea.scrollTop = scrollTop;
|
|
28
31
|
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
29
32
|
};
|
|
30
33
|
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
@@ -100,11 +103,12 @@ export function initMessages(app) {
|
|
|
100
103
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
101
104
|
app.updateBadge();
|
|
102
105
|
app.updateJump();
|
|
103
|
-
void app.markActiveRoomRead();
|
|
106
|
+
void app.markActiveRoomRead(true);
|
|
104
107
|
};
|
|
105
108
|
app.updateJump = () => {
|
|
106
109
|
const thread = $("#thread");
|
|
107
|
-
|
|
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;
|
|
108
112
|
$("#btnJump").hidden = !away;
|
|
109
113
|
};
|
|
110
114
|
app.updateBadge = () => {
|
|
@@ -113,33 +117,65 @@ export function initMessages(app) {
|
|
|
113
117
|
badge.hidden = app.state.unread === 0;
|
|
114
118
|
app.updateTitle();
|
|
115
119
|
};
|
|
116
|
-
app.markActiveRoomRead = async () => {
|
|
120
|
+
app.markActiveRoomRead = async (interactive = false) => {
|
|
117
121
|
const room = app.state.room, entry = room && app.state.rooms.get(room.id);
|
|
118
122
|
const generation = app.state.pollGeneration;
|
|
119
123
|
const thread = $("#thread");
|
|
120
|
-
if (!room || !entry || document.hidden || !document.hasFocus()
|
|
124
|
+
if (!room || !entry || document.hidden || (!interactive && !document.hasFocus())
|
|
121
125
|
|| thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
126
|
+
// Reaching this point means the room is within the read distance of the bottom,
|
|
127
|
+
// so the restore guard has done its job even without a user scroll.
|
|
128
|
+
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);
|
|
125
135
|
}
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
136
|
+
const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
|
|
137
|
+
let advanced = false;
|
|
138
|
+
app.state.readRequests ||= new Set();
|
|
139
|
+
// One acknowledgement at a time; scrolling fires this on every frame near the bottom.
|
|
140
|
+
if (timestamp > entry.readTs && !app.state.readRequests.has(room.id)) {
|
|
141
|
+
app.state.readRequests.add(room.id);
|
|
142
|
+
try {
|
|
143
|
+
await app.api("/read", {
|
|
144
|
+
method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
|
|
145
|
+
});
|
|
146
|
+
if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
|
|
147
|
+
entry.readTs = timestamp;
|
|
148
|
+
app.saveReadTs(room.id, timestamp);
|
|
149
|
+
entry.unreadOverflow = false;
|
|
150
|
+
advanced = true;
|
|
151
|
+
} catch { return; /* The next active poll will retry the read watermark. */ }
|
|
152
|
+
finally { app.state.readRequests.delete(room.id); }
|
|
153
|
+
}
|
|
154
|
+
// Unanswered questions stay unread until answered.
|
|
155
|
+
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
|
+
for (const [id, message] of entry.unreadIds) {
|
|
164
|
+
const current = known.get(id) || message;
|
|
165
|
+
// 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);
|
|
167
|
+
else if (known.has(id)) entry.unreadIds.set(id, current);
|
|
168
|
+
}
|
|
169
|
+
for (const message of room.messages) {
|
|
170
|
+
if (open(message) && !isOwnMessage(message, app, room)) entry.unreadIds.set(message.id, message);
|
|
171
|
+
}
|
|
172
|
+
app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
173
|
+
if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
|
|
138
174
|
app.updateBadge();
|
|
139
175
|
app.updateJump();
|
|
140
176
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
141
177
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
142
|
-
}
|
|
178
|
+
}
|
|
143
179
|
};
|
|
144
180
|
|
|
145
181
|
app.renderMessage = (message, live) => {
|
|
@@ -293,11 +329,11 @@ export function initMessages(app) {
|
|
|
293
329
|
|
|
294
330
|
app.send = async () => {
|
|
295
331
|
const input = $("#msgInput"), room = app.state.room, replyTarget = room && app.replyTargetFor?.(room.id);
|
|
296
|
-
const isQuestion = !replyTarget && Boolean(app.isQuestionSending?.());
|
|
297
332
|
if (!room || app.state.sendingRooms?.has(room.id)) return;
|
|
298
333
|
const message = app.prepareMessage?.(room.id, input.value) || { text: input.value.trim(), ids: [], ready: Boolean(input.value.trim()) };
|
|
299
334
|
if (!message.ready) return;
|
|
300
335
|
const text = message.text;
|
|
336
|
+
const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
|
|
301
337
|
const revision = app.state.draftRevision.get(room.id) || 0;
|
|
302
338
|
app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
|
|
303
339
|
app.closeMention();
|
|
@@ -312,19 +348,29 @@ export function initMessages(app) {
|
|
|
312
348
|
let updated;
|
|
313
349
|
if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
|
|
314
350
|
else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
|
|
315
|
-
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text,
|
|
351
|
+
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
|
|
316
352
|
});
|
|
317
353
|
app.completeAttachments?.(room.id, message.ids);
|
|
318
354
|
if (app.state.room?.id !== room.id) return;
|
|
319
|
-
app.state.room = updated;
|
|
320
355
|
const entry = app.state.rooms.get(room.id);
|
|
356
|
+
// The POST snapshot is older than anything polling received while it was
|
|
357
|
+
// in flight; merge instead of dropping those messages.
|
|
358
|
+
let current = updated;
|
|
321
359
|
if (entry) {
|
|
322
|
-
entry.room
|
|
323
|
-
const
|
|
360
|
+
const merged = new Map([...entry.room.messages, ...updated.messages].map((item) => [item.id, { ...item, roomId: updated.id }]));
|
|
361
|
+
const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
362
|
+
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
363
|
+
current = { ...updated, messages };
|
|
364
|
+
}
|
|
365
|
+
app.state.room = current;
|
|
366
|
+
if (entry) {
|
|
367
|
+
entry.room = current;
|
|
368
|
+
const latest = current.messages.at(-1);
|
|
324
369
|
if (latest) setRoomPreview(entry, latest);
|
|
325
370
|
}
|
|
326
371
|
app.renderMessages(true);
|
|
327
|
-
|
|
372
|
+
// Reading history and sending must not teleport to the newest message or mark it read.
|
|
373
|
+
if (followedBottom) $("#thread").scrollTop = $("#thread").scrollHeight;
|
|
328
374
|
app.renderMembers();
|
|
329
375
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
330
376
|
app.updateBadge();
|
|
@@ -333,12 +379,19 @@ export function initMessages(app) {
|
|
|
333
379
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
334
380
|
} catch (error) {
|
|
335
381
|
const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
|
|
336
|
-
|
|
337
|
-
|
|
382
|
+
// Someone answered the question first; retrying the answer can never succeed,
|
|
383
|
+
// so keep the text as a draft instead of a failed message.
|
|
384
|
+
const staleReply = Boolean(replyTarget?.isQuestion) && (error.status === 409 || error.status === 404);
|
|
385
|
+
if (staleReply) app.saveDraft(room.id, text);
|
|
386
|
+
else {
|
|
387
|
+
const failures = app.state.failedMessages.get(room.id) || [];
|
|
388
|
+
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
|
|
389
|
+
app.renderFailedMessages();
|
|
390
|
+
}
|
|
338
391
|
app.completeAttachments?.(room.id, message.ids);
|
|
339
|
-
app.renderFailedMessages();
|
|
340
392
|
if (app.state.room?.id !== room.id) return;
|
|
341
|
-
if (unchanged) app.clearDraft(room.id);
|
|
393
|
+
if (unchanged && !staleReply) app.clearDraft(room.id);
|
|
394
|
+
if (staleReply) input.draftValue = text;
|
|
342
395
|
app.autoGrow(input);
|
|
343
396
|
app.updateSendState();
|
|
344
397
|
app.updateDraftCount();
|
|
@@ -403,9 +456,13 @@ export function initMessages(app) {
|
|
|
403
456
|
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
404
457
|
added++;
|
|
405
458
|
}
|
|
406
|
-
if (entry && item.createdAt > entry.readTs &&
|
|
459
|
+
if (entry && item.createdAt > entry.readTs && isUnreadMessage(item, app) && !entry.unreadIds.has(item.id)) {
|
|
407
460
|
entry.unreadIds.set(item.id, item); unreadChanged = true;
|
|
408
461
|
}
|
|
462
|
+
// An answer to a question clears that question even before the room is read.
|
|
463
|
+
if (entry && item.answerToMessageID && entry.unreadIds.get(item.answerToMessageID)?.isQuestion) {
|
|
464
|
+
entry.unreadIds.delete(item.answerToMessageID); unreadChanged = true;
|
|
465
|
+
}
|
|
409
466
|
}
|
|
410
467
|
if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
|
|
411
468
|
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
@@ -418,6 +475,7 @@ export function initMessages(app) {
|
|
|
418
475
|
if (added || unreadChanged || entry && previousUnreadOverflow !== entry.unreadOverflow) {
|
|
419
476
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : app.state.unread + added;
|
|
420
477
|
app.updateBadge();
|
|
478
|
+
app.updateJump();
|
|
421
479
|
}
|
|
422
480
|
if (rendered.skipped === 0) void app.markActiveRoomRead();
|
|
423
481
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
@@ -489,10 +547,16 @@ export function initMessages(app) {
|
|
|
489
547
|
|
|
490
548
|
}
|
|
491
549
|
|
|
550
|
+
// Unread means a person said something you have not seen; join/leave notices are not a badge.
|
|
551
|
+
export function isUnreadMessage(message, app, room = app.state.room, myName = app.state.myName) {
|
|
552
|
+
return message.senderId !== "system" && !isOwnMessage(message, app, room, myName);
|
|
553
|
+
}
|
|
554
|
+
|
|
492
555
|
export function isOwnMessage(message, app, room = app.state.room, myName = app.state.myName) {
|
|
493
556
|
const direct = room.kind === "direct";
|
|
494
557
|
const sameName = app.state.memberSessions.get(room.id)?.filter((member) => member.name === message.senderId);
|
|
495
558
|
return direct ? message.senderId === LS.sessionID
|
|
496
559
|
: message.senderSessionID ? message.senderSessionID === LS.sessionID
|
|
497
|
-
|
|
560
|
+
// Without a recorded sender session, fall back to the name unless a namesake is known.
|
|
561
|
+
: message.senderId === myName && (!sameName || sameName.every((member) => member.sessionID === LS.sessionID));
|
|
498
562
|
}
|
|
@@ -3,13 +3,13 @@ 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(),
|
|
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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
// Undefined until the server list for this room has loaded; callers must not
|
|
10
|
+
// treat that as "no open questions".
|
|
11
|
+
app.unansweredQuestionIds = (roomId = app.state.room?.id) => pending.has(roomId)
|
|
12
|
+
? new Set((pending.get(roomId) || []).map((item) => item.id)) : undefined;
|
|
13
13
|
|
|
14
14
|
const renderMessage = app.renderMessage;
|
|
15
15
|
app.renderMessage = (message, live) => {
|
|
@@ -29,6 +29,9 @@ export function initQuestions(app) {
|
|
|
29
29
|
const items = pending.get(roomId) || [];
|
|
30
30
|
const active = app.state.room?.id === roomId;
|
|
31
31
|
if (active) {
|
|
32
|
+
const signature = `${roomId}\0${app.locale}\0${selected.get(roomId) || ""}\0${items.map((question) => `${question.id}\0${question.text}`).join("\u0001")}`;
|
|
33
|
+
if (list.dataset.signature === signature) { renderReply(roomId); return; }
|
|
34
|
+
list.dataset.signature = signature;
|
|
32
35
|
$("#questionBadge").textContent = items.length > 99 ? "99+" : String(items.length);
|
|
33
36
|
$("#questionBadge").hidden = !items.length;
|
|
34
37
|
trigger.setAttribute("aria-label", `${app.t("questions")}: ${items.length}`);
|
|
@@ -218,6 +221,10 @@ export function initQuestions(app) {
|
|
|
218
221
|
|
|
219
222
|
function applyAnswer(roomId, questionId, result) {
|
|
220
223
|
const entry = app.state.rooms.get(roomId);
|
|
224
|
+
if (entry && result.answer) {
|
|
225
|
+
const question = entry.room.messages.find((item) => item.id === questionId);
|
|
226
|
+
if (question) question.answeredByMessageID = result.answer.id;
|
|
227
|
+
}
|
|
221
228
|
if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
|
|
222
229
|
entry.room.messages.push({ ...result.answer, roomId }); entry.room.messages.sort((a, b) => a.createdAt - b.createdAt);
|
|
223
230
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
@@ -264,7 +271,6 @@ export function initQuestions(app) {
|
|
|
264
271
|
const activateRoom = app.activateRoom;
|
|
265
272
|
app.activateRoom = (roomId, preserveRoomListGeneration = false) => {
|
|
266
273
|
activateRoom(roomId, preserveRoomListGeneration);
|
|
267
|
-
$("#questionToggle").checked = Boolean(questionMode.get(roomId));
|
|
268
274
|
void load(roomId);
|
|
269
275
|
};
|
|
270
276
|
const applyLocale = app.applyLocale;
|
|
@@ -29,10 +29,11 @@ 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) })}` : "";
|
|
36
|
+
detail.textContent = `${schedule}${reminder.paused ? ` · ${app.t("reminderPaused")}` : next}`;
|
|
36
37
|
const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "btn ghost small"; toggle.textContent = app.t(reminder.paused ? "reminderResume" : "reminderPause");
|
|
37
38
|
toggle.addEventListener("click", () => void update(reminder, !reminder.paused));
|
|
38
39
|
const remove = document.createElement("button"); remove.type = "button"; remove.className = "btn ghost small danger-text"; remove.textContent = app.t("reminderDelete");
|
|
@@ -51,8 +52,7 @@ export function initReminders(app) {
|
|
|
51
52
|
} catch (error) { if (current(id, context) && generation === request) status(errorText(error)); }
|
|
52
53
|
}
|
|
53
54
|
function validCron(expression) {
|
|
54
|
-
|
|
55
|
-
return fields.length === 5 && fields.every((field) => /^[0-9*/?,\-]+$/.test(field));
|
|
55
|
+
return expression.trim().split(/\s+/).length === 5;
|
|
56
56
|
}
|
|
57
57
|
async function update(reminder, paused) {
|
|
58
58
|
const id = roomId(), context = roomGeneration;
|
|
@@ -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
|
}
|
|
@@ -134,7 +130,7 @@ async function jumpToOriginal(roomId, messageId, app) {
|
|
|
134
130
|
}
|
|
135
131
|
} catch { return; }
|
|
136
132
|
if (!original) return markUnavailable(messageId, roomId, app);
|
|
137
|
-
app.state.positions.set(roomId, { messageId, offset: 0 }); app.savePosition(roomId, { messageId, offset: 0 });
|
|
133
|
+
app.state.positions.set(roomId, { messageId, offset: 0, atBottom: false }); app.savePosition(roomId, { messageId, offset: 0, atBottom: false });
|
|
138
134
|
if (app.state.room?.id === roomId && app.state.navigationGeneration === generation) {
|
|
139
135
|
app.state.room = app.state.rooms.get(roomId)?.room || room; app.rerenderMessages();
|
|
140
136
|
document.querySelector(`[data-msg-id="${CSS.escape(messageId)}"]`)?.scrollIntoView({ block: "center" });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isUnreadMessage } from "./messages.js";
|
|
2
2
|
import { setRoomPreview } from "./system-messages.js";
|
|
3
3
|
|
|
4
4
|
export async function watchRoom(roomId, app) {
|
|
@@ -13,12 +13,15 @@ export async function watchRoom(roomId, app) {
|
|
|
13
13
|
if (result.member !== true || !Array.isArray(result.items) || app.state.room?.id === roomId) return;
|
|
14
14
|
const previousReceivedTs = entry.receivedTs || 0;
|
|
15
15
|
const sawSystem = result.items.some((message) => message.senderId === "system");
|
|
16
|
+
const before = new Set(entry.room.messages.map((message) => message.id));
|
|
16
17
|
for (const message of result.items) {
|
|
17
|
-
if (
|
|
18
|
-
if (
|
|
18
|
+
if (message.createdAt > entry.readTs && isUnreadMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
19
|
+
if (message.answerToMessageID && entry.unreadIds.get(message.answerToMessageID)?.isQuestion) entry.unreadIds.delete(message.answerToMessageID);
|
|
20
|
+
if (!before.has(message.id)) entry.room.messages.push({ ...message, roomId });
|
|
19
21
|
if (message.createdAt >= entry.previewAt) setRoomPreview(entry, message);
|
|
20
22
|
}
|
|
21
23
|
entry.receivedTs = result.items.reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
24
|
+
entry.unreadOverflow = Boolean(result.hasMore);
|
|
22
25
|
if (sawSystem || result.hasMore) {
|
|
23
26
|
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
24
27
|
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
@@ -26,8 +29,13 @@ export async function watchRoom(roomId, app) {
|
|
|
26
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);
|
|
27
30
|
const newest = latest.messages.at(-1);
|
|
28
31
|
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
32
|
+
// A full refresh pages past the inbox window; count what arrived since the last look.
|
|
33
|
+
for (const message of latest.messages) {
|
|
34
|
+
if (message.answeredByMessageID) entry.unreadIds.delete(message.id);
|
|
35
|
+
if (message.createdAt > previousReceivedTs && message.createdAt > entry.readTs && isUnreadMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
36
|
+
}
|
|
37
|
+
if (newest && Number.isSafeInteger(newest.createdAt)) entry.receivedTs = Math.max(entry.receivedTs, newest.createdAt);
|
|
29
38
|
}
|
|
30
|
-
entry.unreadOverflow = Boolean(result.hasMore);
|
|
31
39
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
32
40
|
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
33
41
|
} catch (error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { isUnreadMessage } from "./messages.js";
|
|
2
3
|
import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
|
|
3
4
|
import { watchRoom } from "./room-watcher.js";
|
|
4
5
|
|
|
@@ -50,10 +51,17 @@ export function initRooms(app) {
|
|
|
50
51
|
const entry = existing || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0, receivedTs: room.messages.at(-1)?.createdAt ?? 0 };
|
|
51
52
|
entry.unreadIds ||= new Map();
|
|
52
53
|
entry.unreadOverflow ||= false;
|
|
53
|
-
|
|
54
|
+
const latest = room.messages.at(-1), savedReadTs = app.state.lastReadTs.get(room.id) ?? (typeof room.lastReadTs === "number" ? room.lastReadTs : undefined);
|
|
55
|
+
if (savedReadTs !== undefined && !app.state.lastReadTs.has(room.id)) app.saveReadTs(room.id, savedReadTs);
|
|
56
|
+
entry.readTs ||= savedReadTs || 0;
|
|
54
57
|
entry.room = room;
|
|
55
58
|
entry.name = name;
|
|
56
|
-
|
|
59
|
+
// Only rebuild unread history when this browser already has a read watermark;
|
|
60
|
+
// 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);
|
|
64
|
+
}
|
|
57
65
|
entry.receivedTs ??= latest?.createdAt ?? 0;
|
|
58
66
|
if (latest && (!existing || latest.createdAt >= entry.previewAt)) setRoomPreview(entry, latest);
|
|
59
67
|
app.state.rooms.set(room.id, entry);
|
|
@@ -88,7 +96,8 @@ export function initRooms(app) {
|
|
|
88
96
|
$("#msgList").textContent = "";
|
|
89
97
|
app.renderMessages(false);
|
|
90
98
|
const restoredPosition = app.restoreReadingPosition?.(roomId);
|
|
91
|
-
|
|
99
|
+
// A restore above the bottom needs a scroll before it counts as read.
|
|
100
|
+
app.state.readAnchorGuard = restoredPosition && !restoredPosition.atBottom ? { roomId, ...restoredPosition } : null;
|
|
92
101
|
app.startPolling();
|
|
93
102
|
app.renderMembers();
|
|
94
103
|
if (!restoredPosition) $("#thread").scrollTop = typeof savedPosition === "number" ? savedPosition : entry.position || $("#thread").scrollHeight;
|
|
@@ -102,7 +111,7 @@ export function initRooms(app) {
|
|
|
102
111
|
app.hideSendError();
|
|
103
112
|
app.updateBadge();
|
|
104
113
|
app.updateJump();
|
|
105
|
-
if (!restoredPosition) app.markActiveRoomRead();
|
|
114
|
+
if (!restoredPosition || restoredPosition.atBottom) app.markActiveRoomRead();
|
|
106
115
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
107
116
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
108
117
|
void app.refreshRoomList();
|
|
@@ -183,7 +192,7 @@ export function initRooms(app) {
|
|
|
183
192
|
app.disposeRoomAttachments?.(roomId);
|
|
184
193
|
if (active) {
|
|
185
194
|
app.state.navigationGeneration++;
|
|
186
|
-
app.saveDraft(roomId, $("#msgInput").
|
|
195
|
+
app.saveDraft(roomId, $("#msgInput").draftValue);
|
|
187
196
|
app.captureReadingPosition?.();
|
|
188
197
|
app.stopPolling();
|
|
189
198
|
app.closeMention();
|
|
@@ -386,7 +395,7 @@ export function initRooms(app) {
|
|
|
386
395
|
status.className = "r-status";
|
|
387
396
|
app.setText(status, entry ? "joined" : "joinAction");
|
|
388
397
|
button.append(name, kind, meta, preview, status);
|
|
389
|
-
const unread = entry?.
|
|
398
|
+
const unread = entry && app.state.room?.id !== room.id ? (entry.unreadOverflow ? 100 : entry.unreadIds.size) : 0;
|
|
390
399
|
if (unread) {
|
|
391
400
|
const badge = document.createElement("span");
|
|
392
401
|
badge.className = "r-badge";
|
|
@@ -398,6 +407,8 @@ export function initRooms(app) {
|
|
|
398
407
|
row.append(button);
|
|
399
408
|
list.append(row);
|
|
400
409
|
}
|
|
410
|
+
// Other rooms' unread changes only reach the title through this rerender.
|
|
411
|
+
app.updateTitle();
|
|
401
412
|
};
|
|
402
413
|
|
|
403
414
|
app.closePanels = () => {
|
|
@@ -233,10 +233,9 @@ const messages = {
|
|
|
233
233
|
questionsFailed: "Could not load questions. Try again.", questionsUnsupported: "Unanswered questions are unavailable on this server.", questionLabel: "Question",
|
|
234
234
|
answerQuestion: "Reply", answerPlaceholder: "Write a reply…", sendAnswer: "Send reply", selectQuestion: "Reply to question", copyQuestion: "Copy question", questionCopied: "Question copied.", questionCopyFailed: "Could not copy question.",
|
|
235
235
|
answerFailed: "Reply failed. Your draft is still here.", answerTooLong: "Reply must be 2,000 characters or fewer.", questionAlreadyAnswered: "This question was answered elsewhere.",
|
|
236
|
-
sendAsQuestion: "Send as a question",
|
|
237
236
|
adminBindingGuide: "Choose a room and an Agent in it. Send the invitation privately to finish setup.", adminRoomLabel: "Administrator room", adminDesignateAgent: "Invite Agent",
|
|
238
|
-
settings: "Settings", adminAccess: "Administration", adminToken: "Administration token", openAdministration: "Open administration", administration: "Administration", designations: "Designations", adminRoom: "Administrator room", targetRoom: "Agent membership room", adminScopeNote: "Choose an Agent in the administrator room. Administrators can manage all rooms.", targetAgent: "Registered agent", designate: "Designate
|
|
239
|
-
adminLoading: "Loading administration…", refreshAdmin: "Refresh", adminRoomBadge: "admin", chooseAdminRoom: "Choose a normal room", chooseTargetRoom: "Choose an agent room", chooseAgent: "Choose a registered agent", taskTargetRoom: "Target room", taskTargetAgent: "Target agent", createAdminRoomFirst: "Create a normal room first, then select it as the admin room.", noAgents: "No registered agents", selectAdminAgent: "Choose an admin room and registered agent.",
|
|
237
|
+
settings: "Settings", adminAccess: "Administration", adminToken: "Administration token", openAdministration: "Open administration", administration: "Administration", designations: "Designations", adminRoom: "Administrator room", targetRoom: "Agent membership room", adminScopeNote: "Choose an Agent in the administrator room. Administrators can manage all rooms.", targetAgent: "Registered agent", designate: "Designate administrator", revokeDesignation: "Revoke designation", globalStatus: "Global status", adminTasks: "Tasks", taskText: "Task", dispatchTask: "Dispatch task", timers: "Timers", planName: "Timer name", createTimer: "Create timer", tokenRequired: "The server requires an access token (401).",
|
|
238
|
+
adminLoading: "Loading administration…", refreshAdmin: "Refresh", adminRoomBadge: "admin", chooseAdminRoom: "Choose a normal room", chooseTargetRoom: "Choose an agent room", chooseAgent: "Choose a registered agent", taskTargetRoom: "Target room", taskTargetAgent: "Target agent", createAdminRoomFirst: "Create a normal room first, then select it as the admin room.", noAgents: "No registered agents", selectAdminAgent: "Choose an admin room and registered agent.", adminDesignated: "Administrator designation is active immediately and stays until you revoke it.", revokeConfirm: "Revoke this admin designation? The normal room will remain.", updateTask: "Update task", task_pending: "Pending", task_working: "Working", task_blocked: "Blocked", task_completed: "Completed", task_cancelled: "Cancelled", nextRun: ({ time, minutes }) => `Every ${minutes} min · next ${time}`, paused: "Paused", pauseTimer: "Pause", resumeTimer: "Resume", deleteTimer: "Delete", deleteTimerConfirm: ({ name }) => `Delete timer “${name}”?`,
|
|
240
239
|
leave: "Leave", reconnecting: "Connection lost. Retrying…", messageList: "Message list",
|
|
241
240
|
noMessages: "No messages yet. Say something.", latestMessages: "Back to latest messages",
|
|
242
241
|
mentionMembers: "Choose a member to mention", messagePlaceholder: "Message · Enter to send",
|
|
@@ -309,10 +308,9 @@ const messages = {
|
|
|
309
308
|
questionsFailed: "无法加载问题,请重试。", questionsUnsupported: "此服务器不支持查看待回答问题。", questionLabel: "问题",
|
|
310
309
|
answerQuestion: "回复", answerPlaceholder: "写下回复…", sendAnswer: "发送回复", selectQuestion: "回复此问题", copyQuestion: "复制问题", questionCopied: "问题已复制。", questionCopyFailed: "无法复制问题。",
|
|
311
310
|
answerFailed: "回复失败,草稿仍已保留。", answerTooLong: "回复不能超过 2,000 个字符。", questionAlreadyAnswered: "此问题已由其他人回答。",
|
|
312
|
-
sendAsQuestion: "作为问题发送",
|
|
313
311
|
adminBindingGuide: "选择管理员房间和其中的 Agent,再将邀请私下发送给该 Agent 完成设置。", adminRoomLabel: "管理员房间", adminDesignateAgent: "邀请 Agent",
|
|
314
|
-
adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "请选择管理员房间内的 Agent。管理员可以管理所有房间。", adminRoomBadge: "管理", targetAgent: "已注册 Agent", designate: "
|
|
315
|
-
adminLoading: "正在加载管理面板…", refreshAdmin: "刷新", adminRoomBadge: "管理", chooseAdminRoom: "选择普通房间", chooseTargetRoom: "选择 Agent 房间", chooseAgent: "选择已注册 Agent", taskTargetRoom: "任务目标房间", taskTargetAgent: "任务目标 Agent", createAdminRoomFirst: "请先按普通流程创建房间,再选作管理房间。", noAgents: "没有已注册的 Agent", selectAdminAgent: "请选择管理房间和已注册的 Agent。",
|
|
312
|
+
adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "请选择管理员房间内的 Agent。管理员可以管理所有房间。", adminRoomBadge: "管理", targetAgent: "已注册 Agent", designate: "指定管理员", revokeDesignation: "撤销绑定", globalStatus: "全局状态", adminTasks: "任务", taskText: "任务内容", dispatchTask: "派发任务", timers: "定时任务", planName: "定时任务名称", createTimer: "创建定时任务",
|
|
313
|
+
adminLoading: "正在加载管理面板…", refreshAdmin: "刷新", adminRoomBadge: "管理", chooseAdminRoom: "选择普通房间", chooseTargetRoom: "选择 Agent 房间", chooseAgent: "选择已注册 Agent", taskTargetRoom: "任务目标房间", taskTargetAgent: "任务目标 Agent", createAdminRoomFirst: "请先按普通流程创建房间,再选作管理房间。", noAgents: "没有已注册的 Agent", selectAdminAgent: "请选择管理房间和已注册的 Agent。", adminDesignated: "管理员已立即生效,长期有效,直到撤销。", revokeConfirm: "撤销此管理绑定?普通房间会保留。", updateTask: "更新任务", task_pending: "待处理", task_working: "进行中", task_blocked: "受阻", task_completed: "已完成", task_cancelled: "已取消", nextRun: ({ time, minutes }) => `每 ${minutes} 分钟 · 下次 ${time}`, paused: "已暂停", pauseTimer: "暂停", resumeTimer: "恢复", deleteTimer: "删除", deleteTimerConfirm: ({ name }) => `删除定时任务“${name}”?`,
|
|
316
314
|
tokenRequired: "服务器要求访问令牌(401)。", leave: "离开", reconnecting: "连接中断,正在重试…",
|
|
317
315
|
messageList: "消息列表", noMessages: "还没有消息,说点什么吧。", latestMessages: "回到最新消息",
|
|
318
316
|
mentionMembers: "选择要提及的成员", messagePlaceholder: "输入消息,Enter 发送",
|
|
@@ -469,7 +467,10 @@ app.flash = (button, key) => {
|
|
|
469
467
|
};
|
|
470
468
|
app.updateTitle = () => {
|
|
471
469
|
const title = app.state.room ? app.t("roomTitle", { name: app.state.room.name }) : app.t("documentTitle");
|
|
472
|
-
|
|
470
|
+
const active = app.state.room?.id;
|
|
471
|
+
let total = 0;
|
|
472
|
+
for (const [id, entry] of app.state.rooms) total += id === active ? app.state.unread : entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
473
|
+
document.title = total ? `(${total}) ${title}` : title;
|
|
473
474
|
};
|
|
474
475
|
app.setOnline = (online) => { app.$("#connBar").hidden = online; };
|
|
475
476
|
app.showSendError = (key, values = {}) => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export function formatSystemMessage(message, app) {
|
|
2
|
-
|
|
2
|
+
// `<at>@name</at>` is an editor token; system rows and previews show the plain mention.
|
|
3
|
+
const text = String(message?.text ?? "").replace(/<at>([\s\S]*?)<\/at>/g, "$1");
|
|
3
4
|
if (message?.senderId !== "system") return text;
|
|
4
5
|
const joined = /^(.*?)\s+joined the room$/.exec(text);
|
|
5
6
|
if (joined) return app.t("systemJoined", { name: joined[1] });
|
|
@@ -442,9 +442,7 @@
|
|
|
442
442
|
background: linear-gradient(180deg, var(--surface), color-mix(in srgb, var(--accent-soft) 18%, var(--surface)));
|
|
443
443
|
}
|
|
444
444
|
.composer-row { display: flex; gap: 9px; align-items: flex-end; }
|
|
445
|
-
.composer-meta { display: flex; align-items: center; justify-content:
|
|
446
|
-
.question-toggle { min-width: 0; margin: 0; color: var(--ink-2); font-size: 12px; }
|
|
447
|
-
.question-toggle input { accent-color: var(--accent); vertical-align: -1px; }
|
|
445
|
+
.composer-meta { display: flex; align-items: center; justify-content: flex-end; gap: 8px; width: min(940px, 100%); min-width: 0; margin: -1px auto 0; }
|
|
448
446
|
.composer .input { flex: 1; }
|
|
449
447
|
.composer .input:disabled { opacity: .5; }
|
|
450
448
|
#msgInput {
|