@alexsun-top/opencode-chat-room 0.5.3 → 0.5.4
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 +19 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/package.json +1 -1
- package/server/admin-auth.ts +4 -2
- package/server/assets/base.css +1 -1
- package/server/assets/chat/admin.js +4 -9
- package/server/assets/chat/announcements.js +17 -1
- package/server/assets/chat/attachments.js +4 -1
- package/server/assets/chat/editor.js +15 -2
- package/server/assets/chat/events.js +6 -1
- package/server/assets/chat/markdown.js +31 -11
- package/server/assets/chat/mentions.js +3 -1
- package/server/assets/chat/messages.js +54 -19
- package/server/assets/chat/questions.js +11 -0
- package/server/assets/chat/reminders.js +3 -3
- package/server/assets/chat/room-watcher.js +11 -3
- package/server/assets/chat/rooms.js +11 -4
- package/server/assets/chat/state.js +4 -4
- package/server/chat-server.ts +25 -36
- package/server/member-routes.ts +9 -11
- package/server/wake.ts +11 -2
- package/src/admin-client.ts +3 -3
- package/src/center-inbox.ts +0 -2
- package/src/plugin-notifications.ts +4 -3
- package/src/resources.ts +4 -1
- package/src/sqlite-state.ts +40 -0
- package/src/store.ts +4 -1
- package/src/supervision-inbox.ts +0 -50
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.4 — 2026-11-11
|
|
4
|
+
|
|
5
|
+
- Keep unanswered questions unread, including when they are answered from another room, and stop own messages from raising unread counts. The sidebar badge now clears once the conversation is read.
|
|
6
|
+
- Fix the first character being dropped when typing with an IME, and keep the caret stable after inserting a mention.
|
|
7
|
+
- Merge a send response with the polling result so a stale snapshot no longer erases newer messages.
|
|
8
|
+
- Make timestamps increase monotonically inside the write transaction and resume long polling from the exact cursor.
|
|
9
|
+
- Write sends, read acknowledgements, and queued watermarks directly instead of rewriting the whole state file.
|
|
10
|
+
- Keep per-room drafts, including mentions, and restore them after a reload.
|
|
11
|
+
- Show the next run only for recurring reminders; one-shot reminders show just their trigger time.
|
|
12
|
+
- Preview attachments you sent automatically and keep other people's attachments collapsed.
|
|
13
|
+
- Increase text selection contrast with an inverted accent background in both themes.
|
|
14
|
+
- Designate administrators in one step: the designation applies immediately and stays until revoked. The enrollment code and claim step are gone; existing claimed capabilities keep working.
|
|
15
|
+
- Render AVIF images and show a visible banner when an attachment upload fails.
|
|
16
|
+
- Keep the attachment preview toggle clickable and correctly labelled while a preview loads, and clear a preview that cannot be decoded.
|
|
17
|
+
- Stop rebuilding the question panel every few seconds and fix the CRON timezone label.
|
|
18
|
+
- Reject malformed JSON bodies with 400 instead of failing with 500.
|
|
19
|
+
- Re-check the operator token on every admin request and cap the in-memory wake table.
|
|
20
|
+
- Trim the queued watermark per room and remove the unused supervision inbox.
|
|
21
|
+
|
|
3
22
|
## 0.5.3 — 2026-11-11
|
|
4
23
|
|
|
5
24
|
- Fix reply preview overflow and add an accessible cancel button and reply icon.
|
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Restart OpenCode. Ask an agent to create a room named `dev`, or enter `/room cre
|
|
|
22
22
|
On a machine reachable by the other devices, start the server. Replace `your-password` with a shared password:
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
-
bunx @alexsun-top/opencode-chat-room@0.5.
|
|
25
|
+
bunx @alexsun-top/opencode-chat-room@0.5.4 --host 0.0.0.0 --port 4399 --token 'your-password'
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
On each machine running OpenCode, set the server address and the same password, then start OpenCode from that environment:
|
package/README.zh-CN.md
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
在一台可被其他设备访问的机器上启动服务器,把 `换成自己的密码` 换成共享密码:
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
-
bunx @alexsun-top/opencode-chat-room@0.5.
|
|
25
|
+
bunx @alexsun-top/opencode-chat-room@0.5.4 --host 0.0.0.0 --port 4399 --token '换成自己的密码'
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
在每台运行 OpenCode 的机器上设置服务器地址和相同密码,再从该环境启动 OpenCode:
|
package/package.json
CHANGED
package/server/admin-auth.ts
CHANGED
|
@@ -11,6 +11,8 @@ export function agentHeadersMatch(request: Request, binding: Binding): boolean {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export function hasAdminCapability(request: Request, binding: Binding): boolean {
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
if (!agentHeadersMatch(request, binding)) return false;
|
|
15
|
+
// Operator designation is the grant; the optional claim capability is legacy.
|
|
16
|
+
if (!binding.capability_hash) return true;
|
|
17
|
+
return matchesHash(request.headers.get("x-chat-admin-capability") ?? "", binding.capability_hash);
|
|
16
18
|
}
|
package/server/assets/base.css
CHANGED
|
@@ -85,6 +85,7 @@ export function initAdmin(app) {
|
|
|
85
85
|
if (!agents.length) status(app.t("noAgents")); else status("");
|
|
86
86
|
}
|
|
87
87
|
$("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
|
|
88
|
+
app.verifyAdminToken = verifyToken;
|
|
88
89
|
$("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
|
|
89
90
|
$("#btnRefreshAdmin").addEventListener("click", async () => {
|
|
90
91
|
const id = $("#adminRoomSelect").value;
|
|
@@ -110,15 +111,9 @@ export function initAdmin(app) {
|
|
|
110
111
|
setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
|
|
111
112
|
await loadBinding(generation);
|
|
112
113
|
if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value) return;
|
|
113
|
-
const box = $("#adminEnrollment"),
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
|
|
117
|
-
copy.addEventListener("click", async () => {
|
|
118
|
-
try { if (!navigator.clipboard?.writeText) throw new Error(); await navigator.clipboard.writeText(instruction); status(app.t("enrollmentCopied")); }
|
|
119
|
-
catch { fallback.value = instruction; box.replaceChildren(warning, fallback, copy); fallback.focus(); fallback.select(); status(warning.textContent || ""); }
|
|
120
|
-
});
|
|
121
|
-
box.replaceChildren(warning, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
|
|
114
|
+
const box = $("#adminEnrollment"), note = document.createElement("p");
|
|
115
|
+
note.textContent = app.t("adminDesignated");
|
|
116
|
+
box.replaceChildren(note); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
|
|
122
117
|
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
123
118
|
finally { button.disabled = false; }
|
|
124
119
|
});
|
|
@@ -54,7 +54,14 @@ export function initAnnouncements(app) {
|
|
|
54
54
|
items = Array.isArray(result.announcements) ? result.announcements : [];
|
|
55
55
|
status("");
|
|
56
56
|
const chosen = items.find((item) => item.name === selected);
|
|
57
|
-
if (!chosen)
|
|
57
|
+
if (!chosen) {
|
|
58
|
+
const stale = selected && draft(id, selected);
|
|
59
|
+
if (stale) {
|
|
60
|
+
drafts.set(key(id, ""), { ...stale, name: $("#announcementName").value.trim() || stale.name });
|
|
61
|
+
drafts.delete(key(id, selected));
|
|
62
|
+
}
|
|
63
|
+
select(null);
|
|
64
|
+
} else select(chosen);
|
|
58
65
|
render();
|
|
59
66
|
} catch (error) {
|
|
60
67
|
if (roomId() !== id || context !== roomGeneration || generation !== request) return;
|
|
@@ -83,6 +90,15 @@ export function initAnnouncements(app) {
|
|
|
83
90
|
generation++; items = [...items.filter((item) => item.name !== name), result.announcement]; render();
|
|
84
91
|
clearDraftIfUnchanged(id, draftName, captured);
|
|
85
92
|
if (editorMatches(captured)) { select(result.announcement); status(app.t("announcementSaved")); }
|
|
93
|
+
else if (!selected) {
|
|
94
|
+
// Keep editing the newer draft under the name the create just reserved.
|
|
95
|
+
drafts.delete(key(id, draftName));
|
|
96
|
+
selected = result.announcement.name;
|
|
97
|
+
$("#announcementName").value = selected; $("#announcementName").readOnly = true;
|
|
98
|
+
$("#btnDeleteAnnouncement").hidden = false;
|
|
99
|
+
drafts.set(key(id, selected), { name: selected, content: $("#announcementContent").value });
|
|
100
|
+
render();
|
|
101
|
+
}
|
|
86
102
|
}
|
|
87
103
|
} catch (error) {
|
|
88
104
|
if (currentRoom(id, context) && editorMatches(captured)) status(error.status === 403 ? error.message : app.t("announcementLoadFailed"));
|
|
@@ -112,7 +112,10 @@ export function initAttachments(app) {
|
|
|
112
112
|
item.cancelled = true; item.xhr?.abort();
|
|
113
113
|
if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
114
114
|
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
115
|
-
if (remaining.length)
|
|
115
|
+
if (remaining.length) {
|
|
116
|
+
drafts.set(id, remaining);
|
|
117
|
+
if (statuses.get(id)?.error && !remaining.some((entry) => entry.status === "failed")) statuses.delete(id);
|
|
118
|
+
} else { drafts.delete(id); statuses.delete(id); }
|
|
116
119
|
if (roomId() === id) render();
|
|
117
120
|
}
|
|
118
121
|
function clearRoom(id) {
|
|
@@ -91,11 +91,24 @@ function lengthBefore(root, target, position) {
|
|
|
91
91
|
}
|
|
92
92
|
|
|
93
93
|
export function setCaret(editor, offset) {
|
|
94
|
-
const selection = getSelection(), range = document.createRange()
|
|
95
|
-
|
|
94
|
+
const selection = getSelection(), range = document.createRange();
|
|
95
|
+
// Chromium starts IME composition poorly at an element boundary next to a
|
|
96
|
+
// non-editable chip; keep the caret inside a real text node instead.
|
|
97
|
+
const [container, index] = textPoint(editorPoint(editor, offset));
|
|
98
|
+
range.setStart(container, index); range.collapse(true);
|
|
96
99
|
selection.removeAllRanges(); selection.addRange(range);
|
|
97
100
|
}
|
|
98
101
|
|
|
102
|
+
function textPoint([container, offset]) {
|
|
103
|
+
if (container.nodeType !== Node.ELEMENT_NODE) return [container, offset];
|
|
104
|
+
const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
|
|
105
|
+
if (child?.nodeType === Node.TEXT_NODE) return [child, 0];
|
|
106
|
+
if (previous?.nodeType === Node.TEXT_NODE) return [previous, previous.length];
|
|
107
|
+
const text = document.createTextNode("");
|
|
108
|
+
container.insertBefore(text, child || null);
|
|
109
|
+
return [text, 0];
|
|
110
|
+
}
|
|
111
|
+
|
|
99
112
|
export function setEditorSelection(editor, start, end = start) {
|
|
100
113
|
const range = document.createRange(), selection = getSelection();
|
|
101
114
|
const first = editorPoint(editor, start), last = editorPoint(editor, end);
|
|
@@ -61,6 +61,7 @@ export function initEvents(app) {
|
|
|
61
61
|
const readTs = entry?.readTs || app.state.lastReadTs.get(roomId) || 0;
|
|
62
62
|
const boundary = readTs && entry?.room.messages.find((message) => message.createdAt > readTs);
|
|
63
63
|
if (boundary && align(boundary.id, 0)) return { messageId: boundary.id };
|
|
64
|
+
if (!saved && !boundary) return false;
|
|
64
65
|
return saved?.messageId || readTs ? { messageId: saved?.messageId || null, missing: true } : false;
|
|
65
66
|
};
|
|
66
67
|
function closeRoomDrawer(restore = true) {
|
|
@@ -227,6 +228,9 @@ export function initEvents(app) {
|
|
|
227
228
|
if (event.deltaY < 0 && thread.scrollTop <= 0 || event.deltaY > 0 && gap <= 2) event.preventDefault();
|
|
228
229
|
}, { passive: false });
|
|
229
230
|
thread.addEventListener("touchmove", markScrollIntent, { passive: true });
|
|
231
|
+
thread.addEventListener("keydown", (event) => {
|
|
232
|
+
if (/^(PageDown|PageUp|End|Home|ArrowDown|ArrowUp| )$/.test(event.key)) markScrollIntent();
|
|
233
|
+
});
|
|
230
234
|
thread.addEventListener("pointerdown", (event) => {
|
|
231
235
|
if (event.clientX >= thread.getBoundingClientRect().right - 18) markScrollIntent();
|
|
232
236
|
});
|
|
@@ -234,7 +238,7 @@ export function initEvents(app) {
|
|
|
234
238
|
const adjusting = (app.state.resizeScrollAdjusting || app.state.layoutScrollAdjusting)
|
|
235
239
|
&& performance.now() > app.state.userScrollIntentUntil;
|
|
236
240
|
if (!adjusting || performance.now() <= app.state.userScrollIntentUntil) captureReadingPosition();
|
|
237
|
-
if (!adjusting && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) void app.markActiveRoomRead();
|
|
241
|
+
if (!adjusting && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) void app.markActiveRoomRead(performance.now() <= app.state.userScrollIntentUntil);
|
|
238
242
|
app.queueReceiptRefresh();
|
|
239
243
|
if (!adjusting) app.queueReceiptObservation();
|
|
240
244
|
app.updateJump();
|
|
@@ -327,6 +331,7 @@ function saveAccessToken(button, app) {
|
|
|
327
331
|
try { persistent = localStorage.getItem("chat.token") === LS.token; } catch { /* Memory fallback is tab-scoped. */ }
|
|
328
332
|
app.flash(button, persistent ? "saved" : "savedMemory");
|
|
329
333
|
void app.refreshRoomList();
|
|
334
|
+
void app.verifyAdminToken?.();
|
|
330
335
|
app.retryPendingAction();
|
|
331
336
|
}
|
|
332
337
|
|
|
@@ -132,14 +132,19 @@ async function loadResourceCard(card, roomId, app) {
|
|
|
132
132
|
if (previewKind(type)) {
|
|
133
133
|
const preview = resourceButton("resourcePreview", resource.name, () => previewResource(card, roomId, id, resource, type, preview, app, status), app);
|
|
134
134
|
actions.append(preview);
|
|
135
|
+
// Media you sent yourself is shown inline; other people's media stays collapsed.
|
|
136
|
+
if (card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
|
|
135
137
|
}
|
|
136
138
|
} catch { if (card.isConnected) setResourceError(card, app); }
|
|
137
139
|
}
|
|
140
|
+
function setResourceButton(button, key, name, app) {
|
|
141
|
+
button.dataset.i18n = key; button.textContent = app.t(key);
|
|
142
|
+
button.setAttribute("aria-label", `${app.t(key)}: ${name}`);
|
|
143
|
+
}
|
|
138
144
|
function resourceButton(key, name, action, app) {
|
|
139
145
|
const button = document.createElement("button");
|
|
140
146
|
button.type = "button"; button.className = "btn ghost small resource-button";
|
|
141
|
-
button
|
|
142
|
-
button.setAttribute("aria-label", `${app.t(key)}: ${name}`);
|
|
147
|
+
setResourceButton(button, key, name, app);
|
|
143
148
|
button.addEventListener("click", action); return button;
|
|
144
149
|
}
|
|
145
150
|
async function downloadResource(card, roomId, id, resource, app, status, button) {
|
|
@@ -161,30 +166,45 @@ async function previewResource(card, roomId, id, resource, type, button, app, st
|
|
|
161
166
|
button.disabled = true;
|
|
162
167
|
if (card._previewElement) {
|
|
163
168
|
try {
|
|
164
|
-
await app.preserveReadingLayout(() =>
|
|
169
|
+
await app.preserveReadingLayout(() => {
|
|
170
|
+
card._previewElement.remove();
|
|
171
|
+
setResourceButton(button, "resourcePreview", resource.name, app); button.disabled = false;
|
|
172
|
+
});
|
|
165
173
|
URL.revokeObjectURL(card._resourceUrl); previewUrls.delete(card); delete card._resourceUrl; delete card._previewElement;
|
|
166
|
-
if (card.isConnected) { button.dataset.i18n = "resourcePreview"; button.textContent = app.t("resourcePreview"); }
|
|
167
174
|
} catch {
|
|
168
175
|
if (!card.isConnected) return;
|
|
169
176
|
} finally { if (card.isConnected) button.disabled = false; }
|
|
170
177
|
return;
|
|
171
178
|
}
|
|
172
179
|
status.textContent = app.t("resourceLoading");
|
|
173
|
-
let url;
|
|
180
|
+
let url, media;
|
|
181
|
+
const fail = () => {
|
|
182
|
+
media?.remove(); media = undefined;
|
|
183
|
+
if (url) { URL.revokeObjectURL(url); url = undefined; }
|
|
184
|
+
setResourceButton(button, "resourcePreview", resource.name, app); button.disabled = false;
|
|
185
|
+
if (card.isConnected) status.textContent = app.t("resourceFailed");
|
|
186
|
+
};
|
|
174
187
|
try {
|
|
175
188
|
const blob = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}/content`);
|
|
176
189
|
if (!card.isConnected) return;
|
|
177
190
|
url = URL.createObjectURL(blob);
|
|
178
|
-
const kind = previewKind(type)
|
|
191
|
+
const kind = previewKind(type);
|
|
192
|
+
media = document.createElement(kind);
|
|
193
|
+
const ready = waitForMediaSize(media, kind);
|
|
179
194
|
if (kind === "img") media.alt = resource.name;
|
|
180
195
|
else { media.controls = true; media.preload = "metadata"; }
|
|
181
|
-
media.addEventListener("error",
|
|
196
|
+
media.addEventListener("error", fail, { once: true });
|
|
182
197
|
media.src = url;
|
|
183
|
-
|
|
184
|
-
|
|
198
|
+
// Update the control inside the layout step: a stalled animation frame must not
|
|
199
|
+
// leave the preview open with a disabled button.
|
|
200
|
+
await app.preserveReadingLayout(async () => {
|
|
201
|
+
status.textContent = ""; card.append(media);
|
|
202
|
+
setResourceButton(button, "resourceHide", resource.name, app); button.disabled = false;
|
|
203
|
+
await ready;
|
|
204
|
+
});
|
|
205
|
+
if (!card.isConnected) { fail(); return; }
|
|
185
206
|
card._resourceUrl = url; card._previewElement = media; previewUrls.set(card, url); watchPreviewRemoval();
|
|
186
|
-
|
|
187
|
-
} catch { if (url) URL.revokeObjectURL(url); if (card.isConnected) status.textContent = app.t("resourceFailed"); }
|
|
207
|
+
} catch { fail(); }
|
|
188
208
|
finally { if (card.isConnected) button.disabled = false; }
|
|
189
209
|
}
|
|
190
210
|
function waitForMediaSize(media, kind) {
|
|
@@ -77,8 +77,10 @@ export function initMentions(app) {
|
|
|
77
77
|
if (input.value.slice(mention.start, end) !== `@${mention.query}`) return app.closeMention();
|
|
78
78
|
replaceEditorRange(input, mention.start, end, `<at>@${name}</at>`);
|
|
79
79
|
app.closeMention();
|
|
80
|
-
|
|
80
|
+
// Chrome can reset the selection while focus() lands; restore the caret last.
|
|
81
81
|
input.focus({ preventScroll: true });
|
|
82
|
+
input.setCaret?.(mention.start + `<at>@${name}</at>`.length);
|
|
83
|
+
input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
|
|
82
84
|
};
|
|
83
85
|
}
|
|
84
86
|
|
|
@@ -11,6 +11,7 @@ export function initMessages(app) {
|
|
|
11
11
|
|
|
12
12
|
app.autoGrow = (textarea) => {
|
|
13
13
|
const thread = $("#thread"), atBottom = Boolean(app.state.room && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
14
|
+
const scrollTop = textarea.scrollTop;
|
|
14
15
|
textarea.style.overflowY = "hidden";
|
|
15
16
|
const style = getComputedStyle(textarea), line = parseFloat(style.lineHeight);
|
|
16
17
|
const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
|
|
@@ -25,6 +26,8 @@ export function initMessages(app) {
|
|
|
25
26
|
const overflow = textarea.scrollHeight > limit + 1;
|
|
26
27
|
textarea.style.height = `${Math.min(textarea.scrollHeight, limit) + border}px`;
|
|
27
28
|
textarea.style.overflowY = overflow ? "auto" : "hidden";
|
|
29
|
+
// Collapsing the height to measure content resets scrollTop; keep the caret view where it was.
|
|
30
|
+
if (overflow) textarea.scrollTop = scrollTop;
|
|
28
31
|
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
29
32
|
};
|
|
30
33
|
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
@@ -100,7 +103,7 @@ export function initMessages(app) {
|
|
|
100
103
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
101
104
|
app.updateBadge();
|
|
102
105
|
app.updateJump();
|
|
103
|
-
void app.markActiveRoomRead();
|
|
106
|
+
void app.markActiveRoomRead(true);
|
|
104
107
|
};
|
|
105
108
|
app.updateJump = () => {
|
|
106
109
|
const thread = $("#thread");
|
|
@@ -113,33 +116,55 @@ export function initMessages(app) {
|
|
|
113
116
|
badge.hidden = app.state.unread === 0;
|
|
114
117
|
app.updateTitle();
|
|
115
118
|
};
|
|
116
|
-
app.markActiveRoomRead = async () => {
|
|
119
|
+
app.markActiveRoomRead = async (interactive = false) => {
|
|
117
120
|
const room = app.state.room, entry = room && app.state.rooms.get(room.id);
|
|
118
121
|
const generation = app.state.pollGeneration;
|
|
119
122
|
const thread = $("#thread");
|
|
120
|
-
if (!room || !entry || document.hidden || !document.hasFocus()
|
|
123
|
+
if (!room || !entry || document.hidden || (!interactive && !document.hasFocus())
|
|
121
124
|
|| thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
|
|
122
125
|
if (app.state.readAnchorGuard?.roomId === room.id) {
|
|
123
|
-
if (performance.now() > app.state.userScrollIntentUntil) return;
|
|
126
|
+
if (!interactive && performance.now() > app.state.userScrollIntentUntil) return;
|
|
124
127
|
app.state.readAnchorGuard = null;
|
|
125
128
|
}
|
|
126
129
|
const timestamp = room.messages.reduce((latest, message) => Math.max(latest, message.createdAt), entry.readTs);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
130
|
+
const unreadBefore = entry.unreadIds.size, overflowBefore = entry.unreadOverflow;
|
|
131
|
+
let advanced = false;
|
|
132
|
+
if (timestamp > entry.readTs) {
|
|
133
|
+
try {
|
|
134
|
+
await app.api("/read", {
|
|
135
|
+
method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
|
|
136
|
+
});
|
|
137
|
+
if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
|
|
138
|
+
entry.readTs = timestamp;
|
|
139
|
+
app.saveReadTs(room.id, timestamp);
|
|
140
|
+
entry.unreadOverflow = false;
|
|
141
|
+
advanced = true;
|
|
142
|
+
} catch { return; /* The next active poll will retry the read watermark. */ }
|
|
143
|
+
}
|
|
144
|
+
// Unanswered questions stay unread until answered.
|
|
145
|
+
const known = new Map(room.messages.map((message) => [message.id, message]));
|
|
146
|
+
const answered = new Set(room.messages.filter((message) => message.answerToMessageID).map((message) => message.answerToMessageID));
|
|
147
|
+
const listed = app.unansweredQuestionIds?.();
|
|
148
|
+
const open = (message) => {
|
|
149
|
+
if (!message.isQuestion || message.answeredByMessageID) return false;
|
|
150
|
+
// A question outside the message window is judged by the server list.
|
|
151
|
+
return known.has(message.id) ? !answered.has(message.id) : !listed || listed.has(message.id);
|
|
152
|
+
};
|
|
153
|
+
for (const [id, message] of entry.unreadIds) {
|
|
154
|
+
const current = known.get(id) || message;
|
|
155
|
+
if (current.createdAt <= entry.readTs && !open(current)) entry.unreadIds.delete(id);
|
|
156
|
+
else if (known.has(id)) entry.unreadIds.set(id, current);
|
|
157
|
+
}
|
|
158
|
+
for (const message of room.messages) {
|
|
159
|
+
if (open(message) && !isOwnMessage(message, app, room)) entry.unreadIds.set(message.id, message);
|
|
160
|
+
}
|
|
161
|
+
app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
162
|
+
if (advanced || entry.unreadIds.size !== unreadBefore || entry.unreadOverflow !== overflowBefore) {
|
|
138
163
|
app.updateBadge();
|
|
139
164
|
app.updateJump();
|
|
140
165
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
141
166
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
142
|
-
}
|
|
167
|
+
}
|
|
143
168
|
};
|
|
144
169
|
|
|
145
170
|
app.renderMessage = (message, live) => {
|
|
@@ -316,11 +341,20 @@ export function initMessages(app) {
|
|
|
316
341
|
});
|
|
317
342
|
app.completeAttachments?.(room.id, message.ids);
|
|
318
343
|
if (app.state.room?.id !== room.id) return;
|
|
319
|
-
app.state.room = updated;
|
|
320
344
|
const entry = app.state.rooms.get(room.id);
|
|
345
|
+
// The POST snapshot is older than anything polling received while it was
|
|
346
|
+
// in flight; merge instead of dropping those messages.
|
|
347
|
+
let current = updated;
|
|
348
|
+
if (entry) {
|
|
349
|
+
const merged = new Map([...entry.room.messages, ...updated.messages].map((item) => [item.id, { ...item, roomId: updated.id }]));
|
|
350
|
+
const messages = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
351
|
+
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
352
|
+
current = { ...updated, messages };
|
|
353
|
+
}
|
|
354
|
+
app.state.room = current;
|
|
321
355
|
if (entry) {
|
|
322
|
-
entry.room =
|
|
323
|
-
const latest =
|
|
356
|
+
entry.room = current;
|
|
357
|
+
const latest = current.messages.at(-1);
|
|
324
358
|
if (latest) setRoomPreview(entry, latest);
|
|
325
359
|
}
|
|
326
360
|
app.renderMessages(true);
|
|
@@ -418,6 +452,7 @@ export function initMessages(app) {
|
|
|
418
452
|
if (added || unreadChanged || entry && previousUnreadOverflow !== entry.unreadOverflow) {
|
|
419
453
|
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : app.state.unread + added;
|
|
420
454
|
app.updateBadge();
|
|
455
|
+
app.updateJump();
|
|
421
456
|
}
|
|
422
457
|
if (rendered.skipped === 0) void app.markActiveRoomRead();
|
|
423
458
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
@@ -7,6 +7,10 @@ export function initQuestions(app) {
|
|
|
7
7
|
let request = 0;
|
|
8
8
|
const panel = $("#questionPanel"), trigger = $("#btnQuestions"), list = $("#questionList"), status = $("#questionStatus");
|
|
9
9
|
app.isQuestionSending = () => Boolean(questionMode.get(app.state.room?.id));
|
|
10
|
+
// Undefined until the server list for this room has loaded; callers must not
|
|
11
|
+
// treat that as "no open questions".
|
|
12
|
+
app.unansweredQuestionIds = (roomId = app.state.room?.id) => pending.has(roomId)
|
|
13
|
+
? new Set((pending.get(roomId) || []).map((item) => item.id)) : undefined;
|
|
10
14
|
$("#questionToggle").addEventListener("change", (event) => {
|
|
11
15
|
if (app.state.room) questionMode.set(app.state.room.id, event.target.checked);
|
|
12
16
|
});
|
|
@@ -29,6 +33,9 @@ export function initQuestions(app) {
|
|
|
29
33
|
const items = pending.get(roomId) || [];
|
|
30
34
|
const active = app.state.room?.id === roomId;
|
|
31
35
|
if (active) {
|
|
36
|
+
const signature = `${roomId}\0${app.locale}\0${selected.get(roomId) || ""}\0${items.map((question) => `${question.id}\0${question.text}`).join("\u0001")}`;
|
|
37
|
+
if (list.dataset.signature === signature) { renderReply(roomId); return; }
|
|
38
|
+
list.dataset.signature = signature;
|
|
32
39
|
$("#questionBadge").textContent = items.length > 99 ? "99+" : String(items.length);
|
|
33
40
|
$("#questionBadge").hidden = !items.length;
|
|
34
41
|
trigger.setAttribute("aria-label", `${app.t("questions")}: ${items.length}`);
|
|
@@ -218,6 +225,10 @@ export function initQuestions(app) {
|
|
|
218
225
|
|
|
219
226
|
function applyAnswer(roomId, questionId, result) {
|
|
220
227
|
const entry = app.state.rooms.get(roomId);
|
|
228
|
+
if (entry && result.answer) {
|
|
229
|
+
const question = entry.room.messages.find((item) => item.id === questionId);
|
|
230
|
+
if (question) question.answeredByMessageID = result.answer.id;
|
|
231
|
+
}
|
|
221
232
|
if (entry && result.answer && !entry.room.messages.some((item) => item.id === result.answer.id)) {
|
|
222
233
|
entry.room.messages.push({ ...result.answer, roomId }); entry.room.messages.sort((a, b) => a.createdAt - b.createdAt);
|
|
223
234
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
@@ -32,7 +32,8 @@ export function initReminders(app) {
|
|
|
32
32
|
text.textContent = reminder.text; detail.className = "hint";
|
|
33
33
|
const timezone = reminder.schedule.timezone;
|
|
34
34
|
const schedule = reminder.schedule.type === "once" ? formatTime(reminder.schedule.at, timezone) : `${reminder.schedule.expression} · ${timezone}`;
|
|
35
|
-
|
|
35
|
+
const next = reminder.schedule.type === "cron" && reminder.nextRunAt ? ` · ${app.t("reminderNext", { time: formatTime(reminder.nextRunAt, timezone) })}` : "";
|
|
36
|
+
detail.textContent = `${schedule}${reminder.paused ? ` · ${app.t("reminderPaused")}` : next}`;
|
|
36
37
|
const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "btn ghost small"; toggle.textContent = app.t(reminder.paused ? "reminderResume" : "reminderPause");
|
|
37
38
|
toggle.addEventListener("click", () => void update(reminder, !reminder.paused));
|
|
38
39
|
const remove = document.createElement("button"); remove.type = "button"; remove.className = "btn ghost small danger-text"; remove.textContent = app.t("reminderDelete");
|
|
@@ -51,8 +52,7 @@ export function initReminders(app) {
|
|
|
51
52
|
} catch (error) { if (current(id, context) && generation === request) status(errorText(error)); }
|
|
52
53
|
}
|
|
53
54
|
function validCron(expression) {
|
|
54
|
-
|
|
55
|
-
return fields.length === 5 && fields.every((field) => /^[0-9*/?,\-]+$/.test(field));
|
|
55
|
+
return expression.trim().split(/\s+/).length === 5;
|
|
56
56
|
}
|
|
57
57
|
async function update(reminder, paused) {
|
|
58
58
|
const id = roomId(), context = roomGeneration;
|
|
@@ -13,12 +13,15 @@ export async function watchRoom(roomId, app) {
|
|
|
13
13
|
if (result.member !== true || !Array.isArray(result.items) || app.state.room?.id === roomId) return;
|
|
14
14
|
const previousReceivedTs = entry.receivedTs || 0;
|
|
15
15
|
const sawSystem = result.items.some((message) => message.senderId === "system");
|
|
16
|
+
const before = new Set(entry.room.messages.map((message) => message.id));
|
|
16
17
|
for (const message of result.items) {
|
|
17
|
-
if (!isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
18
|
-
if (
|
|
18
|
+
if (message.createdAt > entry.readTs && !isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
19
|
+
if (message.answerToMessageID && entry.unreadIds.get(message.answerToMessageID)?.isQuestion) entry.unreadIds.delete(message.answerToMessageID);
|
|
20
|
+
if (!before.has(message.id)) entry.room.messages.push({ ...message, roomId });
|
|
19
21
|
if (message.createdAt >= entry.previewAt) setRoomPreview(entry, message);
|
|
20
22
|
}
|
|
21
23
|
entry.receivedTs = result.items.reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
24
|
+
entry.unreadOverflow = Boolean(result.hasMore);
|
|
22
25
|
if (sawSystem || result.hasMore) {
|
|
23
26
|
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
24
27
|
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
@@ -26,8 +29,13 @@ export async function watchRoom(roomId, app) {
|
|
|
26
29
|
entry.room.messages = [...new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message])).values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
|
|
27
30
|
const newest = latest.messages.at(-1);
|
|
28
31
|
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
32
|
+
// A full refresh pages past the inbox window; count what arrived since the last look.
|
|
33
|
+
for (const message of latest.messages) {
|
|
34
|
+
if (message.answeredByMessageID) entry.unreadIds.delete(message.id);
|
|
35
|
+
if (message.createdAt > previousReceivedTs && message.createdAt > entry.readTs && !isOwnMessage(message, app, entry.room, entry.name) && !entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
36
|
+
}
|
|
37
|
+
if (newest && Number.isSafeInteger(newest.createdAt)) entry.receivedTs = Math.max(entry.receivedTs, newest.createdAt);
|
|
29
38
|
}
|
|
30
|
-
entry.unreadOverflow = Boolean(result.hasMore);
|
|
31
39
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
32
40
|
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
33
41
|
} catch (error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { isOwnMessage } from "./messages.js";
|
|
2
3
|
import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
|
|
3
4
|
import { watchRoom } from "./room-watcher.js";
|
|
4
5
|
|
|
@@ -50,10 +51,16 @@ export function initRooms(app) {
|
|
|
50
51
|
const entry = existing || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0, receivedTs: room.messages.at(-1)?.createdAt ?? 0 };
|
|
51
52
|
entry.unreadIds ||= new Map();
|
|
52
53
|
entry.unreadOverflow ||= false;
|
|
53
|
-
|
|
54
|
+
const latest = room.messages.at(-1), savedReadTs = app.state.lastReadTs.get(room.id);
|
|
55
|
+
entry.readTs ||= savedReadTs || 0;
|
|
54
56
|
entry.room = room;
|
|
55
57
|
entry.name = name;
|
|
56
|
-
|
|
58
|
+
// Only rebuild unread history when this browser already has a read watermark;
|
|
59
|
+
// a never-opened room is not a burst of unread messages.
|
|
60
|
+
if (!existing && savedReadTs !== undefined) for (const message of room.messages) {
|
|
61
|
+
const unread = message.createdAt > entry.readTs || (message.isQuestion && !message.answeredByMessageID);
|
|
62
|
+
if (unread && !isOwnMessage(message, app, room, name)) entry.unreadIds.set(message.id, message);
|
|
63
|
+
}
|
|
57
64
|
entry.receivedTs ??= latest?.createdAt ?? 0;
|
|
58
65
|
if (latest && (!existing || latest.createdAt >= entry.previewAt)) setRoomPreview(entry, latest);
|
|
59
66
|
app.state.rooms.set(room.id, entry);
|
|
@@ -183,7 +190,7 @@ export function initRooms(app) {
|
|
|
183
190
|
app.disposeRoomAttachments?.(roomId);
|
|
184
191
|
if (active) {
|
|
185
192
|
app.state.navigationGeneration++;
|
|
186
|
-
app.saveDraft(roomId, $("#msgInput").
|
|
193
|
+
app.saveDraft(roomId, $("#msgInput").draftValue);
|
|
187
194
|
app.captureReadingPosition?.();
|
|
188
195
|
app.stopPolling();
|
|
189
196
|
app.closeMention();
|
|
@@ -386,7 +393,7 @@ export function initRooms(app) {
|
|
|
386
393
|
status.className = "r-status";
|
|
387
394
|
app.setText(status, entry ? "joined" : "joinAction");
|
|
388
395
|
button.append(name, kind, meta, preview, status);
|
|
389
|
-
const unread = entry?.
|
|
396
|
+
const unread = entry && app.state.room?.id !== room.id ? (entry.unreadOverflow ? 100 : entry.unreadIds.size) : 0;
|
|
390
397
|
if (unread) {
|
|
391
398
|
const badge = document.createElement("span");
|
|
392
399
|
badge.className = "r-badge";
|
|
@@ -235,8 +235,8 @@ const messages = {
|
|
|
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
|
|
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.",
|
|
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 administrator", revokeDesignation: "Revoke designation", globalStatus: "Global status", adminTasks: "Tasks", taskText: "Task", dispatchTask: "Dispatch task", timers: "Timers", planName: "Timer name", createTimer: "Create timer", tokenRequired: "The server requires an access token (401).",
|
|
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.", adminDesignated: "Administrator designation is active immediately and stays until you revoke it.", revokeConfirm: "Revoke this admin designation? The normal room will remain.", updateTask: "Update task", task_pending: "Pending", task_working: "Working", task_blocked: "Blocked", task_completed: "Completed", task_cancelled: "Cancelled", nextRun: ({ time, minutes }) => `Every ${minutes} min · next ${time}`, paused: "Paused", pauseTimer: "Pause", resumeTimer: "Resume", deleteTimer: "Delete", deleteTimerConfirm: ({ name }) => `Delete timer “${name}”?`,
|
|
240
240
|
leave: "Leave", reconnecting: "Connection lost. Retrying…", messageList: "Message list",
|
|
241
241
|
noMessages: "No messages yet. Say something.", latestMessages: "Back to latest messages",
|
|
242
242
|
mentionMembers: "Choose a member to mention", messagePlaceholder: "Message · Enter to send",
|
|
@@ -311,8 +311,8 @@ const messages = {
|
|
|
311
311
|
answerFailed: "回复失败,草稿仍已保留。", answerTooLong: "回复不能超过 2,000 个字符。", questionAlreadyAnswered: "此问题已由其他人回答。",
|
|
312
312
|
sendAsQuestion: "作为问题发送",
|
|
313
313
|
adminBindingGuide: "选择管理员房间和其中的 Agent,再将邀请私下发送给该 Agent 完成设置。", adminRoomLabel: "管理员房间", adminDesignateAgent: "邀请 Agent",
|
|
314
|
-
adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "请选择管理员房间内的 Agent。管理员可以管理所有房间。", adminRoomBadge: "管理", targetAgent: "已注册 Agent", designate: "
|
|
315
|
-
adminLoading: "正在加载管理面板…", refreshAdmin: "刷新", adminRoomBadge: "管理", chooseAdminRoom: "选择普通房间", chooseTargetRoom: "选择 Agent 房间", chooseAgent: "选择已注册 Agent", taskTargetRoom: "任务目标房间", taskTargetAgent: "任务目标 Agent", createAdminRoomFirst: "请先按普通流程创建房间,再选作管理房间。", noAgents: "没有已注册的 Agent", selectAdminAgent: "请选择管理房间和已注册的 Agent。",
|
|
314
|
+
adminAccess: "管理", adminToken: "管理令牌", openAdministration: "打开管理面板", administration: "管理面板", designations: "管理绑定", adminRoom: "管理员房间", targetRoom: "Agent 所属房间", adminScopeNote: "请选择管理员房间内的 Agent。管理员可以管理所有房间。", adminRoomBadge: "管理", targetAgent: "已注册 Agent", designate: "指定管理员", revokeDesignation: "撤销绑定", globalStatus: "全局状态", adminTasks: "任务", taskText: "任务内容", dispatchTask: "派发任务", timers: "定时任务", planName: "定时任务名称", createTimer: "创建定时任务",
|
|
315
|
+
adminLoading: "正在加载管理面板…", refreshAdmin: "刷新", adminRoomBadge: "管理", chooseAdminRoom: "选择普通房间", chooseTargetRoom: "选择 Agent 房间", chooseAgent: "选择已注册 Agent", taskTargetRoom: "任务目标房间", taskTargetAgent: "任务目标 Agent", createAdminRoomFirst: "请先按普通流程创建房间,再选作管理房间。", noAgents: "没有已注册的 Agent", selectAdminAgent: "请选择管理房间和已注册的 Agent。", adminDesignated: "管理员已立即生效,长期有效,直到撤销。", revokeConfirm: "撤销此管理绑定?普通房间会保留。", updateTask: "更新任务", task_pending: "待处理", task_working: "进行中", task_blocked: "受阻", task_completed: "已完成", task_cancelled: "已取消", nextRun: ({ time, minutes }) => `每 ${minutes} 分钟 · 下次 ${time}`, paused: "已暂停", pauseTimer: "暂停", resumeTimer: "恢复", deleteTimer: "删除", deleteTimerConfirm: ({ name }) => `删除定时任务“${name}”?`,
|
|
316
316
|
tokenRequired: "服务器要求访问令牌(401)。", leave: "离开", reconnecting: "连接中断,正在重试…",
|
|
317
317
|
messageList: "消息列表", noMessages: "还没有消息,说点什么吧。", latestMessages: "回到最新消息",
|
|
318
318
|
mentionMembers: "选择要提及的成员", messagePlaceholder: "输入消息,Enter 发送",
|
package/server/chat-server.ts
CHANGED
|
@@ -8,7 +8,7 @@ import RoomService, {
|
|
|
8
8
|
type Message,
|
|
9
9
|
type Room,
|
|
10
10
|
} from "../src/room-service";
|
|
11
|
-
import { answerQuestion, sendReply, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/store";
|
|
11
|
+
import { acknowledgeQueued, answerQuestion, appendRoomMessage, sendReply, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/store";
|
|
12
12
|
import {
|
|
13
13
|
admissionMatches,
|
|
14
14
|
clearPendingAdmission,
|
|
@@ -17,6 +17,7 @@ import { readInbox } from "./inbox";
|
|
|
17
17
|
import { isReceiverOwnerID } from "../src/receiver-owner";
|
|
18
18
|
import { claimWake, touchActive, wakeMentionedSessions } from "./wake";
|
|
19
19
|
import { historyRoute } from "./history-route";
|
|
20
|
+
import { jsonObject } from "./json-body";
|
|
20
21
|
import { roomManagement } from "./newrooms";
|
|
21
22
|
import { memberRoutes } from "./member-routes";
|
|
22
23
|
import { resourceRoutes } from "./resource-routes";
|
|
@@ -161,7 +162,8 @@ async function handle(req: Request): Promise<Response> {
|
|
|
161
162
|
const management = await roomManagement(req, url);
|
|
162
163
|
if (management) return management;
|
|
163
164
|
if (req.method === "POST" && p === "/rooms") {
|
|
164
|
-
const body =
|
|
165
|
+
const body = await jsonObject<Record<string, string>>(req);
|
|
166
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
165
167
|
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
166
168
|
return json({ error: "invalid receiver ownership" }, 400);
|
|
167
169
|
}
|
|
@@ -226,13 +228,14 @@ async function handle(req: Request): Promise<Response> {
|
|
|
226
228
|
while (result.items.length === 0 && Date.now() < deadline) {
|
|
227
229
|
// ponytail: 2s between disk scans (orc-1 #7) — 1s × 25 iterations
|
|
228
230
|
// doubles the file reads on shared-mount deployments
|
|
229
|
-
await sleep(2000);
|
|
231
|
+
await sleep(Math.max(1, Math.min(2000, deadline - Date.now())));
|
|
230
232
|
result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
231
233
|
}
|
|
232
234
|
return json(result);
|
|
233
235
|
}
|
|
234
236
|
if (req.method === "POST" && p === "/queued") {
|
|
235
|
-
const body =
|
|
237
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
238
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
236
239
|
const ts = Number(body.ts);
|
|
237
240
|
const roomId = String(body.roomId ?? "");
|
|
238
241
|
const sessionID = String(body.sessionID ?? "");
|
|
@@ -245,32 +248,28 @@ async function handle(req: Request): Promise<Response> {
|
|
|
245
248
|
) {
|
|
246
249
|
return json({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
247
250
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
return false;
|
|
252
|
-
}
|
|
253
|
-
entry.lastQueuedTs = Math.max(entry.lastQueuedTs ?? 0, ts);
|
|
254
|
-
return true;
|
|
255
|
-
});
|
|
256
|
-
if (!updated) {
|
|
251
|
+
// Clamp to the room tail so a forged future ts cannot silence delivery.
|
|
252
|
+
const updated = await acknowledgeQueued(roomId, sessionID, ts);
|
|
253
|
+
if (updated === null) {
|
|
257
254
|
return json({ error: "registry entry not found" }, 404);
|
|
258
255
|
}
|
|
259
|
-
clearPendingAdmission(sessionID, roomId,
|
|
256
|
+
clearPendingAdmission(sessionID, roomId, updated);
|
|
260
257
|
touchActive(sessionID);
|
|
261
258
|
return json({ ok: true });
|
|
262
259
|
}
|
|
263
260
|
if (req.method === "POST" && p === "/active") {
|
|
264
261
|
// ponytail: 活跃上报——插件对"进程内自推成功"的 session 调用(真实
|
|
265
262
|
// 活跃);服务器据此避免 serve 双唤起
|
|
266
|
-
const body =
|
|
263
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
264
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
267
265
|
touchActive(String(body.sessionID ?? ""));
|
|
268
266
|
return json({ ok: true });
|
|
269
267
|
}
|
|
270
268
|
if (req.method === "POST" && p === "/wake-claim") {
|
|
271
269
|
// ponytail: atomic cross-process wake dedupe (see claimWake) — the
|
|
272
270
|
// server only arbitrates, it never spawns anything itself
|
|
273
|
-
const body =
|
|
271
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
272
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
274
273
|
const sessionID = String(body.sessionID ?? "");
|
|
275
274
|
const ok = claimWake(sessionID);
|
|
276
275
|
return json({ ok });
|
|
@@ -278,7 +277,8 @@ async function handle(req: Request): Promise<Response> {
|
|
|
278
277
|
const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
|
|
279
278
|
if (m) {
|
|
280
279
|
const roomId = decodeURIComponent(m[1]!);
|
|
281
|
-
const body =
|
|
280
|
+
const body = await jsonObject<Record<string, string>>(req);
|
|
281
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
282
282
|
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
283
283
|
if (req.method === "POST" && m[2] === "join") {
|
|
284
284
|
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
@@ -380,7 +380,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
380
380
|
const isQuestion = (body as Record<string, unknown>).isQuestion;
|
|
381
381
|
if (isQuestion !== undefined && typeof isQuestion !== "boolean") return json({ error: "isQuestion must be a boolean" }, 400);
|
|
382
382
|
// ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
|
|
383
|
-
const text =
|
|
383
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
384
384
|
if (!text) {
|
|
385
385
|
return json({ error: "text is required" }, 400);
|
|
386
386
|
}
|
|
@@ -402,26 +402,15 @@ async function handle(req: Request): Promise<Response> {
|
|
|
402
402
|
void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
|
|
403
403
|
return json(serializeRoom(room), 201);
|
|
404
404
|
}
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
if (
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
return svc.getRoom(roomId);
|
|
411
|
-
});
|
|
405
|
+
const result = await appendRoomMessage(roomId, sessionID, text, isQuestion === true);
|
|
406
|
+
if (result.status !== "ok") {
|
|
407
|
+
if (result.status === "missing") return json({ error: "room not found" }, 404);
|
|
408
|
+
return json({ error: "session is not a room member" }, 409);
|
|
409
|
+
}
|
|
412
410
|
touchActive(sessionID); // 发送者活跃
|
|
411
|
+
const room = await read((svc) => svc.getRoom(roomId));
|
|
413
412
|
// ponytail: 即时唤起——仅 @ 点名成员时(核心需求)
|
|
414
|
-
|
|
415
|
-
if (sent) {
|
|
416
|
-
void wakeMentionedSessions(
|
|
417
|
-
serveWakeUrl,
|
|
418
|
-
roomId,
|
|
419
|
-
room.name,
|
|
420
|
-
text,
|
|
421
|
-
sessionID,
|
|
422
|
-
sent,
|
|
423
|
-
);
|
|
424
|
-
}
|
|
413
|
+
void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
|
|
425
414
|
return json(serializeRoom(room), 201);
|
|
426
415
|
}
|
|
427
416
|
}
|
package/server/member-routes.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { memberActivity, type WorkState } from "../src/member-state";
|
|
2
|
-
import { acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence,
|
|
2
|
+
import { acknowledgeRead, acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence, type ReceiptEvidence, type ReceiptIdentity } from "../src/store";
|
|
3
3
|
import { isReceiverOwnerID } from "../src/receiver-owner";
|
|
4
4
|
import { clearPendingAdmission } from "../src/queue";
|
|
5
5
|
import { touchActive } from "./wake";
|
|
6
6
|
import { announcementRoutes } from "./announcement-routes";
|
|
7
|
+
import { jsonObject } from "./json-body";
|
|
7
8
|
|
|
8
9
|
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
9
10
|
const states = new Set<WorkState>(["working", "idle", "waiting", "unknown"]);
|
|
@@ -17,7 +18,8 @@ export async function memberRoutes(req: Request, url: URL): Promise<Response | u
|
|
|
17
18
|
const announcements = await announcementRoutes(req, url);
|
|
18
19
|
if (announcements) return announcements;
|
|
19
20
|
if (req.method === "POST" && url.pathname === "/read") {
|
|
20
|
-
const body =
|
|
21
|
+
const body = await jsonObject<Record<string, unknown>>(req);
|
|
22
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
21
23
|
const ts = body.ts;
|
|
22
24
|
const roomId = String(body.roomId ?? "");
|
|
23
25
|
const sessionID = String(body.sessionID ?? "");
|
|
@@ -48,15 +50,11 @@ export async function memberRoutes(req: Request, url: URL): Promise<Response | u
|
|
|
48
50
|
touchActive(sessionID);
|
|
49
51
|
return json({ ok: true, acceptedIDs: result.acceptedIDs });
|
|
50
52
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return { actualTs };
|
|
57
|
-
});
|
|
58
|
-
if (!updated) return json({ error: "registry entry not found" }, 404);
|
|
59
|
-
clearPendingAdmission(sessionID, roomId, updated.actualTs);
|
|
53
|
+
// Read watermark is the hottest write path; update the registry row directly
|
|
54
|
+
// instead of rewriting every room and message.
|
|
55
|
+
const actualTs = await acknowledgeRead(roomId, sessionID, ts);
|
|
56
|
+
if (actualTs === null) return json({ error: "registry entry not found" }, 404);
|
|
57
|
+
clearPendingAdmission(sessionID, roomId, actualTs);
|
|
60
58
|
touchActive(sessionID);
|
|
61
59
|
return json({ ok: true });
|
|
62
60
|
}
|
package/server/wake.ts
CHANGED
|
@@ -11,12 +11,21 @@ const activeSessions = new Map<string, number>();
|
|
|
11
11
|
const WAKE_CLAIM_MS = 30_000;
|
|
12
12
|
const WAKE_INACTIVE_MS = 2 * 60_000;
|
|
13
13
|
|
|
14
|
+
const MAX_TRACKED = 10_000;
|
|
15
|
+
function track(map: Map<string, number>, id: string, ttl: number): void {
|
|
16
|
+
map.set(id, Date.now());
|
|
17
|
+
if (map.size <= MAX_TRACKED) return;
|
|
18
|
+
const floor = Date.now() - ttl;
|
|
19
|
+
for (const [key, at] of map) if (at < floor) map.delete(key);
|
|
20
|
+
for (const key of map.keys()) { if (map.size <= MAX_TRACKED) break; map.delete(key); }
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
export function claimWake(id: string): boolean {
|
|
15
24
|
if (Date.now() - (wakeClaims.get(id) ?? 0) < WAKE_CLAIM_MS) return false;
|
|
16
|
-
wakeClaims
|
|
25
|
+
track(wakeClaims, id, WAKE_CLAIM_MS);
|
|
17
26
|
return true;
|
|
18
27
|
}
|
|
19
|
-
export function touchActive(id: string): void { if (id) activeSessions
|
|
28
|
+
export function touchActive(id: string): void { if (id) track(activeSessions, id, WAKE_INACTIVE_MS); }
|
|
20
29
|
|
|
21
30
|
export async function wakeMentionedSessions(
|
|
22
31
|
serveWakeUrl: string, roomId: string, roomName: string, text: string,
|
package/src/admin-client.ts
CHANGED
|
@@ -14,7 +14,7 @@ export const adminToolSchema = z.object({
|
|
|
14
14
|
roomId: z.string().optional(), enrollmentKey: z.string().optional(), targetRoomId: z.string().optional(),
|
|
15
15
|
limit: z.number().int().min(1).max(50).optional(),
|
|
16
16
|
});
|
|
17
|
-
export const adminToolDescription = "Administer an operator-
|
|
17
|
+
export const adminToolDescription = "Administer an operator-designated room: overview and history. This tool never joins a room.";
|
|
18
18
|
const safe = (value: string) => encodeURIComponent(value);
|
|
19
19
|
|
|
20
20
|
async function send(opts: CenterOpts, path: string, method: string, body?: unknown,
|
|
@@ -67,8 +67,8 @@ export async function adminTool(args: AdminArgs, context: AdminContext, opts: Ce
|
|
|
67
67
|
}
|
|
68
68
|
if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
|
|
69
69
|
const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
// Designation is immediate; a claimed capability is only sent when one exists.
|
|
71
|
+
const capability = (await loadAdminCapability(identity)) ?? "";
|
|
72
72
|
const root = `/admin/rooms/${safe(roomId)}`;
|
|
73
73
|
const request = (route: string, method: string, body?: unknown) =>
|
|
74
74
|
send(opts, `${root}${route}`, method, body, capability, context.sessionID, ownerID ?? "");
|
package/src/center-inbox.ts
CHANGED
|
@@ -13,7 +13,6 @@ import { explicitlyAddresses } from "./mentions";
|
|
|
13
13
|
import { claimBackgroundAttempt } from "./receiver-state";
|
|
14
14
|
import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
|
|
15
15
|
import { serializeSessionPush } from "./session-delivery";
|
|
16
|
-
import { checkSupervisionInbox } from "./supervision-inbox";
|
|
17
16
|
export { serializeSessionPush } from "./session-delivery";
|
|
18
17
|
import {
|
|
19
18
|
sendAsyncNotification,
|
|
@@ -69,7 +68,6 @@ export async function checkCenterInbox(
|
|
|
69
68
|
items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
70
69
|
}
|
|
71
70
|
await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
|
|
72
|
-
await checkSupervisionInbox(opts, sessionID, transport);
|
|
73
71
|
});
|
|
74
72
|
} catch {
|
|
75
73
|
// The next inbox poll retries failed delivery.
|
|
@@ -96,10 +96,11 @@ export function createNotifier(deps: {
|
|
|
96
96
|
const service = backgroundServiceKey(targetTransport);
|
|
97
97
|
const cutoff = Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0);
|
|
98
98
|
prunePendingAdmission(sessionID, batch.roomId, cutoff, (items) => render(batch, entry.name, roomKind, items));
|
|
99
|
-
const
|
|
99
|
+
const unreadAll = batch.messages.filter((m) =>
|
|
100
100
|
m.createdAt > cutoff &&
|
|
101
101
|
(m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== (roomKind === "direct" ? sessionID : entry.name)),
|
|
102
|
-
)
|
|
102
|
+
);
|
|
103
|
+
const unread = unreadAll.slice(-20).map((item) => ({ ...item, roomKind }));
|
|
103
104
|
const existing = pendingAdmission(sessionID, batch.roomId);
|
|
104
105
|
if (!unread.length && existing?.state !== "pending") return undefined;
|
|
105
106
|
const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
@@ -108,7 +109,7 @@ export function createNotifier(deps: {
|
|
|
108
109
|
: unread;
|
|
109
110
|
const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
|
|
110
111
|
if (mentionOnly && !eligibleItems.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind)) &&
|
|
111
|
-
!
|
|
112
|
+
!unreadAll.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))) return undefined;
|
|
112
113
|
const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
|
|
113
114
|
const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
|
|
114
115
|
const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
|
package/src/resources.ts
CHANGED
|
@@ -27,7 +27,10 @@ function mime(bytes: Uint8Array): string {
|
|
|
27
27
|
if (String.fromCharCode(...bytes.slice(0, 4)) === "RIFF" && String.fromCharCode(...bytes.slice(8, 12)) === "WAVE") return "audio/wav";
|
|
28
28
|
if (String.fromCharCode(...bytes.slice(0, 3)) === "ID3" || (bytes[0] === 0xff && (bytes[1]! & 0xe0) === 0xe0)) return "audio/mpeg";
|
|
29
29
|
if (String.fromCharCode(...bytes.slice(0, 4)) === "OggS") return "audio/ogg";
|
|
30
|
-
if (String.fromCharCode(...bytes.slice(4, 8)) === "ftyp")
|
|
30
|
+
if (String.fromCharCode(...bytes.slice(4, 8)) === "ftyp") {
|
|
31
|
+
const brand = String.fromCharCode(...bytes.slice(8, 12));
|
|
32
|
+
return brand === "avif" || brand === "avis" ? "image/avif" : "video/mp4";
|
|
33
|
+
}
|
|
31
34
|
if (starts(0x1a, 0x45, 0xdf, 0xa3)) return "video/webm";
|
|
32
35
|
return "application/octet-stream";
|
|
33
36
|
}
|
package/src/sqlite-state.ts
CHANGED
|
@@ -360,6 +360,24 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
|
|
|
360
360
|
});
|
|
361
361
|
}
|
|
362
362
|
|
|
363
|
+
export async function appendRoomMessage(file: string, roomID: string, sessionID: string, text: string, isQuestion: boolean): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" }> {
|
|
364
|
+
const db = await openStateDatabase(file);
|
|
365
|
+
return immediate(db, () => {
|
|
366
|
+
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
|
|
367
|
+
const member = db.query("SELECT g.name,r.kind FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
|
|
368
|
+
if (!member) return { status: "member" };
|
|
369
|
+
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
|
|
370
|
+
const message: Message = {
|
|
371
|
+
id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name,
|
|
372
|
+
senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1),
|
|
373
|
+
...(isQuestion ? { isQuestion: true } : {}),
|
|
374
|
+
};
|
|
375
|
+
db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)")
|
|
376
|
+
.run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0);
|
|
377
|
+
return { status: "ok", message };
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
363
381
|
export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" | "target" | "question" }> {
|
|
364
382
|
const db = await openStateDatabase(file);
|
|
365
383
|
return immediate(db, () => {
|
|
@@ -450,6 +468,28 @@ export async function readMessageReceipts(file: string, roomID: string, messageI
|
|
|
450
468
|
}).deferred();
|
|
451
469
|
}
|
|
452
470
|
|
|
471
|
+
export async function acknowledgeQueued(file: string, roomID: string, sessionID: string, ts: number): Promise<number | null> {
|
|
472
|
+
const db = await openStateDatabase(file);
|
|
473
|
+
return immediate(db, () => {
|
|
474
|
+
if (!db.query("SELECT 1 FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID)) return null;
|
|
475
|
+
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
|
|
476
|
+
const capped = Math.min(ts, tail?.created_at ?? 0);
|
|
477
|
+
db.query("UPDATE registry SET last_queued_ts=max(coalesce(last_queued_ts,0),?) WHERE room_id=? AND session_id=?").run(capped, roomID, sessionID);
|
|
478
|
+
return capped;
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export async function acknowledgeRead(file: string, roomID: string, sessionID: string, ts: number): Promise<number | null> {
|
|
483
|
+
const db = await openStateDatabase(file);
|
|
484
|
+
return immediate(db, () => {
|
|
485
|
+
if (!db.query("SELECT 1 FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID)) return null;
|
|
486
|
+
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
|
|
487
|
+
const actualTs = Math.min(ts, tail?.created_at ?? 0);
|
|
488
|
+
if (actualTs > 0) db.query("UPDATE registry SET last_read_ts=max(coalesce(last_read_ts,0),?) WHERE room_id=? AND session_id=?").run(actualTs, roomID, sessionID);
|
|
489
|
+
return actualTs;
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
|
|
453
493
|
export async function writeMessageReceipts(file: string, roomID: string, sessionID: string, messageIDs: string[], evidence: ReceiptEvidence, identity: ReceiptIdentity, readAt: number, readThroughTs?: number): Promise<ReceiptWriteResult> {
|
|
454
494
|
if (!messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) || !["displayed", "tool", "context"].includes(evidence)) return { status: "messageIDs", acceptedIDs: [] };
|
|
455
495
|
const ids = [...new Set(messageIDs)];
|
package/src/store.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import RoomService, { type Message, type Room } from "./room-service";
|
|
7
|
-
import { answerQuestion as sqliteAnswerQuestion, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
|
|
7
|
+
import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
|
|
8
8
|
|
|
9
9
|
export function statePath(): string {
|
|
10
10
|
// JSON path remains the migration source; SQLite lives beside it.
|
|
@@ -35,8 +35,11 @@ export async function readHistory(roomID: string, beforeSeq?: number, limit = 10
|
|
|
35
35
|
return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
|
|
36
36
|
}
|
|
37
37
|
export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
|
|
38
|
+
export function acknowledgeRead(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeRead(databasePath(), roomID, sessionID, ts); }
|
|
39
|
+
export function acknowledgeQueued(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeQueued(databasePath(), roomID, sessionID, ts); }
|
|
38
40
|
export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
|
|
39
41
|
export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text); }
|
|
42
|
+
export function appendRoomMessage(roomID: string, sessionID: string, text: string, isQuestion: boolean) { return sqliteAppendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion); }
|
|
40
43
|
export async function readQuestionExcerpt(roomID: string, questionID: string) { return sqliteQuestionExcerpt(databasePath(), roomID, questionID); }
|
|
41
44
|
|
|
42
45
|
export async function loadRooms(): Promise<Room[]> {
|
package/src/supervision-inbox.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { request, type CenterOpts } from "./center-client";
|
|
2
|
-
import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
|
|
3
|
-
import { loadAdminCapability } from "./admin-credentials";
|
|
4
|
-
import { protectedAdminRequest } from "./admin-client";
|
|
5
|
-
|
|
6
|
-
type Delivery = { id: string; admissionID?: string; adminRoomId?: string; kind: "supervision"; text: string };
|
|
7
|
-
type Inbox = { deliveries?: Delivery[]; supervisionRoomIds?: string[] };
|
|
8
|
-
|
|
9
|
-
function promptText(item: Delivery): string {
|
|
10
|
-
return `<supervision>Reminder from admin room ${item.adminRoomId}. Use admin(action="admin_overview", roomId="${item.adminRoomId}") to review it.\n${item.text}</supervision>`;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
async function push(opts: CenterOpts, sessionID: string, ownerID: string, transport: QueueTransport,
|
|
14
|
-
item: Delivery, capability?: string): Promise<void> {
|
|
15
|
-
const raw = promptText(item), text = capability ? raw.replaceAll(capability, "[redacted]") : raw;
|
|
16
|
-
const admissionID = item.admissionID ?? item.id;
|
|
17
|
-
const result = transport.protocol === "v1" ? await sendAsyncNotification(transport, sessionID, text)
|
|
18
|
-
: await sendQueue(transport, sessionID, text, admissionID, "steer");
|
|
19
|
-
if (result !== "delivered") return;
|
|
20
|
-
const body = { id: item.id, sessionID, receiverOwnerID: ownerID };
|
|
21
|
-
if (capability) await protectedAdminRequest(opts, "/supervision/ack", "POST", capability, sessionID, ownerID, body);
|
|
22
|
-
else await request(opts, "/supervision/ack", "POST", body);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export async function checkSupervisionInbox(opts: CenterOpts, sessionID: string, transport: QueueTransport): Promise<void> {
|
|
26
|
-
if (!opts.center || (transport.protocol === "v2" && !transport.receiverOwnerID)) return;
|
|
27
|
-
const ownerID = transport.receiverOwnerID ?? "";
|
|
28
|
-
let inbox: Inbox;
|
|
29
|
-
try {
|
|
30
|
-
const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID });
|
|
31
|
-
inbox = await request(opts, `/supervision/inbox?${query}`, "GET") as Inbox;
|
|
32
|
-
} catch { return; }
|
|
33
|
-
if (!inbox || typeof inbox !== "object") return;
|
|
34
|
-
|
|
35
|
-
const hintedRooms = Array.isArray(inbox.supervisionRoomIds)
|
|
36
|
-
? [...new Set(inbox.supervisionRoomIds.filter((room): room is string => typeof room === "string" && !!room))].slice(0, 50)
|
|
37
|
-
: [];
|
|
38
|
-
for (const roomId of hintedRooms) {
|
|
39
|
-
const capability = await loadAdminCapability({ center: opts.center, roomId, sessionID, ownerID });
|
|
40
|
-
if (!capability) continue;
|
|
41
|
-
try {
|
|
42
|
-
const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID, adminRoomId: roomId });
|
|
43
|
-
const result = await protectedAdminRequest(opts, `/supervision/inbox?${query}`, "GET", capability, sessionID, ownerID) as Inbox;
|
|
44
|
-
for (const item of (Array.isArray(result.deliveries) ? result.deliveries : []).slice(0, 50)) {
|
|
45
|
-
if (item?.kind !== "supervision" || item.adminRoomId !== roomId || !item.id || typeof item.text !== "string") continue;
|
|
46
|
-
try { await push(opts, sessionID, ownerID, transport, item, capability); } catch { /* Retry with the same server-issued ID next sweep. */ }
|
|
47
|
-
}
|
|
48
|
-
} catch { /* A room's protected feed does not block other admin rooms. */ }
|
|
49
|
-
}
|
|
50
|
-
}
|