@alexsun-top/opencode-chat-room 0.5.0 → 0.5.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +23 -7
  3. package/README.zh-CN.md +23 -7
  4. package/docs/administrator-rooms.md +51 -0
  5. package/package.json +11 -2
  6. package/plugin.ts +29 -12
  7. package/server/admin-auth.ts +16 -0
  8. package/server/admin-plan-routes.ts +79 -0
  9. package/server/admin-routes.ts +154 -0
  10. package/server/admin-scheduler.ts +42 -0
  11. package/server/admin-state.ts +61 -0
  12. package/server/admin-task-routes.ts +182 -0
  13. package/server/assets/base.css +55 -43
  14. package/server/assets/chat/admin.js +223 -0
  15. package/server/assets/chat/attachments.js +240 -0
  16. package/server/assets/chat/editor.js +211 -0
  17. package/server/assets/chat/events.js +34 -10
  18. package/server/assets/chat/index.js +8 -0
  19. package/server/assets/chat/markdown.js +1 -12
  20. package/server/assets/chat/members.js +1 -1
  21. package/server/assets/chat/mentions.js +38 -28
  22. package/server/assets/chat/message-window.js +18 -0
  23. package/server/assets/chat/messages.js +64 -46
  24. package/server/assets/chat/questions.js +113 -41
  25. package/server/assets/chat/receipts.js +0 -1
  26. package/server/assets/chat/reminders.js +101 -0
  27. package/server/assets/chat/replies.js +149 -0
  28. package/server/assets/chat/rooms.js +30 -10
  29. package/server/assets/chat/state.js +68 -18
  30. package/server/assets/conversation.css +111 -45
  31. package/server/assets/responsive.css +83 -28
  32. package/server/chat-server.ts +23 -6
  33. package/server/chat.html +82 -31
  34. package/server/inbox.ts +5 -1
  35. package/server/newrooms.ts +27 -10
  36. package/server/resource-routes.ts +3 -0
  37. package/server/room-reminders.ts +212 -0
  38. package/server/wake.ts +11 -15
  39. package/skills/chatroom/SKILL.md +21 -1
  40. package/src/admin-client.ts +130 -0
  41. package/src/admin-credentials.ts +58 -0
  42. package/src/agent-receipts.ts +13 -18
  43. package/src/center-client.ts +1 -1
  44. package/src/center-inbox.ts +2 -0
  45. package/src/plugin-notifications.ts +4 -0
  46. package/src/queue.ts +7 -2
  47. package/src/reminder-client.ts +50 -0
  48. package/src/resource-read.ts +118 -0
  49. package/src/resources.ts +1 -1
  50. package/src/sqlite-state.ts +89 -21
  51. package/src/store.ts +22 -8
  52. package/src/supervision-inbox.ts +62 -0
  53. package/src/v1-plugin.ts +13 -3
  54. package/src/v2-plugin.ts +24 -7
@@ -0,0 +1,149 @@
1
+ import { LS } from "./state.js";
2
+ import { replaceEditorRange, setEditorSelection, setCaret } from "./editor.js";
3
+
4
+ export function initReplies(app) {
5
+ const $ = app.$, targets = new Map(Object.entries(LS.replyDrafts || {}).filter(([, item]) => validTarget(item)));
6
+ app.replyTargetFor = (roomId) => targets.get(roomId);
7
+ app.setReplyTarget = (roomId, target) => {
8
+ if (validTarget(target)) targets.set(roomId, target); else targets.delete(roomId);
9
+ LS.replyDrafts = Object.fromEntries(targets);
10
+ if (app.state.room?.id === roomId) app.renderReplyPreview();
11
+ };
12
+ app.clearReplyTarget = (roomId) => app.setReplyTarget(roomId, null);
13
+ app.renderReplyPreview = () => {
14
+ const roomId = app.state.room?.id, target = roomId && targets.get(roomId), box = $("#replyPreview");
15
+ const questionToggle = $("#questionToggle");
16
+ questionToggle.disabled = Boolean(target);
17
+ if (target && questionToggle.checked) { questionToggle.checked = false; questionToggle.dispatchEvent(new Event("change")); }
18
+ box.hidden = !target;
19
+ if (!target) return;
20
+ $("#replyPreviewName").textContent = senderName(target, app);
21
+ $("#replyPreviewText").textContent = excerpt(target.text);
22
+ };
23
+ $("#replyCancel").addEventListener("click", () => cancelReply(app));
24
+ bindMessageActions(app);
25
+ }
26
+
27
+ function validTarget(item) {
28
+ return item && typeof item.id === "string" && typeof item.text === "string" && typeof item.senderId === "string";
29
+ }
30
+ function excerpt(text) { return String(text).replace(/<at>@([^<]+)<\/at>/g, "@$1").replace(/\s+/g, " ").trim().slice(0, 180); }
31
+
32
+ function bindMessageActions(app) {
33
+ const $ = app.$;
34
+ const render = app.renderMessage;
35
+ app.renderMessage = (message, live) => {
36
+ const row = render(message, live);
37
+ if (message.senderId === "system") return row;
38
+ if (message.answerToMessageID) row.querySelector(".msg-meta")?.after(quoteButton(message, app));
39
+ const copy = row.querySelector("[data-copy-message]");
40
+ if (copy) {
41
+ const actions = document.createElement("div"), reply = document.createElement("button");
42
+ actions.className = "message-actions";
43
+ reply.type = "button"; reply.className = "message-reply"; reply.textContent = app.t("replyMessage"); reply.dataset.i18n = "replyMessage";
44
+ reply.setAttribute("aria-label", app.t("replyMessage")); reply.dataset.i18nAriaLabel = "replyMessage"; reply.dataset.replyMessage = message.id;
45
+ copy.before(actions); actions.append(copy, reply);
46
+ }
47
+ return row;
48
+ };
49
+ $("#msgList").addEventListener("click", (event) => {
50
+ const button = event.target.closest?.("[data-reply-message], [data-reply-target-id]");
51
+ if (!button || !app.state.room) return;
52
+ const room = app.state.room, id = button.dataset.replyMessage || button.dataset.replyTargetId;
53
+ if (button.dataset.replyMessage) selectReply(app.state.room.messages.find((item) => item.id === id), app);
54
+ else void jumpToOriginal(room.id, id, app);
55
+ });
56
+ }
57
+
58
+ function selectReply(message, app) {
59
+ if (!message || !app.state.room) return;
60
+ const roomId = app.state.room.id;
61
+ removeAutoMention(app.replyTargetFor(roomId), app.$("#msgInput"));
62
+ const target = { id: message.id, text: message.text, senderId: message.senderId, senderSessionID: message.senderSessionID, isQuestion: Boolean(message.isQuestion) };
63
+ const name = uniqueAuthor(message, app);
64
+ const input = app.$("#msgInput");
65
+ if (name && !input.value.includes(`<at>@${name}</at>`)) {
66
+ const prefix = `<at>@${name}</at> `;
67
+ target.autoMention = name;
68
+ replaceEditorRange(input, 0, 0, prefix); input.setCaret(prefix.length);
69
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
70
+ }
71
+ const toggle = app.$("#questionToggle"); toggle.checked = false; toggle.dispatchEvent(new Event("change"));
72
+ app.setReplyTarget(roomId, target);
73
+ input.focus({ preventScroll: true });
74
+ }
75
+
76
+ function cancelReply(app) {
77
+ const roomId = app.state.room?.id, target = roomId && app.replyTargetFor(roomId);
78
+ if (!roomId || !target) return;
79
+ removeAutoMention(target, app.$("#msgInput"));
80
+ app.clearReplyTarget(roomId);
81
+ }
82
+
83
+ function removeAutoMention(target, input) {
84
+ const prefix = target?.autoMention && `<at>@${target.autoMention}</at> `;
85
+ if (prefix && input.value.startsWith(prefix)) {
86
+ setEditorSelection(input, 0, prefix.length); getSelection().deleteFromDocument(); setCaret(input, 0);
87
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
88
+ }
89
+ }
90
+
91
+ function uniqueAuthor(message, app) {
92
+ const members = app.state.memberSessions.get(app.state.room?.id) || [];
93
+ const matches = message.senderSessionID ? members.filter((item) => item.sessionID === message.senderSessionID)
94
+ : members.filter((item) => item.name === message.senderId);
95
+ const name = matches[0]?.name;
96
+ return matches.length === 1 && members.filter((item) => item.name === name).length === 1 && matches[0].sessionID !== LS.sessionID && name !== "all" ? name : "";
97
+ }
98
+
99
+ function senderName(message, app) {
100
+ if (message.senderSessionID === LS.sessionID) return app.t("you");
101
+ const members = app.state.memberSessions.get(app.state.room?.id) || [];
102
+ const match = message.senderSessionID && members.find((item) => item.sessionID === message.senderSessionID);
103
+ if (match) return match.name;
104
+ return message.senderId || app.t("guest");
105
+ }
106
+
107
+ function quoteButton(message, app) {
108
+ const button = document.createElement("button"), targetId = message.answerToMessageID;
109
+ const original = app.state.room.messages.find((item) => item.id === targetId);
110
+ button.type = "button"; button.className = "reply-quote"; button.dataset.replyTargetId = targetId;
111
+ button.setAttribute("aria-label", app.t("replyOpenOriginal")); button.dataset.i18nAriaLabel = "replyOpenOriginal";
112
+ button.textContent = original ? `${senderName(original, app)} · ${excerpt(original.text)}` : app.t("replyOpenOriginal");
113
+ return button;
114
+ }
115
+
116
+ async function jumpToOriginal(roomId, messageId, app) {
117
+ const generation = app.state.navigationGeneration;
118
+ let entry = app.state.rooms.get(roomId), room = entry?.room;
119
+ if (!entry || !room) return;
120
+ let original = room.messages.find((item) => item.id === messageId), beforeSeq;
121
+ try {
122
+ while (!original) {
123
+ const query = new URLSearchParams({ limit: "100" });
124
+ if (beforeSeq) query.set("beforeSeq", String(beforeSeq));
125
+ const page = await app.api(`/rooms/${encodeURIComponent(roomId)}/history?${query}`);
126
+ entry = app.state.rooms.get(roomId); if (!entry) return;
127
+ room = entry.room;
128
+ original = (page.messages || []).find((item) => item.id === messageId);
129
+ const merged = new Map([...room.messages, ...(page.messages || []).map((item) => ({ ...item, roomId }))].map((item) => [item.id, item]));
130
+ room.messages = [...merged.values()].sort((left, right) => left.createdAt - right.createdAt);
131
+ if (original || !page.hasMore || !page.nextBeforeSeq || page.nextBeforeSeq === beforeSeq) break;
132
+ beforeSeq = page.nextBeforeSeq;
133
+ }
134
+ } catch { return; }
135
+ if (!original) return markUnavailable(messageId, roomId, app);
136
+ app.state.positions.set(roomId, { messageId, offset: 0 }); app.savePosition(roomId, { messageId, offset: 0 });
137
+ if (app.state.room?.id === roomId && app.state.navigationGeneration === generation) {
138
+ app.state.room = app.state.rooms.get(roomId)?.room || room; app.rerenderMessages();
139
+ document.querySelector(`[data-msg-id="${CSS.escape(messageId)}"]`)?.scrollIntoView({ block: "center" });
140
+ }
141
+ const quote = document.querySelector(`[data-reply-target-id="${CSS.escape(messageId)}"]`);
142
+ if (quote) quote.textContent = `${senderName(original, app)} · ${excerpt(original.text)}`;
143
+ }
144
+
145
+ function markUnavailable(messageId, roomId, app) {
146
+ if (app.state.room?.id !== roomId) return;
147
+ const quote = document.querySelector(`[data-reply-target-id="${CSS.escape(messageId)}"]`);
148
+ if (quote) { quote.textContent = app.t("replyOriginalUnavailable"); quote.disabled = true; }
149
+ }
@@ -1,19 +1,24 @@
1
1
  import { LS } from "./state.js";
2
+ import { isOwnMessage } from "./messages.js";
2
3
  import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
3
4
 
4
5
  export function initRooms(app) {
5
6
  const $ = app.$;
6
7
 
7
8
  app.showJoin = (refresh = true) => {
9
+ document.documentElement.classList.remove("session-restore");
8
10
  if (!$("#inName").value) $("#inName").value = LS.name;
9
11
  $("#chatView").hidden = true;
12
+ $("#restoreView").hidden = true;
10
13
  $("#joinView").hidden = false;
11
14
  app.updateTitle();
12
15
  if (refresh) void app.refreshRoomList();
13
16
  $("#inRoomId").focus();
14
17
  };
15
18
  app.showChat = () => {
19
+ document.documentElement.classList.remove("session-restore");
16
20
  $("#joinView").hidden = true;
21
+ $("#restoreView").hidden = true;
17
22
  $("#chatView").hidden = false;
18
23
  };
19
24
  app.renderHead = () => {
@@ -21,7 +26,7 @@ export function initRooms(app) {
21
26
  $("#roomIdShort").textContent = app.state.room.id.slice(0, 8);
22
27
  $("#btnCopyId").title = app.t("copyRoomIdTitle", { id: app.state.room.id });
23
28
  $("#btnCopyId").setAttribute("aria-label", app.t("copyRoomId"));
24
- app.setText($("#railIdentity"), "identityLabel", { name: app.state.myName });
29
+ $("#railIdentity").textContent = app.state.myName;
25
30
  $("#profileAvatar").textContent = Array.from(app.state.myName.trim())[0]?.toLocaleUpperCase() || "?";
26
31
  app.updateTitle();
27
32
  };
@@ -61,7 +66,7 @@ export function initRooms(app) {
61
66
  if (!entry) return;
62
67
  if (app.state.room?.id === roomId) return;
63
68
  if (app.state.room) {
64
- app.saveDraft(app.state.room.id, $("#msgInput").value);
69
+ app.saveDraft(app.state.room.id, $("#msgInput").draftValue);
65
70
  app.captureReadingPosition?.();
66
71
  }
67
72
  app.stopPolling();
@@ -82,8 +87,9 @@ export function initRooms(app) {
82
87
  app.startPolling();
83
88
  app.renderMembers();
84
89
  if (!restoredPosition) $("#thread").scrollTop = typeof savedPosition === "number" ? savedPosition : entry.position || $("#thread").scrollHeight;
85
- $("#msgInput").disabled = false;
86
- $("#msgInput").value = app.state.drafts.get(roomId) || "";
90
+ $("#msgInput").contentEditable = "true";
91
+ $("#msgInput").setAttribute("aria-disabled", "false"); $("#msgInput").tabIndex = 0;
92
+ $("#msgInput").draftValue = app.state.drafts.get(roomId) || ""; app.renderReplyPreview?.();
87
93
  app.renderFailedMessages();
88
94
  app.autoGrow($("#msgInput"));
89
95
  app.updateDraftCount();
@@ -166,19 +172,21 @@ export function initRooms(app) {
166
172
  app.removeJoinedRoom = async (roomId, { leaveServer = false, reason = false } = {}) => {
167
173
  const active = app.state.room?.id === roomId;
168
174
  const entry = app.state.rooms.get(roomId);
175
+ app.disposeRoomAttachments?.(roomId);
169
176
  if (active) {
170
177
  app.state.navigationGeneration++;
171
178
  app.saveDraft(roomId, $("#msgInput").value);
172
179
  app.captureReadingPosition?.();
173
180
  app.stopPolling();
174
181
  app.closeMention();
175
- app.state.room = null;
182
+ app.state.room = null; app.renderReplyPreview?.();
176
183
  app.state.myName = "";
177
184
  app.state.unread = 0;
178
185
  app.rendered = 0;
179
186
  app.firstMessageId = null;
180
187
  $("#msgList").textContent = "";
181
- $("#msgInput").disabled = true;
188
+ $("#msgInput").contentEditable = "false";
189
+ $("#msgInput").setAttribute("aria-disabled", "true"); $("#msgInput").tabIndex = -1;
182
190
  $("#btnSend").disabled = true;
183
191
  }
184
192
  app.state.rooms.delete(roomId);
@@ -235,7 +243,11 @@ export function initRooms(app) {
235
243
  empty.hidden = rooms.length > 0;
236
244
  chatEmpty.hidden = rooms.length > 0;
237
245
  } catch (error) {
238
- if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
246
+ if (error.status === 401) {
247
+ if (!app.state.room && !app.state.restored) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); }
248
+ else app.state.room ? app.openChatSettings() : app.openTokenBox();
249
+ }
250
+ else if (!app.state.restored && !app.state.room) app.showRestoreFailure(app.t("networkRetry"));
239
251
  else {
240
252
  app.setText(empty, "roomListError");
241
253
  app.setText(chatEmpty, "roomListError");
@@ -262,6 +274,7 @@ export function initRooms(app) {
262
274
  const candidates = [...new Set([activeId, ...rooms.filter((room) => room.joined).map((room) => room.id), ...app.state.joinedIds, ...directIds].filter(Boolean))];
263
275
  const valid = new Set();
264
276
  const unresolved = new Set();
277
+ let authFailed = false;
265
278
  await bounded(candidates, 3, async (roomId) => {
266
279
  try {
267
280
  const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
@@ -273,6 +286,7 @@ export function initRooms(app) {
273
286
  } catch (error) {
274
287
  if (error.status !== 404) {
275
288
  unresolved.add(roomId);
289
+ if (error.status === 401) authFailed = true;
276
290
  if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
277
291
  }
278
292
  }
@@ -281,12 +295,16 @@ export function initRooms(app) {
281
295
  app.state.restorePending = unresolved;
282
296
  app.saveJoinedIds();
283
297
  app.state.restored = unresolved.size === 0;
298
+ if (authFailed) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); return; }
284
299
  if (activeId && valid.has(activeId)) app.activateRoom(activeId);
285
- else if (activeId && unresolved.has(activeId)) app.showJoin(false);
300
+ else if (activeId && unresolved.has(activeId)) {
301
+ app.showRestoreFailure(app.t("networkRetry"));
302
+ }
286
303
  else {
287
304
  LS.roomId = "";
288
305
  const fallback = valid.values().next().value;
289
306
  if (fallback) app.activateRoom(fallback);
307
+ else if (unresolved.size) app.showRestoreFailure(app.t("networkRetry"));
290
308
  else app.showJoin(false);
291
309
  }
292
310
  app.startRoomWatcher();
@@ -361,6 +379,7 @@ export function initRooms(app) {
361
379
  document.querySelectorAll(".panel").forEach((panel) => { panel.hidden = true; });
362
380
  $("#btnMembers").setAttribute("aria-expanded", "false");
363
381
  $("#btnSettings").setAttribute("aria-expanded", "false");
382
+ $("#btnRoomOptions").setAttribute("aria-expanded", "false");
364
383
  };
365
384
  app.togglePanel = (selector) => {
366
385
  const panel = $(selector), wasHidden = panel.hidden;
@@ -392,12 +411,13 @@ export function initRooms(app) {
392
411
  try {
393
412
  await app.api(`/rooms/${encodeURIComponent(room.id)}`, {
394
413
  method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }),
414
+ headers: LS.adminToken ? { "X-Chat-Admin-Token": LS.adminToken } : {},
395
415
  });
396
416
  await app.removeJoinedRoom(room.id);
397
417
  app.clearDraft(room.id);
398
418
  app.clearPosition(room.id);
399
419
  app.saveFailedMessages(room.id, []);
400
- } catch (error) { app.showSendError("sendFailed", { message: error.message }); }
420
+ } catch (error) { app.showSendError(error.status === 403 && error.message.includes("operator token required") ? "adminRoomDeleteDenied" : "sendFailed", { message: error.message }); }
401
421
  };
402
422
 
403
423
  app.copyRoomId = async () => {
@@ -453,7 +473,7 @@ async function watchRoom(roomId, app) {
453
473
  const previousReceivedTs = entry.receivedTs || 0;
454
474
  const sawSystem = (result.items || []).some((message) => message.senderId === "system");
455
475
  for (const message of result.items || []) {
456
- if (!entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
476
+ if (!isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
457
477
  if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
458
478
  if (message.createdAt >= entry.previewAt) {
459
479
  setRoomPreview(entry, message);
@@ -132,6 +132,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
132
132
  get name() { return ensureIdentity().name; },
133
133
  set name(value) { ensureIdentity(); browserIdentity.name = String(value ?? "").slice(0, 64); writeSession("chat.name", browserIdentity.name || null); saveIdentity(); },
134
134
  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); },
135
136
  get locale() { return read("chat.locale") || "en"; }, set locale(value) { write("chat.locale", value || null); },
136
137
  get joinedRoomIds() {
137
138
  try {
@@ -144,6 +145,8 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
144
145
  set roomNames(value) { writeSession("chat.roomNames", JSON.stringify(value)); },
145
146
  get drafts() { try { return JSON.parse(readSession("chat.drafts") || "{}"); } catch { return {}; } },
146
147
  set drafts(value) { writeSession("chat.drafts", JSON.stringify(value)); },
148
+ get replyDrafts() { try { return JSON.parse(readSession("chat.replyDrafts") || "{}"); } catch { return {}; } },
149
+ set replyDrafts(value) { writeSession("chat.replyDrafts", JSON.stringify(value)); },
147
150
  get positions() { try { return JSON.parse(readSession("chat.positions") || "{}"); } catch { return {}; } },
148
151
  set positions(value) { writeSession("chat.positions", JSON.stringify(value)); },
149
152
  get readTs() { try { return JSON.parse(readSession("chat.readTs") || "{}"); } catch { return {}; } },
@@ -187,7 +190,13 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
187
190
  const response = await apiResponse(url, options), blob = await response.blob();
188
191
  assertIdentity(); return blob;
189
192
  };
190
- return { LS: auth, saveToken, api, apiBlob };
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 };
191
200
  }
192
201
 
193
202
  const messages = {
@@ -195,6 +204,7 @@ const messages = {
195
204
  brand: "OC Chat", documentTitle: "OC Chat",
196
205
  roomTitle: ({ name }) => `${name} · OC Chat`,
197
206
  tagline: "A lightweight chat room. Enter a room ID to join, or create a new one.",
207
+ restoringSession: "Restoring your session…", retry: "Retry", roomOptions: "Options",
198
208
  languageLabel: "Language", roomIdLabel: "Room ID", roomIdPlaceholder: "Paste or enter a room ID",
199
209
  nameLabel: "Your name", namePlaceholder: "What should we call you?", joinRoom: "Join room",
200
210
  or: "or", newRoomNameLabel: "New room name", newRoomNamePlaceholder: "e.g. Weekend movie night",
@@ -207,28 +217,41 @@ const messages = {
207
217
  members: "Members", membersCount: ({ count }) => `Members (${count})`, noMembers: "No members yet.", profileMenu: "Your profile and settings",
208
218
  questions: "Questions", pendingQuestions: "Pending questions", refreshQuestions: "Refresh",
209
219
  announcements: "Announcements", announcementName: "Name", announcementContent: "Content",
220
+ reminders: "Reminders", reminderSchedule: "Schedule", reminderOnce: "One time", reminderDate: "Date and time",
221
+ reminderCron: "5-field CRON expression", reminderTimezone: "Timezone override (optional)", reminderTimezoneHint: "Leave blank to use the server timezone. An IANA timezone applies to both schedule types. The server rejects one-time times skipped or repeated by daylight-saving changes.",
222
+ reminderText: "Reminder text", reminderTemplateHint: "Use {time}, {initiator}, and {room} in your message.", reminderCreate: "Create reminder",
223
+ reminderLoading: "Loading reminders…", reminderEmpty: "No reminders yet.", reminderPaused: "Paused", reminderNext: ({ time }) => `Next: ${time}`,
224
+ reminderPause: "Pause", reminderResume: "Resume", reminderDelete: "Delete", reminderDeleteConfirm: "Delete this reminder?",
225
+ reminderCreated: "Reminder created.", reminderUpdated: "Reminder updated.", reminderDeleted: "Reminder deleted.",
226
+ reminderInvalid: "Check the date, 5-field CRON expression, IANA timezone, and reminder text.", reminderLoadFailed: "Could not load reminders. Your draft is still here.",
210
227
  diagramLoading: "Rendering diagram…", diagramRenderFailed: "Diagram unavailable; showing its source.", resourceLoading: "Loading file…", resourceFailed: "This file could not be loaded.", resourceDownload: "Download", resourcePreview: "Preview", resourceHide: "Hide preview",
211
228
  announcementDelete: "Delete announcement",
212
229
  announcementNew: "New announcement", announcementEmpty: "No announcements yet.", announcementLoading: "Loading announcements…",
213
230
  announcementLoadFailed: "Could not load announcements. Your draft is still here.", announcementSaved: "Announcement saved.", announcementDeleted: "Announcement deleted.",
214
231
  announcementDuplicate: "That name already exists. Select it to edit, or choose another name.", announcementDeleteConfirm: ({ name }) => `Delete “${name}”?`, announcementCount: ({ count }) => `${count} / 5000`, announcementInvalid: "Use a name of 1–64 characters and content up to 5000 characters.",
215
232
  questionsLoading: "Loading questions…", questionsEmpty: "No unanswered questions.",
216
- questionsFailed: "Could not load questions. Try again.", questionLabel: "Question",
217
- answerQuestion: "Reply", answerPlaceholder: "Write a reply…", sendAnswer: "Send reply",
218
- answerFailed: "Reply failed. Your draft is still here.", questionAlreadyAnswered: "This question was answered elsewhere.",
233
+ questionsFailed: "Could not load questions. Try again.", questionsUnsupported: "Unanswered questions are unavailable on this server.", questionLabel: "Question",
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
+ answerFailed: "Reply failed. Your draft is still here.", answerTooLong: "Reply must be 2,000 characters or fewer.", questionAlreadyAnswered: "This question was answered elsewhere.",
219
236
  sendAsQuestion: "Send as a question",
220
- settings: "Settings", tokenRequired: "The server requires an access token (401).",
237
+ settings: "Settings", adminAccess: "Administration", adminToken: "Administration token", openAdministration: "Open administration", administration: "Administration", designations: "Designations", adminRoom: "Administrator room", targetRoom: "Agent membership room", adminScopeNote: "An administrator manages every room, including this one and rooms created later. The Agent room below is where the selected Agent is a member; it does not limit access.", targetAgent: "Registered agent", designate: "Designate and issue enrollment", 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.", privateEnrollment: ({ expires }) => `Copy this instruction and paste it privately into the selected agent session. Expires ${expires}. Never post it in a room.`, copyEnrollment: "Copy private instruction", enrollmentCopied: "Private instruction copied.", 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}”?`,
221
239
  leave: "Leave", reconnecting: "Connection lost. Retrying…", messageList: "Message list",
222
240
  noMessages: "No messages yet. Say something.", latestMessages: "Back to latest messages",
223
- mentionMembers: "Choose a member to mention", messagePlaceholder: "Message · Enter sends · Shift+Enter adds a line",
241
+ mentionMembers: "Choose a member to mention", messagePlaceholder: "Message · Enter to send",
242
+ attachments: "Attachments", addFiles: "Add files", dropFilesHere: "Drop files here to attach",
243
+ attachmentVolatile: "File attachments are held in this tab and are cleared if you reload.", retryUpload: "Retry", removeFile: "Remove",
244
+ uploadQueued: "Waiting to upload", uploadReady: "Ready to send", uploadPercent: ({ percent }) => `Uploading ${percent}%`,
245
+ uploadFailed: "Upload failed. Retry or remove the file.",
246
+ fileTooLarge: "File exceeds the server's current size limit.",
224
247
  send: "Send", roomMeta: ({ members, count }) => `${members} ${members === 1 ? "member" : "members"} · ${count} ${count === 1 ? "message" : "messages"}`,
225
248
  joinArrow: "Join →", joinDirectTitle: "Click to join directly", mentionEmpty: "No matching members",
226
249
  joined: "Joined", joinAction: "Join room", unreadMessages: ({ count }) => `${count} unread`,
227
250
  mentionHint: "↑↓ Select · Enter to confirm · Esc to close", today: "Today", yesterday: "Yesterday",
228
251
  earlierMessages: "Earlier messages omitted", messagesBetweenOmitted: "Messages between this reading point and latest are omitted.", you: "You", saved: "Saved",
229
252
  savedMemory: "Saved for this tab only", copyFailed: ({ id }) => `Copy failed. Copy manually: ${id}`,
230
- copyCode: "Copy code", copiedCode: "Copied", copyCodeFailed: "Could not copy code. Select and copy it manually.",
231
253
  copyMessage: "Copy", copiedMessage: "Copied", copyMessageFailed: "Could not copy. Select and copy the message manually.",
254
+ replyMessage: "Reply", replyingTo: "Replying to", cancelReply: "Cancel reply", replyOpenOriginal: "View original message", replyOriginalUnavailable: "Original message is unavailable.",
232
255
  identityChanged: "This browser identity changed in another tab. Reload this tab before continuing.",
233
256
  networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
234
257
  roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
@@ -238,6 +261,7 @@ const messages = {
238
261
  roomNotFound: "This room is gone, or you no longer have access.",
239
262
  sendAuth: "Send failed: an access token is required", sendNetwork: "Send failed. Your message is saved below.",
240
263
  sendFailed: ({ message }) => `Send failed: ${message}`,
264
+ adminRoomDeleteDenied: "This room is designated for administration. Enter the Administration token in Settings to delete it.",
241
265
  failedMessages: "Messages not sent", retryFailed: "Retry", discardFailed: "Discard",
242
266
  roomListError: "Unable to load rooms. You can enter a room ID directly.", guest: "Guest",
243
267
  roomsLabel: "Rooms", refreshRooms: "Refresh rooms", identityLabel: ({ name }) => `Chatting as ${name}`,
@@ -251,11 +275,12 @@ const messages = {
251
275
  activity_working: "Working", activity_idle: "Foreground idle", activity_waiting: "Waiting", activity_unknown: "Status unknown", activity_offline: "Status stale",
252
276
  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.",
253
277
  receiptCount: ({ count }) => `Read by ${count}`, receiptNone: "No readers yet", receiptNotLoaded: "Read status not loaded", readerPanelTitle: "Message readers", close: "Close", departedMember: "left",
254
- receiptEvidence_displayed: "Shown on screen", receiptEvidence_tool: "Fetched with room tool", receiptEvidence_context: "Full message reached agent context preparation (not proof of understanding)",
278
+ receiptEvidence_displayed: "Shown on screen", receiptEvidence_tool: "Fetched with room tool", receiptEvidence_context: "In agent context",
255
279
  },
256
280
  "zh-CN": {
257
281
  brand: "OC Chat", documentTitle: "OC Chat", roomTitle: ({ name }) => `${name} · OC Chat`,
258
282
  tagline: "一个轻量的聊天房间。输入房间 ID 加入,或直接新建一个。", languageLabel: "语言",
283
+ restoringSession: "正在恢复会话…", retry: "重试", roomOptions: "选项",
259
284
  roomIdLabel: "房间 ID", roomIdPlaceholder: "粘贴或输入房间 ID", nameLabel: "你的昵称",
260
285
  namePlaceholder: "怎么称呼你", joinRoom: "加入房间", or: "或", newRoomNameLabel: "新房间名称",
261
286
  newRoomNamePlaceholder: "例如:周末电影夜", createRoom: "创建新房间", tokenOptional: "访问令牌(可选)",
@@ -267,26 +292,40 @@ const messages = {
267
292
  membersCount: ({ count }) => `成员 ${count}`, noMembers: "暂无成员", settings: "设置", profileMenu: "个人资料和设置",
268
293
  questions: "提问", pendingQuestions: "待回答的问题", refreshQuestions: "刷新",
269
294
  announcements: "公告栏", announcementName: "名称", announcementContent: "内容",
295
+ reminders: "提醒", reminderSchedule: "计划", reminderOnce: "单次", reminderDate: "日期和时间",
296
+ reminderCron: "5 字段 CRON 表达式", reminderTimezone: "时区覆盖(可选)", reminderTimezoneHint: "留空则使用服务器时区。填写 IANA 时区会应用于两种计划。服务器会拒绝夏令时调整中不存在或重复的单次时间。",
297
+ reminderText: "提醒内容", reminderTemplateHint: "可使用 {time}、{initiator} 和 {room}。", reminderCreate: "创建提醒",
298
+ reminderLoading: "正在加载提醒…", reminderEmpty: "暂无提醒。", reminderPaused: "已暂停", reminderNext: ({ time }) => `下次:${time}`,
299
+ reminderPause: "暂停", reminderResume: "恢复", reminderDelete: "删除", reminderDeleteConfirm: "确定删除此提醒?",
300
+ reminderCreated: "提醒已创建。", reminderUpdated: "提醒已更新。", reminderDeleted: "提醒已删除。",
301
+ reminderInvalid: "请检查日期、5 字段 CRON 表达式、IANA 时区和提醒内容。", reminderLoadFailed: "无法加载提醒,草稿仍已保留。",
270
302
  diagramLoading: "正在渲染图表…", diagramRenderFailed: "图表无法显示,以下为源代码。", resourceLoading: "正在加载文件…", resourceFailed: "无法加载此文件。", resourceDownload: "下载", resourcePreview: "预览", resourceHide: "收起预览",
271
303
  announcementDelete: "删除公告",
272
304
  announcementNew: "新建公告", announcementEmpty: "暂无公告。", announcementLoading: "正在加载公告…",
273
305
  announcementLoadFailed: "无法加载公告,草稿仍已保留。", announcementSaved: "公告已保存。", announcementDeleted: "公告已删除。",
274
306
  announcementDuplicate: "此名称已存在。请选择该公告进行编辑,或使用其他名称。", announcementDeleteConfirm: ({ name }) => `删除“${name}”?`, announcementCount: ({ count }) => `${count} / 5000`, announcementInvalid: "名称需为 1–64 个字符,内容不能超过 5000 个字符。",
275
307
  questionsLoading: "正在加载问题…", questionsEmpty: "没有待回答的问题。",
276
- questionsFailed: "无法加载问题,请重试。", questionLabel: "问题",
277
- answerQuestion: "回复", answerPlaceholder: "写下回复…", sendAnswer: "发送回复",
278
- answerFailed: "回复失败,草稿仍已保留。", questionAlreadyAnswered: "此问题已由其他人回答。",
308
+ questionsFailed: "无法加载问题,请重试。", questionsUnsupported: "此服务器不支持查看待回答问题。", questionLabel: "问题",
309
+ answerQuestion: "回复", answerPlaceholder: "写下回复…", sendAnswer: "发送回复", selectQuestion: "回复此问题", copyQuestion: "复制问题", questionCopied: "问题已复制。", questionCopyFailed: "无法复制问题。",
310
+ answerFailed: "回复失败,草稿仍已保留。", answerTooLong: "回复不能超过 2,000 个字符。", questionAlreadyAnswered: "此问题已由其他人回答。",
279
311
  sendAsQuestion: "作为问题发送",
312
+ adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "管理员可以管理所有房间,包括当前房间和之后创建的房间。下方 Agent 房间只用于选择该 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。", privateEnrollment: ({ expires }) => `复制此指令并私下粘贴到指定的 Agent 会话中。有效期至 ${expires}。请勿发送到房间。`, copyEnrollment: "复制私密指令", enrollmentCopied: "私密指令已复制。", revokeConfirm: "撤销此管理绑定?普通房间会保留。", updateTask: "更新任务", task_pending: "待处理", task_working: "进行中", task_blocked: "受阻", task_completed: "已完成", task_cancelled: "已取消", nextRun: ({ time, minutes }) => `每 ${minutes} 分钟 · 下次 ${time}`, paused: "已暂停", pauseTimer: "暂停", resumeTimer: "恢复", deleteTimer: "删除", deleteTimerConfirm: ({ name }) => `删除定时任务“${name}”?`,
280
314
  tokenRequired: "服务器要求访问令牌(401)。", leave: "离开", reconnecting: "连接中断,正在重试…",
281
315
  messageList: "消息列表", noMessages: "还没有消息,说点什么吧。", latestMessages: "回到最新消息",
282
- mentionMembers: "选择要提及的成员", messagePlaceholder: "输入消息,Enter 发送,Shift+Enter 换行",
316
+ mentionMembers: "选择要提及的成员", messagePlaceholder: "输入消息,Enter 发送",
317
+ attachments: "附件", addFiles: "添加文件", dropFilesHere: "将文件拖到这里添加",
318
+ attachmentVolatile: "附件仅保存在当前标签页,刷新页面后会清除。", retryUpload: "重试", removeFile: "移除",
319
+ uploadQueued: "等待上传", uploadReady: "可以发送", uploadPercent: ({ percent }) => `正在上传 ${percent}%`,
320
+ uploadFailed: "上传失败,请重试或移除文件。",
321
+ fileTooLarge: "文件超过服务器当前大小限制。",
283
322
  send: "发送", roomMeta: ({ members, count }) => `${members} 人 · ${count} 条消息`, joinArrow: "加入 →",
284
323
  joinDirectTitle: "点击直接加入", mentionEmpty: "没有匹配的成员", mentionHint: "↑↓ 选择 · Enter 确认 · Esc 关闭",
285
324
  joined: "已加入", joinAction: "加入房间", unreadMessages: ({ count }) => `${count} 条未读`,
286
325
  today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", messagesBetweenOmitted: "此阅读位置与最新消息之间的部分消息已省略。", you: "我", saved: "已保存",
287
326
  savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
288
- copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
289
327
  copyMessage: "复制", copiedMessage: "已复制", copyMessageFailed: "复制失败,请手动选择并复制消息。",
328
+ replyMessage: "回复", replyingTo: "回复给", cancelReply: "取消回复", replyOpenOriginal: "查看原始消息", replyOriginalUnavailable: "原始消息不可用。",
290
329
  identityChanged: "此浏览器身份已在另一个标签页中更改,请重新加载此标签页后继续。",
291
330
  networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
292
331
  roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
@@ -294,6 +333,7 @@ const messages = {
294
333
  roomNameRequired: "请输入房间名称", createFailed: ({ message }) => `创建失败:${message}`,
295
334
  roomNotFound: "房间不存在,或你已被移出房间", sendAuth: "发送失败:需要访问令牌",
296
335
  sendNetwork: "发送失败,消息已保存在下方", sendFailed: ({ message }) => `发送失败:${message}`,
336
+ adminRoomDeleteDenied: "此房间用于管理。请先在设置中输入管理令牌,再删除房间。",
297
337
  failedMessages: "未发送的消息", retryFailed: "重试", discardFailed: "删除",
298
338
  roomListError: "无法加载房间列表,可直接输入房间 ID 加入。", guest: "访客", roomsLabel: "房间列表",
299
339
  refreshRooms: "刷新房间", identityLabel: ({ name }) => `当前昵称:${name}`, roomsMenu: "打开房间列表", closeRoomList: "关闭房间列表", direct: "私聊",
@@ -305,7 +345,7 @@ const messages = {
305
345
  activity_working: "工作中", activity_idle: "前台空闲", activity_waiting: "等待中", activity_unknown: "状态未知", activity_offline: "状态已过期",
306
346
  activityHint_working: "Agent 正在报告工作状态。", activityHint_idle: "前台空闲;后台任务仍可能继续。", activityHint_waiting: "Agent 正在报告等待状态。", activityHint_unknown: "暂无活动状态报告。", activityHint_offline: "最近的状态已过期;这不能证明 Agent 已离线。",
307
347
  receiptCount: ({ count }) => `已读 ${count} 人`, receiptNone: "尚无人已读", receiptNotLoaded: "尚未加载已读状态", readerPanelTitle: "消息已读情况", close: "关闭", departedMember: "已离开",
308
- receiptEvidence_displayed: "已显示在屏幕上", receiptEvidence_tool: "通过房间工具读取", receiptEvidence_context: "完整消息已进入 Agent 上下文准备阶段(不代表已理解)",
348
+ receiptEvidence_displayed: "已显示在屏幕上", receiptEvidence_tool: "通过房间工具读取", receiptEvidence_context: "进入上下文",
309
349
  },
310
350
  };
311
351
 
@@ -314,10 +354,11 @@ app.t = (key, values = {}) => {
314
354
  const text = typeof entry === "function" ? entry(values) : entry;
315
355
  return String(text).replace(/\{(\w+)\}/g, (_, name) => values[name] ?? "");
316
356
  };
317
- export const { LS, saveToken, api, apiBlob } = createAuth(undefined, undefined, (key, values) => app.t(key, values));
357
+ export const { LS, saveToken, api, apiBlob, adminApi } = createAuth(undefined, undefined, (key, values) => app.t(key, values));
318
358
  app.LS = LS;
319
359
  app.api = api;
320
360
  app.apiBlob = apiBlob;
361
+ app.adminApi = adminApi;
321
362
  app.setToken = saveToken;
322
363
  app.locale = LS.locale === "zh-CN" ? "zh-CN" : "en";
323
364
  app.state.joinedIds = new Set(LS.joinedRoomIds);
@@ -367,7 +408,7 @@ app.applyLocale = () => {
367
408
  ? app.t(element._flashKey)
368
409
  : app.t(element.dataset.i18n, element._i18nValues || {});
369
410
  });
370
- for (const attribute of ["aria-label", "title", "placeholder"]) {
411
+ for (const attribute of ["aria-label", "aria-placeholder", "title", "placeholder"]) {
371
412
  document.querySelectorAll(`[data-i18n-${attribute}]`).forEach((element) => {
372
413
  element.setAttribute(attribute, app.t(element.getAttribute(`data-i18n-${attribute}`), element._i18nValues || {}));
373
414
  });
@@ -407,12 +448,21 @@ app.dayText = (timestamp) => {
407
448
  return new Intl.DateTimeFormat(app.intlLocale(), { month: "short", day: "numeric" }).format(date);
408
449
  };
409
450
  app.flash = (button, key) => {
451
+ const output = button.querySelector("[data-flash-output]");
410
452
  button._flashKey = key;
411
- button.textContent = app.t(key);
453
+ if (output) {
454
+ output._flashKey = key; output.hidden = false; output.textContent = app.t(key);
455
+ button.classList.add("is-flashing");
456
+ if (button.dataset.i18nAriaLabel) button.setAttribute("aria-label", app.t(key));
457
+ } else button.textContent = app.t(key);
412
458
  setTimeout(() => {
413
459
  if (button._flashKey !== key) return;
414
460
  delete button._flashKey;
415
- button.textContent = app.t(button.dataset.i18n, button._i18nValues || {});
461
+ if (output) {
462
+ delete output._flashKey; output.hidden = true; output.textContent = app.t(output.dataset.i18n, output._i18nValues || {});
463
+ button.classList.remove("is-flashing");
464
+ if (button.dataset.i18nAriaLabel) button.setAttribute("aria-label", app.t(button.dataset.i18nAriaLabel));
465
+ } else button.textContent = app.t(button.dataset.i18n, button._i18nValues || {});
416
466
  }, 1200);
417
467
  };
418
468
  app.updateTitle = () => {