@alexsun-top/opencode-chat-room 0.3.0 → 0.3.2
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 +17 -0
- package/README.md +35 -6
- package/README.zh-CN.md +35 -6
- package/package.json +2 -1
- package/plugin.ts +15 -1
- package/server/assets/chat/events.js +10 -3
- package/server/assets/chat/members.js +120 -14
- package/server/assets/chat/message-window.js +13 -0
- package/server/assets/chat/messages.js +103 -34
- package/server/assets/chat/rooms.js +57 -26
- package/server/assets/chat/state.js +85 -17
- package/server/assets/chat/system-messages.js +20 -0
- package/server/assets/conversation.css +19 -5
- package/server/assets/responsive.css +3 -3
- package/server/chat-server.ts +17 -37
- package/server/inbox.ts +2 -2
- package/server/member-routes.ts +117 -0
- package/server/newrooms.ts +6 -10
- package/src/agent-presence.ts +60 -0
- package/src/agent-receipts.ts +107 -0
- package/src/center-client.ts +22 -5
- package/src/center-inbox.ts +7 -1
- package/src/member-state.ts +25 -0
- package/src/plugin-notifications.ts +6 -0
- package/src/receiver-state.ts +51 -6
- package/src/sqlite-state.ts +102 -10
- package/src/store.ts +30 -3
- package/src/v2-plugin.ts +25 -4
- package/src/v2-receiver.ts +69 -45
- package/src/watch.ts +17 -3
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createRandomId, LS } from "./state.js";
|
|
2
2
|
import { renderMarkdown } from "./markdown.js";
|
|
3
|
+
import { hasMessageSelection, pruneMessageRows } from "./message-window.js";
|
|
4
|
+
import { formatSystemMessage, setRoomPreview } from "./system-messages.js";
|
|
3
5
|
|
|
4
6
|
export function initMessages(app) {
|
|
5
7
|
const $ = app.$;
|
|
@@ -52,7 +54,7 @@ export function initMessages(app) {
|
|
|
52
54
|
if (entry) {
|
|
53
55
|
entry.room = mergeRoom(entry.room, updated);
|
|
54
56
|
const latest = entry.room.messages.at(-1);
|
|
55
|
-
if (latest && latest.createdAt >= entry.previewAt)
|
|
57
|
+
if (latest && latest.createdAt >= entry.previewAt) setRoomPreview(entry, latest);
|
|
56
58
|
}
|
|
57
59
|
app.discardFailedMessage(roomId, failedId);
|
|
58
60
|
if (app.state.room?.id === roomId && entry) {
|
|
@@ -120,7 +122,7 @@ export function initMessages(app) {
|
|
|
120
122
|
if (message.senderId === "system") {
|
|
121
123
|
row.className = "sys";
|
|
122
124
|
const text = document.createElement("span");
|
|
123
|
-
text.textContent =
|
|
125
|
+
text.textContent = formatSystemMessage(message, app);
|
|
124
126
|
row.append(text);
|
|
125
127
|
} else {
|
|
126
128
|
const direct = app.state.room.kind === "direct";
|
|
@@ -142,28 +144,47 @@ export function initMessages(app) {
|
|
|
142
144
|
const body = document.createElement("div");
|
|
143
145
|
body.className = "msg-text";
|
|
144
146
|
renderMarkdown(body, message.text, app);
|
|
145
|
-
row.append(meta, body);
|
|
147
|
+
row.append(meta, body, receiptDetails(message, app));
|
|
146
148
|
}
|
|
147
149
|
if (live) row.classList.add("in");
|
|
148
150
|
return row;
|
|
149
151
|
};
|
|
150
152
|
|
|
153
|
+
app.renderReceiptData = (roomId, receipts) => {
|
|
154
|
+
const thread = $("#thread"), edge = thread.getBoundingClientRect();
|
|
155
|
+
const atBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
|
|
156
|
+
const anchor = Array.from($("#msgList").querySelectorAll("[data-msg-id]")).find((node) => node.getBoundingClientRect().bottom > edge.top);
|
|
157
|
+
const anchorId = anchor?.dataset.msgId, anchorTop = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
|
|
158
|
+
for (const receipt of receipts) app.state.receipts.set(`${roomId}\0${receipt.messageID}`, receipt.readers);
|
|
159
|
+
for (const row of document.querySelectorAll(`#msgList [data-msg-id]`)) {
|
|
160
|
+
const message = app.state.room?.messages.find((item) => item.id === row.dataset.msgId);
|
|
161
|
+
if (message?.roomId === roomId || app.state.room?.id === roomId && message) updateReceiptDetails(row, message, app);
|
|
162
|
+
}
|
|
163
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
164
|
+
else if (anchorId) {
|
|
165
|
+
const next = $("#msgList").querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
166
|
+
if (next) thread.scrollTop += next.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorTop;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
151
170
|
app.renderMessages = (live = false) => {
|
|
152
171
|
const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
|
|
153
|
-
const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight
|
|
154
|
-
let
|
|
155
|
-
let anchorId = null;
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
172
|
+
const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
|
|
173
|
+
let skipped = 0;
|
|
174
|
+
let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
|
|
175
|
+
const viewport = thread.getBoundingClientRect();
|
|
176
|
+
const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
|
|
177
|
+
anchorId = firstVisible?.dataset.msgId || null;
|
|
178
|
+
anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
|
|
179
|
+
pruneMessageRows(list, messages);
|
|
180
|
+
let last = list.lastElementChild;
|
|
181
|
+
const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
|
|
182
|
+
let startIndex = 0;
|
|
183
|
+
const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
|
|
184
|
+
if (lastId) for (let index = messages.length - 1; index >= 0; index--) if (messages[index].id === lastId) { startIndex = index + 1; break; }
|
|
185
|
+
for (let index = startIndex; index < messages.length; index++) {
|
|
165
186
|
const message = messages[index];
|
|
166
|
-
if (renderedIds.has(message.id)) continue;
|
|
187
|
+
if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id)) continue;
|
|
167
188
|
try {
|
|
168
189
|
const day = new Date(message.createdAt).toDateString();
|
|
169
190
|
if (!last || last.dataset.day !== day) {
|
|
@@ -190,13 +211,29 @@ export function initMessages(app) {
|
|
|
190
211
|
app.rendered = messages.length;
|
|
191
212
|
app.firstMessageId = messages[0]?.id || app.firstMessageId;
|
|
192
213
|
$("#msgEmpty").hidden = messages.length > 0;
|
|
193
|
-
if (
|
|
214
|
+
if (nearBottom) thread.scrollTop = thread.scrollHeight;
|
|
215
|
+
else if (anchorId) {
|
|
194
216
|
const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
195
|
-
if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top -
|
|
196
|
-
else thread.scrollTop =
|
|
217
|
+
if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - viewport.top - anchorOffset;
|
|
218
|
+
else thread.scrollTop = oldTop;
|
|
197
219
|
} else if (!live || nearBottom) thread.scrollTop = thread.scrollHeight;
|
|
198
220
|
app.updateJump();
|
|
199
221
|
trimMessages(list, app);
|
|
222
|
+
if (nearBottom) {
|
|
223
|
+
thread.scrollTop = thread.scrollHeight;
|
|
224
|
+
const roomId = app.state.room?.id, generation = app.state.pollGeneration;
|
|
225
|
+
requestAnimationFrame(() => {
|
|
226
|
+
if (app.state.room?.id === roomId && app.state.pollGeneration === generation
|
|
227
|
+
&& thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) thread.scrollTop = thread.scrollHeight;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
else if (anchorId) {
|
|
231
|
+
const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
232
|
+
if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorOffset;
|
|
233
|
+
else thread.scrollTop = oldTop;
|
|
234
|
+
}
|
|
235
|
+
app.queueReceiptRefresh?.();
|
|
236
|
+
app.queueReceiptObservation?.();
|
|
200
237
|
return { skipped };
|
|
201
238
|
};
|
|
202
239
|
|
|
@@ -241,7 +278,7 @@ export function initMessages(app) {
|
|
|
241
278
|
if (entry) {
|
|
242
279
|
entry.room = updated;
|
|
243
280
|
const latest = updated.messages.at(-1);
|
|
244
|
-
if (latest)
|
|
281
|
+
if (latest) setRoomPreview(entry, latest);
|
|
245
282
|
}
|
|
246
283
|
app.renderMessages(true);
|
|
247
284
|
$("#thread").scrollTop = $("#thread").scrollHeight;
|
|
@@ -298,15 +335,16 @@ export function initMessages(app) {
|
|
|
298
335
|
const roomId = app.state.room?.id;
|
|
299
336
|
if (!roomId || !isCurrentPoll(roomId, generation)) return;
|
|
300
337
|
try {
|
|
301
|
-
const
|
|
338
|
+
const entry = app.state.rooms.get(roomId);
|
|
339
|
+
const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, excludeSelf: "0", timeout: "25000", afterTs: String(entry?.receivedTs || 0) });
|
|
302
340
|
const data = await app.api(`/inbox?${query}`, { signal });
|
|
303
341
|
if (!isCurrentPoll(roomId, generation)) return;
|
|
304
|
-
if (
|
|
342
|
+
if (data.member === false) {
|
|
305
343
|
void app.removeJoinedRoom(roomId, { reason: true });
|
|
306
344
|
return;
|
|
307
345
|
}
|
|
308
|
-
|
|
309
|
-
const
|
|
346
|
+
if (data.member !== true || !Array.isArray(data.items)) return;
|
|
347
|
+
const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
|
|
310
348
|
const known = new Set(messages.map((message) => message.id));
|
|
311
349
|
let sawSystem = false, added = 0;
|
|
312
350
|
for (const item of items) {
|
|
@@ -315,9 +353,10 @@ export function initMessages(app) {
|
|
|
315
353
|
messages.push({ ...item, roomId });
|
|
316
354
|
known.add(item.id);
|
|
317
355
|
entry?.unreadIds.set(item.id, item);
|
|
318
|
-
if (entry && item.createdAt >= entry.previewAt)
|
|
356
|
+
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
319
357
|
added++;
|
|
320
358
|
}
|
|
359
|
+
if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
|
|
321
360
|
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
322
361
|
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
323
362
|
const rendered = app.renderMessages(true);
|
|
@@ -337,7 +376,7 @@ export function initMessages(app) {
|
|
|
337
376
|
void app.reconcileRoom(roomId, generation);
|
|
338
377
|
}
|
|
339
378
|
app.setOnline(true);
|
|
340
|
-
pollDelay = 2000;
|
|
379
|
+
pollDelay = data.hasMore && (entry?.receivedTs || 0) > previousReceivedTs ? 0 : 2000;
|
|
341
380
|
} catch (error) {
|
|
342
381
|
if (!isCurrentPoll(roomId, generation)) return;
|
|
343
382
|
if (error.status === 401) {
|
|
@@ -397,8 +436,8 @@ export function initMessages(app) {
|
|
|
397
436
|
return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
398
437
|
}
|
|
399
438
|
|
|
400
|
-
|
|
401
|
-
if (list.children.length <= 400) return;
|
|
439
|
+
function trimMessages(list, app) {
|
|
440
|
+
if (list.children.length <= 400 || hasMessageSelection(list)) return;
|
|
402
441
|
while (list.children.length > 300) list.removeChild(list.firstChild);
|
|
403
442
|
if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
|
|
404
443
|
const gap = document.createElement("li");
|
|
@@ -406,12 +445,42 @@ export function initMessages(app) {
|
|
|
406
445
|
app.setText(gap, "earlierMessages");
|
|
407
446
|
list.insertBefore(gap, list.firstChild);
|
|
408
447
|
}
|
|
409
|
-
|
|
448
|
+
}
|
|
410
449
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
450
|
+
function receiptDetails(message, app) {
|
|
451
|
+
const details = document.createElement("details");
|
|
452
|
+
details.className = "message-readers";
|
|
453
|
+
const summary = document.createElement("summary"), count = document.createElement("span"), list = document.createElement("ul");
|
|
454
|
+
count.className = "receipt-count";
|
|
455
|
+
list.className = "receipt-reader-list";
|
|
456
|
+
summary.append(count);
|
|
457
|
+
details.append(summary, list);
|
|
458
|
+
updateReceiptDetails(details.closest("li") || details, message, app);
|
|
459
|
+
return details;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function updateReceiptDetails(row, message, app) {
|
|
463
|
+
const details = row.matches?.("details.message-readers") ? row : row.querySelector("details.message-readers");
|
|
464
|
+
if (!details) return;
|
|
465
|
+
const detailsKey = `${app.state.room?.id || message.roomId || ""}\0${message.id}`;
|
|
466
|
+
const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
|
|
467
|
+
const readers = (app.state.receipts.get(detailsKey) || []).filter((reader) => reader.sessionID !== senderID);
|
|
468
|
+
details.hidden = readers.length === 0;
|
|
469
|
+
details.querySelector(".receipt-count").textContent = app.t("receiptCount", { count: readers.length });
|
|
470
|
+
const list = details.querySelector(".receipt-reader-list");
|
|
471
|
+
list.textContent = "";
|
|
472
|
+
const members = app.state.memberSessions.get(app.state.room?.id) || [];
|
|
473
|
+
for (const reader of readers) {
|
|
474
|
+
const row = document.createElement("li"), name = document.createElement("span"), evidence = document.createElement("span");
|
|
475
|
+
const duplicates = members.filter((member) => member.name === reader.name).length > 1 || readers.filter((item) => item.name === reader.name).length > 1;
|
|
476
|
+
name.textContent = `${reader.name}${duplicates ? ` · ${reader.sessionID.slice(0, 8)}` : ""}${reader.currentMember === false ? ` · ${app.t("departedMember")}` : ""}`;
|
|
477
|
+
evidence.textContent = app.t(`receiptEvidence_${reader.evidence}`);
|
|
478
|
+
evidence.title = evidence.textContent;
|
|
479
|
+
evidence.setAttribute("aria-label", evidence.textContent);
|
|
480
|
+
row.dataset.readerSessionId = reader.sessionID;
|
|
481
|
+
row.append(name, evidence);
|
|
482
|
+
list.append(row);
|
|
416
483
|
}
|
|
417
484
|
}
|
|
485
|
+
|
|
486
|
+
}
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
|
|
2
3
|
|
|
3
4
|
export function initRooms(app) {
|
|
4
5
|
const $ = app.$;
|
|
5
6
|
|
|
6
|
-
app.showJoin = () => {
|
|
7
|
+
app.showJoin = (refresh = true) => {
|
|
8
|
+
if (!$("#inName").value) $("#inName").value = LS.name;
|
|
7
9
|
$("#chatView").hidden = true;
|
|
8
10
|
$("#joinView").hidden = false;
|
|
9
11
|
app.updateTitle();
|
|
10
|
-
void app.refreshRoomList();
|
|
12
|
+
if (refresh) void app.refreshRoomList();
|
|
11
13
|
$("#inRoomId").focus();
|
|
12
14
|
};
|
|
13
15
|
app.showChat = () => {
|
|
@@ -34,13 +36,15 @@ export function initRooms(app) {
|
|
|
34
36
|
};
|
|
35
37
|
|
|
36
38
|
app.ensureJoinedRoom = (room, name) => {
|
|
37
|
-
const
|
|
39
|
+
const existing = app.state.rooms.get(room.id);
|
|
40
|
+
const entry = existing || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0, receivedTs: room.messages.at(-1)?.createdAt ?? 0 };
|
|
38
41
|
entry.unreadIds ||= new Map();
|
|
39
42
|
entry.unreadOverflow ||= false;
|
|
40
43
|
entry.room = room;
|
|
41
44
|
entry.name = name;
|
|
42
|
-
|
|
43
|
-
entry.
|
|
45
|
+
const latest = room.messages.at(-1);
|
|
46
|
+
entry.receivedTs ??= latest?.createdAt ?? 0;
|
|
47
|
+
if (latest && (!existing || latest.createdAt >= entry.previewAt)) setRoomPreview(entry, latest);
|
|
44
48
|
app.state.rooms.set(room.id, entry);
|
|
45
49
|
app.state.roomNames.set(room.id, name);
|
|
46
50
|
app.state.joinedIds.add(room.id);
|
|
@@ -68,11 +72,11 @@ export function initRooms(app) {
|
|
|
68
72
|
app.firstMessageId = null;
|
|
69
73
|
app.state.pendingAction = null;
|
|
70
74
|
LS.roomId = roomId;
|
|
71
|
-
LS.name = entry.name;
|
|
72
75
|
app.showChat();
|
|
73
76
|
app.renderHead();
|
|
74
77
|
$("#msgList").textContent = "";
|
|
75
78
|
app.renderMessages(false);
|
|
79
|
+
app.startPolling();
|
|
76
80
|
app.renderMembers();
|
|
77
81
|
$("#thread").scrollTop = hasSavedPosition ? entry.position : entry.position || $("#thread").scrollHeight;
|
|
78
82
|
$("#msgInput").disabled = false;
|
|
@@ -82,7 +86,6 @@ export function initRooms(app) {
|
|
|
82
86
|
app.updateDraftCount();
|
|
83
87
|
app.updateSendState();
|
|
84
88
|
app.hideSendError();
|
|
85
|
-
app.startPolling();
|
|
86
89
|
app.updateBadge();
|
|
87
90
|
app.updateJump();
|
|
88
91
|
app.markActiveRoomRead();
|
|
@@ -102,6 +105,7 @@ export function initRooms(app) {
|
|
|
102
105
|
method: "POST",
|
|
103
106
|
body: JSON.stringify({ sessionID: LS.sessionID, participantId: name, participantName: name }),
|
|
104
107
|
});
|
|
108
|
+
LS.name = name;
|
|
105
109
|
app.enterRoom(room, name, intent);
|
|
106
110
|
} catch (error) {
|
|
107
111
|
if (error.status === 401) {
|
|
@@ -114,7 +118,7 @@ export function initRooms(app) {
|
|
|
114
118
|
|
|
115
119
|
app.createRoom = async (pending) => {
|
|
116
120
|
const fromChat = pending?.fromChat ?? Boolean(app.state.room);
|
|
117
|
-
const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || app.t("guest");
|
|
121
|
+
const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || LS.name || app.t("guest");
|
|
118
122
|
const roomName = pending?.roomName || $(fromChat ? "#inRoomNameChat" : "#inRoomName").value.trim();
|
|
119
123
|
if (!roomName) return fromChat ? app.showSendError("roomNameRequired") : app.showJoinError("roomNameRequired");
|
|
120
124
|
const intent = ++app.state.navigationGeneration;
|
|
@@ -127,6 +131,7 @@ export function initRooms(app) {
|
|
|
127
131
|
method: "POST",
|
|
128
132
|
body: JSON.stringify({ name: roomName, ownerId: name, sessionID: LS.sessionID }),
|
|
129
133
|
});
|
|
134
|
+
LS.name = name;
|
|
130
135
|
if (fromChat) {
|
|
131
136
|
$("#inRoomNameChat").value = "";
|
|
132
137
|
$("#railRoomForm").hidden = true;
|
|
@@ -188,7 +193,6 @@ export function initRooms(app) {
|
|
|
188
193
|
if (next) app.activateRoom(next);
|
|
189
194
|
else {
|
|
190
195
|
LS.roomId = "";
|
|
191
|
-
LS.name = "";
|
|
192
196
|
app.showJoin();
|
|
193
197
|
if (reason) app.showJoinError("roomNotFound");
|
|
194
198
|
}
|
|
@@ -200,10 +204,11 @@ export function initRooms(app) {
|
|
|
200
204
|
|
|
201
205
|
app.startRoomWatcher = () => {
|
|
202
206
|
clearTimeout(app.state.watcherTimer);
|
|
203
|
-
if (!app.state.rooms.size) return;
|
|
207
|
+
if (!app.state.rooms.size && !app.state.restorePending?.size && !app.state.restoreRetry) return;
|
|
204
208
|
app.state.watcherTimer = setTimeout(async () => {
|
|
205
209
|
const inactive = [...app.state.rooms.keys()].filter((id) => id !== app.state.room?.id);
|
|
206
210
|
await bounded(inactive, 3, (roomId) => watchRoom(roomId, app));
|
|
211
|
+
if (app.state.restorePending?.size || app.state.restoreRetry) void app.refreshRoomList();
|
|
207
212
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
208
213
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
209
214
|
app.startRoomWatcher();
|
|
@@ -214,8 +219,9 @@ export function initRooms(app) {
|
|
|
214
219
|
const empty = $("#roomListEmpty"), chatEmpty = $("#roomListChatEmpty");
|
|
215
220
|
try {
|
|
216
221
|
const rooms = await app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`);
|
|
222
|
+
app.state.restoreRetry = false;
|
|
217
223
|
app.state.availableRooms = rooms;
|
|
218
|
-
if (!app.state.restored) await app.restoreJoinedRooms(rooms);
|
|
224
|
+
if (!app.state.restored || app.state.restorePending?.size) await app.restoreJoinedRooms(rooms);
|
|
219
225
|
else {
|
|
220
226
|
syncCachedRooms(rooms, app);
|
|
221
227
|
await app.discoverDirectRooms(rooms);
|
|
@@ -232,6 +238,11 @@ export function initRooms(app) {
|
|
|
232
238
|
empty.hidden = false;
|
|
233
239
|
chatEmpty.hidden = false;
|
|
234
240
|
}
|
|
241
|
+
if (!app.state.restored) {
|
|
242
|
+
app.state.restoreRetry = true;
|
|
243
|
+
app.state.restorePending = new Set([...app.state.joinedIds, LS.roomId].filter(Boolean));
|
|
244
|
+
app.startRoomWatcher();
|
|
245
|
+
}
|
|
235
246
|
}
|
|
236
247
|
};
|
|
237
248
|
|
|
@@ -244,8 +255,9 @@ export function initRooms(app) {
|
|
|
244
255
|
try {
|
|
245
256
|
const activeId = LS.roomId;
|
|
246
257
|
const directIds = rooms.filter((room) => room.kind === "direct" && room.directSessionIDs?.includes(LS.sessionID)).map((room) => room.id);
|
|
247
|
-
const candidates = [...new Set([...app.state.joinedIds, ...directIds])];
|
|
258
|
+
const candidates = [...new Set([activeId, ...rooms.filter((room) => room.joined).map((room) => room.id), ...app.state.joinedIds, ...directIds].filter(Boolean))];
|
|
248
259
|
const valid = new Set();
|
|
260
|
+
const unresolved = new Set();
|
|
249
261
|
await bounded(candidates, 3, async (roomId) => {
|
|
250
262
|
try {
|
|
251
263
|
const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
@@ -254,18 +266,24 @@ export function initRooms(app) {
|
|
|
254
266
|
if (!me) return;
|
|
255
267
|
valid.add(roomId);
|
|
256
268
|
app.ensureJoinedRoom(room, me.name);
|
|
257
|
-
} catch {
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.status !== 404) {
|
|
271
|
+
unresolved.add(roomId);
|
|
272
|
+
if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
258
275
|
});
|
|
259
|
-
app.state.joinedIds = valid;
|
|
276
|
+
app.state.joinedIds = new Set([...valid, ...unresolved]);
|
|
277
|
+
app.state.restorePending = unresolved;
|
|
260
278
|
app.saveJoinedIds();
|
|
261
|
-
app.state.restored =
|
|
279
|
+
app.state.restored = unresolved.size === 0;
|
|
262
280
|
if (activeId && valid.has(activeId)) app.activateRoom(activeId);
|
|
281
|
+
else if (activeId && unresolved.has(activeId)) app.showJoin(false);
|
|
263
282
|
else {
|
|
264
283
|
LS.roomId = "";
|
|
265
|
-
LS.name = "";
|
|
266
284
|
const fallback = valid.values().next().value;
|
|
267
285
|
if (fallback) app.activateRoom(fallback);
|
|
268
|
-
else app.showJoin();
|
|
286
|
+
else app.showJoin(false);
|
|
269
287
|
}
|
|
270
288
|
app.startRoomWatcher();
|
|
271
289
|
} finally { app.state.restoring = false; }
|
|
@@ -278,8 +296,18 @@ export function initRooms(app) {
|
|
|
278
296
|
const members = await app.api(`/rooms/${encodeURIComponent(room.id)}/members`);
|
|
279
297
|
const me = members.find((member) => member.sessionID === LS.sessionID);
|
|
280
298
|
if (me) app.ensureJoinedRoom(room, me.name);
|
|
281
|
-
} catch {
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.status !== 404) {
|
|
301
|
+
app.state.restorePending ||= new Set();
|
|
302
|
+
app.state.restorePending.add(room.id);
|
|
303
|
+
app.state.joinedIds.add(room.id);
|
|
304
|
+
app.saveJoinedIds();
|
|
305
|
+
app.state.restored = false;
|
|
306
|
+
if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
282
309
|
});
|
|
310
|
+
if (app.state.restorePending?.size) app.startRoomWatcher();
|
|
283
311
|
};
|
|
284
312
|
|
|
285
313
|
app.renderRoomOptions = (list, rooms) => {
|
|
@@ -306,8 +334,7 @@ export function initRooms(app) {
|
|
|
306
334
|
meta.textContent = app.t("roomMeta", { members: shownRoom.participants.length, count: shownRoom.messages.length });
|
|
307
335
|
const preview = document.createElement("span");
|
|
308
336
|
preview.className = "r-preview";
|
|
309
|
-
|
|
310
|
-
preview.textContent = entry ? lastMessage : "";
|
|
337
|
+
preview.textContent = entry ? formatRoomPreview(entry, room.messages.at(-1), app) : "";
|
|
311
338
|
const status = document.createElement("span");
|
|
312
339
|
status.className = "r-status";
|
|
313
340
|
app.setText(status, entry ? "joined" : "joinAction");
|
|
@@ -398,12 +425,12 @@ function syncCachedRooms(rooms, app) {
|
|
|
398
425
|
const remote = new Map(rooms.map((room) => [room.id, room]));
|
|
399
426
|
for (const [roomId, entry] of app.state.rooms) {
|
|
400
427
|
const fresh = remote.get(roomId);
|
|
401
|
-
if (!fresh) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
|
|
428
|
+
if (!fresh || fresh.joined === false) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
|
|
402
429
|
if (app.state.room?.id === roomId) continue;
|
|
403
430
|
const messages = new Map([...entry.room.messages, ...fresh.messages].map((message) => [message.id, message]));
|
|
404
431
|
entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
405
432
|
const latest = entry.room.messages.at(-1);
|
|
406
|
-
if (latest)
|
|
433
|
+
if (latest) setRoomPreview(entry, latest);
|
|
407
434
|
}
|
|
408
435
|
}
|
|
409
436
|
|
|
@@ -412,19 +439,22 @@ async function watchRoom(roomId, app) {
|
|
|
412
439
|
if (!entry || app.state.room?.id === roomId) return;
|
|
413
440
|
try {
|
|
414
441
|
const query = new URLSearchParams({ sessionID: app.LS.sessionID, roomId, excludeSelf: "0", timeout: "0" });
|
|
442
|
+
query.set("afterTs", String(entry.receivedTs || 0));
|
|
415
443
|
const result = await app.api(`/inbox?${query}`);
|
|
416
444
|
if (app.state.rooms.get(roomId) !== entry) return;
|
|
417
|
-
if (
|
|
445
|
+
if (result.member === false) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
|
|
446
|
+
if (result.member !== true || !Array.isArray(result.items)) return;
|
|
418
447
|
if (app.state.room?.id === roomId) return;
|
|
448
|
+
const previousReceivedTs = entry.receivedTs || 0;
|
|
419
449
|
const sawSystem = (result.items || []).some((message) => message.senderId === "system");
|
|
420
450
|
for (const message of result.items || []) {
|
|
421
451
|
if (!entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
422
452
|
if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
|
|
423
453
|
if (message.createdAt >= entry.previewAt) {
|
|
424
|
-
entry
|
|
425
|
-
entry.previewAt = message.createdAt;
|
|
454
|
+
setRoomPreview(entry, message);
|
|
426
455
|
}
|
|
427
456
|
}
|
|
457
|
+
entry.receivedTs = (result.items || []).reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
428
458
|
if (sawSystem || result.hasMore) {
|
|
429
459
|
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
430
460
|
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
@@ -432,10 +462,11 @@ async function watchRoom(roomId, app) {
|
|
|
432
462
|
const messages = new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message]));
|
|
433
463
|
entry.room.messages = [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
|
|
434
464
|
const newest = latest.messages.at(-1);
|
|
435
|
-
if (newest && newest.createdAt >= entry.previewAt)
|
|
465
|
+
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
436
466
|
}
|
|
437
467
|
entry.unreadOverflow = Boolean(result.hasMore);
|
|
438
468
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
469
|
+
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
439
470
|
} catch (error) {
|
|
440
471
|
if (error.status === 401) app.openChatSettings();
|
|
441
472
|
else if (error.status === 404) await app.removeJoinedRoom(roomId, { reason: false });
|
|
@@ -3,7 +3,10 @@ export const app = {
|
|
|
3
3
|
state: {
|
|
4
4
|
room: null, myName: "", unread: 0, drafts: new Map(), rooms: new Map(),
|
|
5
5
|
pollGeneration: 0, navigationGeneration: 0, draftRevision: new Map(), memberSessions: new Map(),
|
|
6
|
-
retryingFailedIds: new Set(), pollController: null,
|
|
6
|
+
retryingFailedIds: new Set(), pollController: null, memberRefreshTimer: 0, receiptRefreshTimer: 0, receiptObservationFrame: 0,
|
|
7
|
+
receiptObservation: null,
|
|
8
|
+
memberApiUnavailable: new Set(), receiptApiUnavailable: new Set(),
|
|
9
|
+
receipts: new Map(), acknowledgedMessages: new Map(), pendingAcknowledgements: new Map(),
|
|
7
10
|
pendingAction: null, watcherTimer: 0, restored: false,
|
|
8
11
|
},
|
|
9
12
|
rendered: 0,
|
|
@@ -26,7 +29,16 @@ export function createRandomId() {
|
|
|
26
29
|
|
|
27
30
|
export function createAuth(storage, fetcher, translate = (key) => key, sessionStore) {
|
|
28
31
|
const memory = Object.create(null);
|
|
29
|
-
let
|
|
32
|
+
let browserIdentity, identityPersistent = false, identityConflict = false;
|
|
33
|
+
const identityKey = "chat.browserIdentity";
|
|
34
|
+
const validSessionID = (id) => typeof id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id);
|
|
35
|
+
const parseIdentity = (value) => {
|
|
36
|
+
try {
|
|
37
|
+
const identity = JSON.parse(value);
|
|
38
|
+
return validSessionID(identity?.sessionID) && typeof identity.name === "string" && identity.name.length <= 64
|
|
39
|
+
? { sessionID: identity.sessionID, name: identity.name } : undefined;
|
|
40
|
+
} catch { return undefined; }
|
|
41
|
+
};
|
|
30
42
|
const read = (key) => {
|
|
31
43
|
if (Object.hasOwn(memory, key)) return memory[key];
|
|
32
44
|
try { return (storage ?? globalThis.localStorage).getItem(key); } catch { return null; }
|
|
@@ -50,19 +62,63 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
50
62
|
else store.setItem(key, value);
|
|
51
63
|
} catch { /* Tab-scoped state is best effort. */ }
|
|
52
64
|
};
|
|
65
|
+
const syncTabIdentity = () => {
|
|
66
|
+
writeSession("chat.sessionID", browserIdentity.sessionID);
|
|
67
|
+
writeSession("chat.name", browserIdentity.name || null);
|
|
68
|
+
};
|
|
69
|
+
const ensureIdentity = () => {
|
|
70
|
+
if (browserIdentity) return browserIdentity;
|
|
71
|
+
let store;
|
|
72
|
+
try {
|
|
73
|
+
store = storage ?? globalThis.localStorage;
|
|
74
|
+
const canonical = parseIdentity(store.getItem(identityKey));
|
|
75
|
+
if (canonical) { browserIdentity = canonical; identityPersistent = true; syncTabIdentity(); return canonical; }
|
|
76
|
+
} catch { /* Keep this tab's identity in memory when storage is blocked. */ }
|
|
77
|
+
const previousID = readSession("chat.sessionID");
|
|
78
|
+
browserIdentity = { sessionID: validSessionID(previousID) ? previousID : createRandomId(), name: validSessionID(previousID) ? (readSession("chat.name") || "").slice(0, 64) : "" };
|
|
79
|
+
syncTabIdentity();
|
|
80
|
+
try {
|
|
81
|
+
store ||= storage ?? globalThis.localStorage;
|
|
82
|
+
store.setItem(identityKey, JSON.stringify(browserIdentity));
|
|
83
|
+
const saved = parseIdentity(store.getItem(identityKey));
|
|
84
|
+
if (saved?.sessionID === browserIdentity.sessionID) { browserIdentity = saved; identityPersistent = true; }
|
|
85
|
+
else if (saved) identityConflict = true;
|
|
86
|
+
} catch { /* This page keeps its in-memory identity without claiming persistence. */ }
|
|
87
|
+
return browserIdentity;
|
|
88
|
+
};
|
|
89
|
+
const identityError = () => {
|
|
90
|
+
const error = new Error(translate("identityChanged"));
|
|
91
|
+
error.identityConflict = true;
|
|
92
|
+
return error;
|
|
93
|
+
};
|
|
94
|
+
const assertIdentity = () => {
|
|
95
|
+
ensureIdentity();
|
|
96
|
+
if (identityConflict) throw identityError();
|
|
97
|
+
try {
|
|
98
|
+
const current = parseIdentity((storage ?? globalThis.localStorage).getItem(identityKey));
|
|
99
|
+
if (current && current.sessionID !== browserIdentity.sessionID || identityPersistent && !current) {
|
|
100
|
+
identityConflict = true;
|
|
101
|
+
throw identityError();
|
|
102
|
+
}
|
|
103
|
+
if (current) identityPersistent = true;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error?.identityConflict) throw error;
|
|
106
|
+
identityPersistent = false;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const saveIdentity = () => {
|
|
110
|
+
if (!identityPersistent) return;
|
|
111
|
+
try {
|
|
112
|
+
const store = storage ?? globalThis.localStorage;
|
|
113
|
+
const current = parseIdentity(store.getItem(identityKey));
|
|
114
|
+
if (current?.sessionID !== browserIdentity.sessionID) { identityConflict = true; return; }
|
|
115
|
+
store.setItem(identityKey, JSON.stringify(browserIdentity));
|
|
116
|
+
if (parseIdentity(store.getItem(identityKey))?.sessionID !== browserIdentity.sessionID) identityConflict = true;
|
|
117
|
+
} catch { /* Keep the preferred name in memory when persistence is blocked. */ }
|
|
118
|
+
};
|
|
53
119
|
const auth = {
|
|
54
120
|
get sessionID() {
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
const store = sessionStore ?? globalThis.sessionStorage;
|
|
58
|
-
memorySessionID = store.getItem("chat.sessionID") || "";
|
|
59
|
-
} catch { /* Keep one identity in memory when tab storage is blocked. */ }
|
|
60
|
-
if (!memorySessionID) {
|
|
61
|
-
memorySessionID = createRandomId();
|
|
62
|
-
try { (sessionStore ?? globalThis.sessionStorage).setItem("chat.sessionID", memorySessionID); }
|
|
63
|
-
catch { /* In-memory identity remains stable. */ }
|
|
64
|
-
}
|
|
65
|
-
return memorySessionID;
|
|
121
|
+
return ensureIdentity().sessionID;
|
|
66
122
|
},
|
|
67
123
|
get roomId() {
|
|
68
124
|
const active = readSession("chat.roomId");
|
|
@@ -72,8 +128,8 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
72
128
|
return legacy || "";
|
|
73
129
|
},
|
|
74
130
|
set roomId(value) { writeSession("chat.roomId", value || null); write("chat.roomId", null); },
|
|
75
|
-
get name() { return
|
|
76
|
-
set name(value) {
|
|
131
|
+
get name() { return ensureIdentity().name; },
|
|
132
|
+
set name(value) { ensureIdentity(); browserIdentity.name = String(value ?? "").slice(0, 64); writeSession("chat.name", browserIdentity.name || null); saveIdentity(); },
|
|
77
133
|
get token() { return read("chat.token") || ""; }, set token(value) { write("chat.token", value || null); },
|
|
78
134
|
get locale() { return read("chat.locale") || "en"; }, set locale(value) { write("chat.locale", value || null); },
|
|
79
135
|
get joinedRoomIds() {
|
|
@@ -99,6 +155,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
99
155
|
};
|
|
100
156
|
const saveToken = (value) => { auth.token = String(value ?? "").trim(); return auth.token; };
|
|
101
157
|
const api = async (url, options = {}) => {
|
|
158
|
+
assertIdentity();
|
|
102
159
|
const headers = { ...options.headers };
|
|
103
160
|
if (options.body) headers["Content-Type"] = "application/json";
|
|
104
161
|
if (auth.token) headers.Authorization = `Bearer ${auth.token}`;
|
|
@@ -110,6 +167,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
110
167
|
throw error;
|
|
111
168
|
}
|
|
112
169
|
const data = await response.json().catch(() => ({}));
|
|
170
|
+
assertIdentity();
|
|
113
171
|
if (!response.ok) {
|
|
114
172
|
const error = new Error(data.error || translate("requestFailed", { status: response.status }));
|
|
115
173
|
error.status = response.status;
|
|
@@ -146,6 +204,7 @@ const messages = {
|
|
|
146
204
|
earlierMessages: "Earlier messages omitted", you: "You", saved: "Saved",
|
|
147
205
|
savedMemory: "Saved for this tab only", copyFailed: ({ id }) => `Copy failed. Copy manually: ${id}`,
|
|
148
206
|
copyCode: "Copy code", copiedCode: "Copied", copyCodeFailed: "Could not copy code. Select and copy it manually.",
|
|
207
|
+
identityChanged: "This browser identity changed in another tab. Reload this tab before continuing.",
|
|
149
208
|
networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
|
|
150
209
|
roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
|
|
151
210
|
networkRetry: "Unable to connect to the server. Check your network and try again.",
|
|
@@ -162,7 +221,11 @@ const messages = {
|
|
|
162
221
|
deleteRoom: "Delete room", deleteConfirm: ({ name }) => `Delete “${name}” and all its messages? This cannot be undone.`,
|
|
163
222
|
allMembers: "Everyone", messageCount: ({ count }) => `${count} / 2000`,
|
|
164
223
|
privacyNote: "Anyone with the shared token can read direct messages and manage rooms; the server can read them too.",
|
|
165
|
-
systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`,
|
|
224
|
+
systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`, systemRemoved: ({ name }) => `${name} was removed from the room`,
|
|
225
|
+
activity_working: "Working", activity_idle: "Foreground idle", activity_waiting: "Waiting", activity_unknown: "Status unknown", activity_offline: "Status stale",
|
|
226
|
+
activityHint_working: "The agent reports active work.", activityHint_idle: "Foreground is idle; background work may continue.", activityHint_waiting: "The agent reports that it is waiting.", activityHint_unknown: "No activity report is available.", activityHint_offline: "The last status is stale; this does not prove the agent is offline.",
|
|
227
|
+
receiptCount: ({ count }) => `Read by ${count}`, departedMember: "left",
|
|
228
|
+
receiptEvidence_displayed: "Shown on screen", receiptEvidence_tool: "Fetched with room tool", receiptEvidence_context: "Full message reached agent context preparation (not proof of understanding)",
|
|
166
229
|
},
|
|
167
230
|
"zh-CN": {
|
|
168
231
|
brand: "闲叙", documentTitle: "闲叙 · 轻量聊天室", roomTitle: ({ name }) => `${name} · 闲叙`,
|
|
@@ -185,6 +248,7 @@ const messages = {
|
|
|
185
248
|
today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", you: "我", saved: "已保存",
|
|
186
249
|
savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
|
|
187
250
|
copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
|
|
251
|
+
identityChanged: "此浏览器身份已在另一个标签页中更改,请重新加载此标签页后继续。",
|
|
188
252
|
networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
|
|
189
253
|
roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
|
|
190
254
|
networkRetry: "无法连接服务器,请检查网络后重试", joinFailed: ({ message }) => `加入失败:${message}`,
|
|
@@ -198,7 +262,11 @@ const messages = {
|
|
|
198
262
|
deleteRoom: "删除房间", deleteConfirm: ({ name }) => `删除“${name}”及全部聊天记录?此操作无法撤销。`,
|
|
199
263
|
allMembers: "所有人", messageCount: ({ count }) => `${count} / 2000`,
|
|
200
264
|
privacyNote: "持有共享令牌的人都可以读取私聊内容和管理房间;服务器也可以读取私聊内容。",
|
|
201
|
-
systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`,
|
|
265
|
+
systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`, systemRemoved: ({ name }) => `${name} 被移出了房间`,
|
|
266
|
+
activity_working: "工作中", activity_idle: "前台空闲", activity_waiting: "等待中", activity_unknown: "状态未知", activity_offline: "状态已过期",
|
|
267
|
+
activityHint_working: "Agent 正在报告工作状态。", activityHint_idle: "前台空闲;后台任务仍可能继续。", activityHint_waiting: "Agent 正在报告等待状态。", activityHint_unknown: "暂无活动状态报告。", activityHint_offline: "最近的状态已过期;这不能证明 Agent 已离线。",
|
|
268
|
+
receiptCount: ({ count }) => `已读 ${count} 人`, departedMember: "已离开",
|
|
269
|
+
receiptEvidence_displayed: "已显示在屏幕上", receiptEvidence_tool: "通过房间工具读取", receiptEvidence_context: "完整消息已进入 Agent 上下文准备阶段(不代表已理解)",
|
|
202
270
|
},
|
|
203
271
|
};
|
|
204
272
|
|