@alexsun-top/opencode-chat-room 0.5.2 → 0.5.3
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 +10 -0
- package/README.md +28 -215
- package/README.zh-CN.md +27 -209
- package/docs/administrator-rooms.md +6 -22
- package/package.json +1 -4
- package/plugin.ts +1 -1
- package/server/admin-routes.ts +2 -11
- package/server/admin-state.ts +15 -4
- package/server/assets/chat/admin.js +33 -121
- package/server/assets/chat/editor.js +50 -13
- package/server/assets/chat/events.js +6 -6
- package/server/assets/chat/messages.js +1 -1
- package/server/assets/chat/questions.js +4 -4
- package/server/assets/chat/reminders.js +1 -0
- package/server/assets/chat/replies.js +2 -1
- package/server/assets/chat/room-watcher.js +37 -0
- package/server/assets/chat/rooms.js +52 -66
- package/server/assets/chat/state.js +6 -4
- package/server/assets/conversation.css +8 -5
- package/server/assets/responsive.css +5 -12
- package/server/chat-server.ts +1 -1
- package/server/chat.html +3 -10
- package/server/room-reminders.ts +15 -5
- package/skills/chatroom/SKILL.md +3 -7
- package/src/admin-client.ts +6 -43
- package/src/admin-credentials.ts +0 -19
- package/src/mentions.ts +2 -1
- package/src/resource-upload.ts +1 -1
- package/src/supervision-inbox.ts +6 -18
- package/src/v2-plugin.ts +1 -1
- package/server/admin-plan-routes.ts +0 -79
- package/server/admin-scheduler.ts +0 -42
- package/server/admin-task-routes.ts +0 -182
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isOwnMessage } from "./messages.js";
|
|
2
|
+
import { setRoomPreview } from "./system-messages.js";
|
|
3
|
+
|
|
4
|
+
export async function watchRoom(roomId, app) {
|
|
5
|
+
const entry = app.state.rooms.get(roomId);
|
|
6
|
+
if (!entry || app.state.room?.id === roomId) return;
|
|
7
|
+
try {
|
|
8
|
+
const query = new URLSearchParams({ sessionID: app.LS.sessionID, roomId, excludeSelf: "0", timeout: "0" });
|
|
9
|
+
query.set("afterTs", String(entry.receivedTs || 0));
|
|
10
|
+
const result = await app.api(`/inbox?${query}`);
|
|
11
|
+
if (app.state.rooms.get(roomId) !== entry) return;
|
|
12
|
+
if (result.member === false) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
|
|
13
|
+
if (result.member !== true || !Array.isArray(result.items) || app.state.room?.id === roomId) return;
|
|
14
|
+
const previousReceivedTs = entry.receivedTs || 0;
|
|
15
|
+
const sawSystem = result.items.some((message) => message.senderId === "system");
|
|
16
|
+
for (const message of result.items) {
|
|
17
|
+
if (!isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
18
|
+
if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
|
|
19
|
+
if (message.createdAt >= entry.previewAt) setRoomPreview(entry, message);
|
|
20
|
+
}
|
|
21
|
+
entry.receivedTs = result.items.reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
22
|
+
if (sawSystem || result.hasMore) {
|
|
23
|
+
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
24
|
+
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
25
|
+
entry.room.participants = latest.participants;
|
|
26
|
+
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
|
+
const newest = latest.messages.at(-1);
|
|
28
|
+
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
29
|
+
}
|
|
30
|
+
entry.unreadOverflow = Boolean(result.hasMore);
|
|
31
|
+
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
32
|
+
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error.status === 401) app.openChatSettings();
|
|
35
|
+
else if (error.status === 404) await app.removeJoinedRoom(roomId, { reason: false });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
-
import { isOwnMessage } from "./messages.js";
|
|
3
2
|
import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
|
|
3
|
+
import { watchRoom } from "./room-watcher.js";
|
|
4
4
|
|
|
5
5
|
export function initRooms(app) {
|
|
6
6
|
const $ = app.$;
|
|
7
|
+
let roomListGeneration = 0;
|
|
8
|
+
let autoRefresh;
|
|
9
|
+
const invalidateRoomList = () => { autoRefresh = undefined; return ++roomListGeneration; };
|
|
7
10
|
|
|
8
|
-
app.showJoin = (refresh = true) => {
|
|
11
|
+
app.showJoin = (refresh = true, preserveRoomListGeneration = false) => {
|
|
12
|
+
if (!preserveRoomListGeneration) invalidateRoomList();
|
|
9
13
|
document.documentElement.classList.remove("session-restore");
|
|
10
14
|
if (!$("#inName").value) $("#inName").value = LS.name;
|
|
11
15
|
$("#chatView").hidden = true;
|
|
@@ -60,11 +64,12 @@ export function initRooms(app) {
|
|
|
60
64
|
app.startRoomWatcher();
|
|
61
65
|
};
|
|
62
66
|
|
|
63
|
-
app.activateRoom = (roomId) => {
|
|
67
|
+
app.activateRoom = (roomId, preserveRoomListGeneration = false) => {
|
|
64
68
|
app.state.navigationGeneration++;
|
|
65
69
|
const entry = app.state.rooms.get(roomId);
|
|
66
70
|
if (!entry) return;
|
|
67
71
|
if (app.state.room?.id === roomId) return;
|
|
72
|
+
if (!preserveRoomListGeneration) invalidateRoomList();
|
|
68
73
|
if (app.state.room) {
|
|
69
74
|
app.saveDraft(app.state.room.id, $("#msgInput").draftValue);
|
|
70
75
|
app.captureReadingPosition?.();
|
|
@@ -106,7 +111,7 @@ export function initRooms(app) {
|
|
|
106
111
|
|
|
107
112
|
app.joinRoom = async (roomId, name) => {
|
|
108
113
|
if (app.state.rooms.has(roomId)) return app.activateRoom(roomId);
|
|
109
|
-
const intent = ++app.state.navigationGeneration;
|
|
114
|
+
const intent = ++app.state.navigationGeneration; invalidateRoomList();
|
|
110
115
|
app.state.pendingAction = null;
|
|
111
116
|
app.setJoinBusy(true);
|
|
112
117
|
app.hideJoinError();
|
|
@@ -115,6 +120,7 @@ export function initRooms(app) {
|
|
|
115
120
|
method: "POST",
|
|
116
121
|
body: JSON.stringify({ sessionID: LS.sessionID, participantId: name, participantName: name }),
|
|
117
122
|
});
|
|
123
|
+
invalidateRoomList();
|
|
118
124
|
LS.name = name;
|
|
119
125
|
app.enterRoom(room, name, intent);
|
|
120
126
|
} catch (error) {
|
|
@@ -122,7 +128,7 @@ export function initRooms(app) {
|
|
|
122
128
|
app.state.pendingAction = { type: "join", roomId, name };
|
|
123
129
|
if (app.state.room) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
124
130
|
else { app.openTokenBox(); app.showJoinError("authRetry"); }
|
|
125
|
-
} else app.showJoinError(error.network ? "networkRetry" : "joinFailed", { message: error.message });
|
|
131
|
+
} else { app.showJoinError(error.network ? "networkRetry" : "joinFailed", { message: error.message }); void app.refreshRoomList(); }
|
|
126
132
|
} finally { app.setJoinBusy(false); }
|
|
127
133
|
};
|
|
128
134
|
|
|
@@ -131,7 +137,7 @@ export function initRooms(app) {
|
|
|
131
137
|
const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || LS.name || app.t("guest");
|
|
132
138
|
const roomName = pending?.roomName || $(fromChat ? "#inRoomNameChat" : "#inRoomName").value.trim();
|
|
133
139
|
if (!roomName) return fromChat ? app.showSendError("roomNameRequired") : app.showJoinError("roomNameRequired");
|
|
134
|
-
const intent = ++app.state.navigationGeneration;
|
|
140
|
+
const intent = ++app.state.navigationGeneration; invalidateRoomList();
|
|
135
141
|
app.setJoinBusy(true);
|
|
136
142
|
app.hideJoinError();
|
|
137
143
|
app.state.pendingAction = null;
|
|
@@ -141,6 +147,7 @@ export function initRooms(app) {
|
|
|
141
147
|
method: "POST",
|
|
142
148
|
body: JSON.stringify({ name: roomName, ownerId: name, sessionID: LS.sessionID }),
|
|
143
149
|
});
|
|
150
|
+
invalidateRoomList();
|
|
144
151
|
LS.name = name;
|
|
145
152
|
if (fromChat) {
|
|
146
153
|
$("#inRoomNameChat").value = "";
|
|
@@ -152,8 +159,8 @@ export function initRooms(app) {
|
|
|
152
159
|
app.state.pendingAction = { type: "create", name, roomName, fromChat };
|
|
153
160
|
if (fromChat) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
154
161
|
else { app.openTokenBox(); app.showJoinError("authRetry"); }
|
|
155
|
-
} else if (fromChat) app.showSendError("sendFailed", { message: error.message });
|
|
156
|
-
else app.showJoinError("createFailed", { message: error.message });
|
|
162
|
+
} else if (fromChat) { app.showSendError("sendFailed", { message: error.message }); void app.refreshRoomList(); }
|
|
163
|
+
else { app.showJoinError("createFailed", { message: error.message }); void app.refreshRoomList(); }
|
|
157
164
|
} finally {
|
|
158
165
|
app.setJoinBusy(false);
|
|
159
166
|
$("#btnCreateChatRoom").disabled = false;
|
|
@@ -169,7 +176,8 @@ export function initRooms(app) {
|
|
|
169
176
|
const roomId = app.state.room?.id;
|
|
170
177
|
if (roomId) void app.removeJoinedRoom(roomId, { leaveServer: !silent });
|
|
171
178
|
};
|
|
172
|
-
app.removeJoinedRoom = async (roomId, { leaveServer = false, reason = false } = {}) => {
|
|
179
|
+
app.removeJoinedRoom = async (roomId, { leaveServer = false, reason = false, reconcile = false } = {}) => {
|
|
180
|
+
if (!reconcile) invalidateRoomList();
|
|
173
181
|
const active = app.state.room?.id === roomId;
|
|
174
182
|
const entry = app.state.rooms.get(roomId);
|
|
175
183
|
app.disposeRoomAttachments?.(roomId);
|
|
@@ -202,10 +210,10 @@ export function initRooms(app) {
|
|
|
202
210
|
}
|
|
203
211
|
if (active) {
|
|
204
212
|
const next = app.state.rooms.keys().next().value;
|
|
205
|
-
if (next) app.activateRoom(next);
|
|
213
|
+
if (next) app.activateRoom(next, true);
|
|
206
214
|
else {
|
|
207
215
|
LS.roomId = "";
|
|
208
|
-
app.showJoin();
|
|
216
|
+
app.showJoin(false, true);
|
|
209
217
|
if (reason) app.showJoinError("roomNotFound");
|
|
210
218
|
}
|
|
211
219
|
}
|
|
@@ -220,29 +228,39 @@ export function initRooms(app) {
|
|
|
220
228
|
app.state.watcherTimer = setTimeout(async () => {
|
|
221
229
|
const inactive = [...app.state.rooms.keys()].filter((id) => id !== app.state.room?.id);
|
|
222
230
|
await bounded(inactive, 3, (roomId) => watchRoom(roomId, app));
|
|
223
|
-
if (app.state.restorePending?.size || app.state.restoreRetry) void app.refreshRoomList();
|
|
231
|
+
if (app.state.restorePending?.size || app.state.restoreRetry) void app.refreshRoomList(true);
|
|
224
232
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
225
233
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
226
234
|
app.startRoomWatcher();
|
|
227
235
|
}, 5000);
|
|
228
236
|
};
|
|
229
237
|
|
|
230
|
-
app.refreshRoomList =
|
|
238
|
+
app.refreshRoomList = (automatic = false) => {
|
|
239
|
+
if (automatic && autoRefresh?.generation === roomListGeneration) return autoRefresh.promise;
|
|
240
|
+
const generation = invalidateRoomList(), promise = loadRoomList(generation);
|
|
241
|
+
if (automatic) { autoRefresh = { generation, promise }; const clear = () => { if (autoRefresh?.promise === promise) autoRefresh = undefined; }; void promise.then(clear, clear); }
|
|
242
|
+
return promise;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
async function loadRoomList(generation) {
|
|
231
246
|
const empty = $("#roomListEmpty"), chatEmpty = $("#roomListChatEmpty");
|
|
232
247
|
try {
|
|
233
248
|
const rooms = await app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`);
|
|
249
|
+
if (generation !== roomListGeneration) return;
|
|
234
250
|
app.state.restoreRetry = false;
|
|
235
251
|
app.state.availableRooms = rooms;
|
|
236
|
-
if (!app.state.restored || app.state.restorePending?.size) await app.restoreJoinedRooms(rooms);
|
|
252
|
+
if (!app.state.restored || app.state.restorePending?.size) await app.restoreJoinedRooms(rooms, generation);
|
|
237
253
|
else {
|
|
238
254
|
syncCachedRooms(rooms, app);
|
|
239
|
-
await app.discoverDirectRooms(rooms);
|
|
255
|
+
await app.discoverDirectRooms(rooms, generation);
|
|
240
256
|
}
|
|
257
|
+
if (generation !== roomListGeneration) return;
|
|
241
258
|
app.renderRoomOptions($("#roomList"), rooms);
|
|
242
259
|
app.renderRoomOptions($("#roomListChat"), rooms);
|
|
243
260
|
empty.hidden = rooms.length > 0;
|
|
244
261
|
chatEmpty.hidden = rooms.length > 0;
|
|
245
262
|
} catch (error) {
|
|
263
|
+
if (generation !== roomListGeneration) return;
|
|
246
264
|
if (error.status === 401) {
|
|
247
265
|
if (!app.state.room && !app.state.restored) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); }
|
|
248
266
|
else app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
@@ -260,13 +278,11 @@ export function initRooms(app) {
|
|
|
260
278
|
app.startRoomWatcher();
|
|
261
279
|
}
|
|
262
280
|
}
|
|
263
|
-
}
|
|
281
|
+
}
|
|
264
282
|
|
|
265
|
-
app.restoreJoinedRooms = async (rooms) => {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
283
|
+
app.restoreJoinedRooms = async (rooms, generation = roomListGeneration) => {
|
|
284
|
+
while (app.state.restoring) { await new Promise((resolve) => setTimeout(resolve, 10)); if (generation !== roomListGeneration) return; }
|
|
285
|
+
if (generation !== roomListGeneration) return;
|
|
270
286
|
app.state.restoring = true;
|
|
271
287
|
try {
|
|
272
288
|
const activeId = LS.roomId;
|
|
@@ -276,14 +292,18 @@ export function initRooms(app) {
|
|
|
276
292
|
const unresolved = new Set();
|
|
277
293
|
let authFailed = false;
|
|
278
294
|
await bounded(candidates, 3, async (roomId) => {
|
|
295
|
+
if (generation !== roomListGeneration) return;
|
|
279
296
|
try {
|
|
280
297
|
const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
298
|
+
if (generation !== roomListGeneration) return;
|
|
281
299
|
const members = await app.api(`/rooms/${encodeURIComponent(roomId)}/members`);
|
|
300
|
+
if (generation !== roomListGeneration) return;
|
|
282
301
|
const me = members.find((member) => member.sessionID === LS.sessionID);
|
|
283
302
|
if (!me) return;
|
|
284
303
|
valid.add(roomId);
|
|
285
304
|
app.ensureJoinedRoom(room, me.name);
|
|
286
305
|
} catch (error) {
|
|
306
|
+
if (generation !== roomListGeneration) return;
|
|
287
307
|
if (error.status !== 404) {
|
|
288
308
|
unresolved.add(roomId);
|
|
289
309
|
if (error.status === 401) authFailed = true;
|
|
@@ -291,34 +311,38 @@ export function initRooms(app) {
|
|
|
291
311
|
}
|
|
292
312
|
}
|
|
293
313
|
});
|
|
314
|
+
if (generation !== roomListGeneration) return;
|
|
294
315
|
app.state.joinedIds = new Set([...valid, ...unresolved]);
|
|
295
316
|
app.state.restorePending = unresolved;
|
|
296
317
|
app.saveJoinedIds();
|
|
297
318
|
app.state.restored = unresolved.size === 0;
|
|
298
|
-
if (authFailed) { app.showJoin(false); app.openTokenBox(); app.showJoinError("authRetry"); return; }
|
|
299
|
-
if (activeId && valid.has(activeId)) app.activateRoom(activeId);
|
|
319
|
+
if (authFailed) { app.showJoin(false, true); app.openTokenBox(); app.showJoinError("authRetry"); return; }
|
|
320
|
+
if (activeId && valid.has(activeId)) app.activateRoom(activeId, true);
|
|
300
321
|
else if (activeId && unresolved.has(activeId)) {
|
|
301
322
|
app.showRestoreFailure(app.t("networkRetry"));
|
|
302
323
|
}
|
|
303
324
|
else {
|
|
304
325
|
LS.roomId = "";
|
|
305
326
|
const fallback = valid.values().next().value;
|
|
306
|
-
if (fallback) app.activateRoom(fallback);
|
|
327
|
+
if (fallback) app.activateRoom(fallback, true);
|
|
307
328
|
else if (unresolved.size) app.showRestoreFailure(app.t("networkRetry"));
|
|
308
|
-
else app.showJoin(false);
|
|
329
|
+
else app.showJoin(false, true);
|
|
309
330
|
}
|
|
310
331
|
app.startRoomWatcher();
|
|
311
332
|
} finally { app.state.restoring = false; }
|
|
312
333
|
};
|
|
313
334
|
|
|
314
|
-
app.discoverDirectRooms = async (rooms) => {
|
|
335
|
+
app.discoverDirectRooms = async (rooms, generation = roomListGeneration) => {
|
|
315
336
|
const candidates = rooms.filter((room) => room.kind === "direct" && !app.state.rooms.has(room.id));
|
|
316
337
|
await bounded(candidates, 3, async (room) => {
|
|
338
|
+
if (generation !== roomListGeneration) return;
|
|
317
339
|
try {
|
|
318
340
|
const members = await app.api(`/rooms/${encodeURIComponent(room.id)}/members`);
|
|
341
|
+
if (generation !== roomListGeneration) return;
|
|
319
342
|
const me = members.find((member) => member.sessionID === LS.sessionID);
|
|
320
343
|
if (me) app.ensureJoinedRoom(room, me.name);
|
|
321
344
|
} catch (error) {
|
|
345
|
+
if (generation !== roomListGeneration) return;
|
|
322
346
|
if (error.status !== 404) {
|
|
323
347
|
app.state.restorePending ||= new Set();
|
|
324
348
|
app.state.restorePending.add(room.id);
|
|
@@ -329,6 +353,7 @@ export function initRooms(app) {
|
|
|
329
353
|
}
|
|
330
354
|
}
|
|
331
355
|
});
|
|
356
|
+
if (generation !== roomListGeneration) return;
|
|
332
357
|
if (app.state.restorePending?.size) app.startRoomWatcher();
|
|
333
358
|
};
|
|
334
359
|
|
|
@@ -450,7 +475,7 @@ function syncCachedRooms(rooms, app) {
|
|
|
450
475
|
const remote = new Map(rooms.map((room) => [room.id, room]));
|
|
451
476
|
for (const [roomId, entry] of app.state.rooms) {
|
|
452
477
|
const fresh = remote.get(roomId);
|
|
453
|
-
if (!fresh || fresh.joined === false) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
|
|
478
|
+
if (!fresh || fresh.joined === false) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId, reconcile: true }); continue; }
|
|
454
479
|
if (app.state.room?.id === roomId) continue;
|
|
455
480
|
const messages = new Map([...entry.room.messages, ...fresh.messages].map((message) => [message.id, message]));
|
|
456
481
|
entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
@@ -458,42 +483,3 @@ function syncCachedRooms(rooms, app) {
|
|
|
458
483
|
if (latest) setRoomPreview(entry, latest);
|
|
459
484
|
}
|
|
460
485
|
}
|
|
461
|
-
|
|
462
|
-
async function watchRoom(roomId, app) {
|
|
463
|
-
const entry = app.state.rooms.get(roomId);
|
|
464
|
-
if (!entry || app.state.room?.id === roomId) return;
|
|
465
|
-
try {
|
|
466
|
-
const query = new URLSearchParams({ sessionID: app.LS.sessionID, roomId, excludeSelf: "0", timeout: "0" });
|
|
467
|
-
query.set("afterTs", String(entry.receivedTs || 0));
|
|
468
|
-
const result = await app.api(`/inbox?${query}`);
|
|
469
|
-
if (app.state.rooms.get(roomId) !== entry) return;
|
|
470
|
-
if (result.member === false) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
|
|
471
|
-
if (result.member !== true || !Array.isArray(result.items)) return;
|
|
472
|
-
if (app.state.room?.id === roomId) return;
|
|
473
|
-
const previousReceivedTs = entry.receivedTs || 0;
|
|
474
|
-
const sawSystem = (result.items || []).some((message) => message.senderId === "system");
|
|
475
|
-
for (const message of result.items || []) {
|
|
476
|
-
if (!isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
477
|
-
if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
|
|
478
|
-
if (message.createdAt >= entry.previewAt) {
|
|
479
|
-
setRoomPreview(entry, message);
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
entry.receivedTs = (result.items || []).reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
483
|
-
if (sawSystem || result.hasMore) {
|
|
484
|
-
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
485
|
-
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
486
|
-
entry.room.participants = latest.participants;
|
|
487
|
-
const messages = new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message]));
|
|
488
|
-
entry.room.messages = [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
|
|
489
|
-
const newest = latest.messages.at(-1);
|
|
490
|
-
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
491
|
-
}
|
|
492
|
-
entry.unreadOverflow = Boolean(result.hasMore);
|
|
493
|
-
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
494
|
-
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
495
|
-
} catch (error) {
|
|
496
|
-
if (error.status === 401) app.openChatSettings();
|
|
497
|
-
else if (error.status === 404) await app.removeJoinedRoom(roomId, { reason: false });
|
|
498
|
-
}
|
|
499
|
-
}
|
|
@@ -219,7 +219,7 @@ const messages = {
|
|
|
219
219
|
announcements: "Announcements", announcementName: "Name", announcementContent: "Content",
|
|
220
220
|
reminders: "Reminders", reminderSchedule: "Schedule", reminderOnce: "One time", reminderDate: "Date and time",
|
|
221
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",
|
|
222
|
+
reminderText: "Reminder text", reminderTemplateHint: "Use {{time}}, {{initiator}}, and {{room}} in your message.", reminderCreate: "Create reminder",
|
|
223
223
|
reminderLoading: "Loading reminders…", reminderEmpty: "No reminders yet.", reminderPaused: "Paused", reminderNext: ({ time }) => `Next: ${time}`,
|
|
224
224
|
reminderPause: "Pause", reminderResume: "Resume", reminderDelete: "Delete", reminderDeleteConfirm: "Delete this reminder?",
|
|
225
225
|
reminderCreated: "Reminder created.", reminderUpdated: "Reminder updated.", reminderDeleted: "Reminder deleted.",
|
|
@@ -234,7 +234,8 @@ const messages = {
|
|
|
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
236
|
sendAsQuestion: "Send as a question",
|
|
237
|
-
|
|
237
|
+
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 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
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.", 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}”?`,
|
|
239
240
|
leave: "Leave", reconnecting: "Connection lost. Retrying…", messageList: "Message list",
|
|
240
241
|
noMessages: "No messages yet. Say something.", latestMessages: "Back to latest messages",
|
|
@@ -294,7 +295,7 @@ const messages = {
|
|
|
294
295
|
announcements: "公告栏", announcementName: "名称", announcementContent: "内容",
|
|
295
296
|
reminders: "提醒", reminderSchedule: "计划", reminderOnce: "单次", reminderDate: "日期和时间",
|
|
296
297
|
reminderCron: "5 字段 CRON 表达式", reminderTimezone: "时区覆盖(可选)", reminderTimezoneHint: "留空则使用服务器时区。填写 IANA 时区会应用于两种计划。服务器会拒绝夏令时调整中不存在或重复的单次时间。",
|
|
297
|
-
reminderText: "提醒内容", reminderTemplateHint: "可使用 {time}、{initiator} 和 {room}。", reminderCreate: "创建提醒",
|
|
298
|
+
reminderText: "提醒内容", reminderTemplateHint: "可使用 {{time}}、{{initiator}} 和 {{room}}。", reminderCreate: "创建提醒",
|
|
298
299
|
reminderLoading: "正在加载提醒…", reminderEmpty: "暂无提醒。", reminderPaused: "已暂停", reminderNext: ({ time }) => `下次:${time}`,
|
|
299
300
|
reminderPause: "暂停", reminderResume: "恢复", reminderDelete: "删除", reminderDeleteConfirm: "确定删除此提醒?",
|
|
300
301
|
reminderCreated: "提醒已创建。", reminderUpdated: "提醒已更新。", reminderDeleted: "提醒已删除。",
|
|
@@ -309,7 +310,8 @@ const messages = {
|
|
|
309
310
|
answerQuestion: "回复", answerPlaceholder: "写下回复…", sendAnswer: "发送回复", selectQuestion: "回复此问题", copyQuestion: "复制问题", questionCopied: "问题已复制。", questionCopyFailed: "无法复制问题。",
|
|
310
311
|
answerFailed: "回复失败,草稿仍已保留。", answerTooLong: "回复不能超过 2,000 个字符。", questionAlreadyAnswered: "此问题已由其他人回答。",
|
|
311
312
|
sendAsQuestion: "作为问题发送",
|
|
312
|
-
|
|
313
|
+
adminBindingGuide: "选择管理员房间和其中的 Agent,再将邀请私下发送给该 Agent 完成设置。", adminRoomLabel: "管理员房间", adminDesignateAgent: "邀请 Agent",
|
|
314
|
+
adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "请选择管理员房间内的 Agent。管理员可以管理所有房间。", adminRoomBadge: "管理", targetAgent: "已注册 Agent", designate: "绑定并生成加入指令", revokeDesignation: "撤销绑定", globalStatus: "全局状态", adminTasks: "任务", taskText: "任务内容", dispatchTask: "派发任务", timers: "定时任务", planName: "定时任务名称", createTimer: "创建定时任务",
|
|
313
315
|
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}”?`,
|
|
314
316
|
tokenRequired: "服务器要求访问令牌(401)。", leave: "离开", reconnecting: "连接中断,正在重试…",
|
|
315
317
|
messageList: "消息列表", noMessages: "还没有消息,说点什么吧。", latestMessages: "回到最新消息",
|
|
@@ -248,13 +248,16 @@
|
|
|
248
248
|
.message-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
249
249
|
.message-copy-feedback { position: absolute; z-index: 25; left: 0; bottom: calc(100% + 5px); width: max-content; max-width: min(260px, calc(100vw - 32px)); padding: 6px 9px; border: 1px solid var(--line); border-radius: 8px; color: var(--ink); background: var(--surface); box-shadow: var(--shadow); font-size: 11px; font-weight: 500; line-height: 1.4; text-align: left; white-space: normal; overflow-wrap: anywhere; }
|
|
250
250
|
.message-actions { display: flex; align-items: center; gap: 2px; }
|
|
251
|
-
.message-reply {
|
|
251
|
+
.message-reply { display: grid; place-items: center; width: 32px; height: 32px; padding: 0; border: 1px solid transparent; border-radius: 8px; color: var(--ink-3); background: transparent; cursor: pointer; }
|
|
252
|
+
.message-reply-icon { display: block; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.7; }
|
|
252
253
|
.message-reply:hover, .message-reply:focus-visible { border-color: var(--line); color: var(--accent); background: var(--accent-soft); }
|
|
253
|
-
.reply-preview { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: min(940px, 100%); margin: 0 auto; padding: 8px 12px; border-left: 3px solid var(--accent); border-radius: 6px; background: var(--accent-soft); }
|
|
254
|
+
.reply-preview { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: min(940px, 100%); min-width: 0; margin: 0 auto; padding: 8px 12px; border-left: 3px solid var(--accent); border-radius: 6px; background: var(--accent-soft); }
|
|
255
|
+
.reply-preview > div { min-width: 0; flex: 1; }
|
|
254
256
|
.reply-preview strong { font-size: 12px; color: var(--accent); }
|
|
255
|
-
.reply-preview p { overflow: hidden; margin: 2px 0 0; color: var(--ink-2); font-size: 12px;
|
|
256
|
-
.reply-cancel { flex: none;
|
|
257
|
-
.reply-cancel:hover { color: var(--danger); background: var(--surface); }
|
|
257
|
+
.reply-preview p { display: -webkit-box; overflow: hidden; margin: 2px 0 0; color: var(--ink-2); font-size: 12px; line-height: 1.4; overflow-wrap: anywhere; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
|
258
|
+
.reply-cancel { flex: none; min-height: 32px; padding: 0 9px; border: 1px solid var(--line); border-radius: 8px; color: var(--ink-2); background: var(--surface); font: inherit; font-size: 11px; font-weight: 600; white-space: nowrap; cursor: pointer; }
|
|
259
|
+
.reply-cancel:hover, .reply-cancel:focus-visible { border-color: var(--danger); color: var(--danger); background: var(--surface); }
|
|
260
|
+
.reply-cancel:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
258
261
|
.reply-quote { display: block; max-width: min(82%, 500px); overflow: hidden; margin: 0 0 5px; padding: 5px 10px; border: 0; border-left: 2px solid var(--accent); border-radius: 0 6px 6px 0; color: var(--ink-2); background: var(--surface-2); font: inherit; font-size: 12px; text-align: left; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
|
|
259
262
|
.reply-quote:hover:not(:disabled) { color: var(--accent); background: var(--accent-soft); }
|
|
260
263
|
.reply-quote:disabled { cursor: default; opacity: .7; }
|
|
@@ -77,25 +77,18 @@
|
|
|
77
77
|
.admin-badge { padding: 3px 8px; }
|
|
78
78
|
.room-admin-badge { padding: 1px 6px; vertical-align: middle; }
|
|
79
79
|
.admin-scope-note { margin: 0 0 14px; padding: 10px 11px; border-left: 2px solid var(--accent); border-radius: 0 8px 8px 0; background: color-mix(in srgb, var(--accent-soft) 58%, transparent); line-height: 1.5; }
|
|
80
|
-
.admin-dialog { width: min(
|
|
80
|
+
.admin-dialog { width: min(560px, calc(100vw - 32px)); max-width: none; max-height: 90dvh; overflow: auto; padding: 24px; color: var(--ink); background: linear-gradient(145deg, var(--surface), color-mix(in srgb, var(--accent-soft) 16%, var(--surface))); border: 1px solid color-mix(in srgb, var(--accent) 18%, var(--line)); border-radius: 20px; box-shadow: 0 24px 80px rgb(10 25 20 / .2); }
|
|
81
81
|
.admin-dialog::backdrop { background: rgb(9 22 18 / .52); backdrop-filter: blur(4px); }
|
|
82
82
|
.admin-dialog-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
|
83
83
|
.admin-dialog-actions { display: flex; align-items: center; gap: 10px; }
|
|
84
84
|
.admin-dialog #btnCloseAdmin { width: 36px; height: 36px; margin: 0; }
|
|
85
85
|
.admin-dialog-head h2 { margin: 0; font-family: var(--font-display); font-size: 25px; font-weight: 600; letter-spacing: -.02em; }
|
|
86
86
|
.admin-dialog h3 { margin: 20px 0 9px; font-size: 14px; font-weight: 700; letter-spacing: .01em; }
|
|
87
|
-
.admin-
|
|
88
|
-
.admin-
|
|
89
|
-
.admin-columns > section > h3:first-child { margin-top: 0; }
|
|
90
|
-
.admin-columns .field { margin-bottom: 10px; }
|
|
87
|
+
.admin-guide { padding: 16px; border: 1px solid color-mix(in srgb, var(--line) 82%, transparent); border-radius: 14px; background: color-mix(in srgb, var(--surface) 84%, var(--accent-soft)); }
|
|
88
|
+
.admin-guide .field { margin-bottom: 12px; }
|
|
91
89
|
.admin-dialog .admin-select { display: block; box-sizing: border-box; width: 100%; min-width: 0; min-height: 40px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: var(--surface); font: inherit; }
|
|
92
|
-
.admin-
|
|
93
|
-
|
|
94
|
-
.admin-list li { display: grid; gap: 7px; }
|
|
95
|
-
.admin-plan-form { display: grid; gap: 8px; }
|
|
96
|
-
.admin-enrollment { display: grid; gap: 8px; margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--accent-soft); overflow-wrap: anywhere; }
|
|
97
|
-
.admin-enrollment code { user-select: all; }
|
|
98
|
-
@media (max-width: 620px) { .admin-dialog { padding: 15px; } .admin-columns { grid-template-columns: minmax(0, 1fr); gap: 0; } }
|
|
90
|
+
.admin-enrollment { display: grid; gap: 8px; margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--accent-soft); }
|
|
91
|
+
@media (max-width: 620px) { .admin-dialog { padding: 15px; } }
|
|
99
92
|
.rail-avatar { display: grid; place-items: center; width: 25px; height: 25px; border-radius: 50%; color: var(--accent); background: var(--accent-soft); }
|
|
100
93
|
.online-dot { width: 7px; height: 7px; border-radius: 50%; background: #609773; box-shadow: 0 0 0 3px color-mix(in srgb, #609773 16%, transparent); }
|
|
101
94
|
#chatView > .chat-head { grid-column: 2; grid-row: 1; min-width: 0; }
|
package/server/chat-server.ts
CHANGED
|
@@ -509,7 +509,7 @@ export default {
|
|
|
509
509
|
console.log(
|
|
510
510
|
`chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`,
|
|
511
511
|
);
|
|
512
|
-
startRoomReminderScheduler();
|
|
512
|
+
startRoomReminderScheduler((roomId, roomName, text, message) => wakeMentionedSessions(serveWakeUrl, roomId, roomName, text, "", message));
|
|
513
513
|
if (!token) {
|
|
514
514
|
console.warn(
|
|
515
515
|
"chat-room center has NO token auth — set CHAT_ROOM_SERVER_TOKEN if this port is reachable from other hosts",
|
package/server/chat.html
CHANGED
|
@@ -113,17 +113,10 @@
|
|
|
113
113
|
<dialog id="adminDialog" class="admin-dialog" aria-labelledby="adminHeading">
|
|
114
114
|
<header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><div class="admin-dialog-actions"><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></div></header>
|
|
115
115
|
<p id="adminStatus" class="hint" role="status" aria-live="polite"></p>
|
|
116
|
-
<div class="admin-
|
|
117
|
-
<section><h3 data-i18n="designations">Designations</h3><p class="hint admin-scope-note" data-i18n="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.</p><label class="field"><span class="field-label" data-i18n="adminRoom">Administrator room</span><select id="adminRoomSelect" class="admin-select"></select></label>
|
|
118
|
-
<label class="field"><span class="field-label" data-i18n="targetRoom">Agent membership room</span><select id="adminTargetRoom" class="admin-select"></select></label>
|
|
116
|
+
<div class="admin-guide"><p class="hint admin-scope-note" data-i18n="adminBindingGuide">Choose a room, then select a registered member. They must privately accept the invitation to finish setup.</p><label class="field"><span class="field-label" data-i18n="adminRoomLabel">Room to administer</span><select id="adminRoomSelect" class="admin-select"></select></label>
|
|
119
117
|
<label class="field"><span class="field-label" data-i18n="targetAgent">Registered agent</span><select id="adminTargetAgent" class="admin-select"></select></label>
|
|
120
|
-
<button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="
|
|
118
|
+
<button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="adminDesignateAgent">Designate agent</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
|
|
121
119
|
<button id="btnRevokeAdmin" class="btn ghost small danger-text" type="button" data-i18n="revokeDesignation">Revoke designation</button>
|
|
122
|
-
</section>
|
|
123
|
-
<section><h3 data-i18n="globalStatus">Global status</h3><div id="adminOverview" class="admin-overview"></div><h3 data-i18n="adminTasks">Tasks</h3>
|
|
124
|
-
<form id="adminTaskForm"><label class="field"><span class="field-label" data-i18n="taskTargetRoom">Target room</span><select id="adminTaskRoom" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskTargetAgent">Target agent</span><select id="adminTaskAgent" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskText">Task</span><textarea id="adminTaskText" class="input" rows="2" maxlength="2000" required></textarea></label><button class="btn primary small" type="submit" data-i18n="dispatchTask">Dispatch task</button></form><ul id="adminTaskList" class="admin-list"></ul>
|
|
125
|
-
<h3 data-i18n="timers">Timers</h3><form id="adminPlanForm" class="admin-plan-form"><input id="adminPlanName" class="input" maxlength="64" required data-i18n-placeholder="planName" placeholder="Timer name"><input id="adminPlanInterval" class="input" type="number" min="60" max="2592000" value="3600" required><textarea id="adminPlanText" class="input" rows="2" maxlength="2000" required></textarea><button class="btn primary small" type="submit" data-i18n="createTimer">Create timer</button></form><ul id="adminPlanList" class="admin-list"></ul>
|
|
126
|
-
</section>
|
|
127
120
|
</div>
|
|
128
121
|
</dialog>
|
|
129
122
|
<button id="roomDrawerBackdrop" class="room-drawer-backdrop" type="button" aria-label="Close room list" data-i18n-aria-label="closeRoomList" hidden></button>
|
|
@@ -161,7 +154,7 @@
|
|
|
161
154
|
<label class="field"><span class="field-label" data-i18n="reminderTimezone">Timezone override (optional)</span><input id="reminderTimezone" class="input" autocomplete="off"></label>
|
|
162
155
|
<p class="hint" data-i18n="reminderTimezoneHint">Leave blank to use the server timezone. Enter an IANA timezone to override it.</p>
|
|
163
156
|
<label class="field"><span class="field-label" data-i18n="reminderText">Reminder text</span><textarea id="reminderText" class="input" rows="3" maxlength="1000" required></textarea></label>
|
|
164
|
-
<p class="hint" data-i18n="reminderTemplateHint">Use {time}, {initiator}, and {room} in your message.</p>
|
|
157
|
+
<p id="reminderTemplateHint" class="hint" data-i18n="reminderTemplateHint">Use {{time}}, {{initiator}}, and {{room}} in your message.</p>
|
|
165
158
|
<button class="btn primary small" type="submit" data-i18n="reminderCreate">Create reminder</button>
|
|
166
159
|
</form>
|
|
167
160
|
</section>
|
package/server/room-reminders.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Cron } from "croner";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { databasePath } from "../src/store";
|
|
4
4
|
import { initializeReminderSchema, withStateTransaction } from "../src/sqlite-state";
|
|
5
|
+
import type { Message } from "../src/room-service";
|
|
5
6
|
|
|
6
7
|
type Schedule = { type: "once"; at: string; timezone?: string } | { type: "cron"; expression: string; timezone: string };
|
|
7
8
|
type Row = { id: string; room_id: string; creator_session_id: string; initiator: string; text: string; schedule_type: string; at: string | null; expression: string | null; timezone: string | null; paused: number; next_run_at: number; created_at: number; last_error: string | null };
|
|
@@ -105,7 +106,8 @@ function template(text: string, at: number, initiator: string, room: string, tim
|
|
|
105
106
|
const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "longOffset" }).formatToParts(at).map(part => [part.type, part.value]));
|
|
106
107
|
return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second} ${parts.timeZoneName} [${timezone}]`;
|
|
107
108
|
})() : new Date(at).toISOString();
|
|
108
|
-
const result = text.replace(/\{(time|initiator|room)\}/g, (_m, key: string) =>
|
|
109
|
+
const result = text.replace(/\{\{(time|initiator|room)\}\}/g, (_m, key: string) =>
|
|
110
|
+
key === "time" ? time : key === "initiator" ? initiator : room);
|
|
109
111
|
if (result.length > 2000) throw new Error("rendered reminder text exceeds 2000 characters");
|
|
110
112
|
return result;
|
|
111
113
|
}
|
|
@@ -171,11 +173,14 @@ export async function roomReminderRoutes(req: Request, url: URL): Promise<Respon
|
|
|
171
173
|
return json(bodyOut, status);
|
|
172
174
|
}
|
|
173
175
|
|
|
174
|
-
export
|
|
176
|
+
export type ReminderWake = (roomId: string, roomName: string, text: string, message: Message) => void | Promise<void>;
|
|
177
|
+
|
|
178
|
+
export async function tickRoomReminders(now = Date.now(), wake?: ReminderWake): Promise<void> {
|
|
175
179
|
await initializeReminderSchema(dbFile());
|
|
176
180
|
const ids = await withStateTransaction(dbFile(), db => (db.query("SELECT id FROM room_reminders WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100").all(now) as Array<{ id: string }>).map(row => row.id));
|
|
177
181
|
const failures: Array<{ id: string; error: string }> = [];
|
|
178
182
|
for (const id of ids) {
|
|
183
|
+
let delivered: { roomName: string; message: Message } | undefined;
|
|
179
184
|
const failure = await withStateTransaction(dbFile(), db => {
|
|
180
185
|
const r = db.query("SELECT * FROM room_reminders WHERE id=? AND paused=0 AND next_run_at<=?").get(id, now) as Row | null;
|
|
181
186
|
if (!r) return null;
|
|
@@ -188,7 +193,9 @@ export async function tickRoomReminders(now = Date.now()): Promise<void> {
|
|
|
188
193
|
: (() => { throw new Error(`unsupported reminder schedule type: ${r.schedule_type}`); })();
|
|
189
194
|
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(r.room_id) as { created_at: number } | null;
|
|
190
195
|
const sentAt = Math.max(now, (tail?.created_at ?? 0) + 1), text = template(r.text, sentAt, r.initiator, room.name, r.timezone ?? undefined);
|
|
191
|
-
|
|
196
|
+
const message: Message = { id: `reminder:${randomUUID()}`, roomId: r.room_id, senderId: "system", text, createdAt: sentAt };
|
|
197
|
+
db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?, 'system',NULL,?,?,0)").run(message.id, r.room_id, text, sentAt);
|
|
198
|
+
delivered = { roomName: room.name, message };
|
|
192
199
|
if (upcoming === undefined) db.query("DELETE FROM room_reminders WHERE id=?").run(r.id);
|
|
193
200
|
else db.query("UPDATE room_reminders SET next_run_at=?,last_error=NULL WHERE id=?").run(upcoming, r.id);
|
|
194
201
|
})();
|
|
@@ -200,13 +207,16 @@ export async function tickRoomReminders(now = Date.now()): Promise<void> {
|
|
|
200
207
|
}
|
|
201
208
|
});
|
|
202
209
|
if (failure) failures.push(failure);
|
|
210
|
+
else if (delivered && wake) {
|
|
211
|
+
try { await wake(delivered.message.roomId, delivered.roomName, delivered.message.text, delivered.message); } catch { /* Inbox polling remains the fallback. */ }
|
|
212
|
+
}
|
|
203
213
|
}
|
|
204
214
|
for (const failure of failures) console.error(`room reminder ${failure.id} paused after delivery error: ${failure.error}`);
|
|
205
215
|
}
|
|
206
216
|
|
|
207
217
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
208
|
-
export function startRoomReminderScheduler(): void {
|
|
218
|
+
export function startRoomReminderScheduler(wake?: ReminderWake): void {
|
|
209
219
|
if (timer) return;
|
|
210
|
-
timer = setInterval(() => { void tickRoomReminders().catch(() => {}); }, 1000);
|
|
220
|
+
timer = setInterval(() => { void tickRoomReminders(Date.now(), wake).catch(() => {}); }, 1000);
|
|
211
221
|
timer.unref?.();
|
|
212
222
|
}
|
package/skills/chatroom/SKILL.md
CHANGED
|
@@ -77,7 +77,7 @@ Names must be non-empty and no longer than 64 Unicode characters after trimming.
|
|
|
77
77
|
|
|
78
78
|
Current room members can create, list, pause, resume, and delete reminders with `room` actions `reminder_create`, `reminder_list`, `reminder_update`, and `reminder_delete`. Create with `roomId`, `text`, and `schedule`: use `{ "type": "once", "at": "2026-11-11T09:00:00", "timezone": "Asia/Shanghai" }` or `{ "type": "cron", "expression": "0 9 * * 1-5", "timezone": "Asia/Shanghai" }`. Timezone is optional and defaults to the server's timezone. Updates use `reminderId` and one or more of `schedule`, `text`, and `paused`; deletion uses `reminderId`.
|
|
79
79
|
|
|
80
|
-
Templates support `{time}`, `{initiator}`, and `{room}`. The server posts the rendered system message to the room. Missed recurring occurrences coalesce into one; a missed one-time reminder fires once after recovery. Reminders continue if their creator leaves. Ambiguous or nonexistent daylight-saving local times must be disambiguated with an explicit offset.
|
|
80
|
+
Templates support `{{time}}`, `{{initiator}}`, and `{{room}}`. The server posts the rendered system message to the room. Missed recurring occurrences coalesce into one; a missed one-time reminder fires once after recovery. Reminders continue if their creator leaves. Ambiguous or nonexistent daylight-saving local times must be disambiguated with an explicit offset.
|
|
81
81
|
|
|
82
82
|
## Share files and media
|
|
83
83
|
|
|
@@ -87,7 +87,7 @@ In central mode, upload a local file with the room tool:
|
|
|
87
87
|
{"action":"upload_resource","roomId":"<room-id>","filePath":"<local-file-path>"}
|
|
88
88
|
```
|
|
89
89
|
|
|
90
|
-
The plugin requests host file-read permissions and returns resource metadata and a `[[resource:<UUID>]]` marker.
|
|
90
|
+
The plugin requests host file-read permissions and returns resource metadata and a `[[resource:<UUID>]]` marker. Uploading alone is invisible: the attachment renders only when the exact marker appears in a sent message, so include it unchanged in a normal `send` message with a short description, outside backticks or code blocks. Do not paraphrase it, shorten the UUID, or mention it only as prose. Uploading does not send a message or join the room. Upload only when already authorized to participate in that room; do not join automatically to share a file.
|
|
91
91
|
|
|
92
92
|
Respect permission denials and do not upload secrets or unrelated files. A local path is read on the machine running the plugin, not on the central server; remote URLs are not upload paths. The server sets the single-file size limit, defaulting to 500 MiB. Images, audio, and video may preview in the browser; other formats are offered as downloads. Resource markers refer to the room where the file was uploaded, not arbitrary filesystem paths or public links.
|
|
93
93
|
|
|
@@ -99,11 +99,7 @@ The separate `admin` tool supports operator-enrolled administrator rooms in cent
|
|
|
99
99
|
|
|
100
100
|
When the user privately supplies an enrollment instruction, call `admin` with `action: "admin_claim"`, `roomId`, and `enrollmentKey` in that designated session. Never post the enrollment key in a room. The plugin stores the resulting capability privately; do not request, copy, or expose it. If enrollment fails, ask the operator to reset it.
|
|
101
101
|
|
|
102
|
-
For a designated supervisor, `admin_overview` lists rooms
|
|
103
|
-
|
|
104
|
-
Workers receiving an assignment can call `admin` with `action: "task_progress"`, `taskId`, `status`, and `progress`. Supported states are `pending`, `working`, `blocked`, `completed`, and `cancelled`. Report actual progress and blockers; a received steer is not evidence that work is complete. Do not join the administrator room to report progress.
|
|
105
|
-
|
|
106
|
-
Use `admin_plan_create`, `admin_plans`, `admin_plan_update`, and `admin_plan_delete` for recurring supervision authorized by the user. Timers persist on the server and coalesce offline reminders; they do not guarantee execution while the host is unavailable. Check task reports and concrete evidence before declaring completion. Pause or delete a plan when its purpose ends.
|
|
102
|
+
For a designated supervisor, `admin_overview` lists rooms and members; `admin_history` reads bounded target-room history. To assign work, send a room message to the intended Agent. For scheduled work, create a room reminder containing the task and an @ mention.
|
|
107
103
|
|
|
108
104
|
## Testing and subagents
|
|
109
105
|
|