@alexsun-top/opencode-chat-room 0.3.1 → 0.3.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 +17 -0
- package/README.md +19 -9
- package/README.zh-CN.md +19 -9
- package/package.json +1 -1
- package/server/assets/chat/events.js +9 -2
- package/server/assets/chat/markdown.js +23 -4
- package/server/assets/chat/message-window.js +13 -0
- package/server/assets/chat/messages.js +39 -28
- package/server/assets/chat/rooms.js +56 -25
- package/server/assets/chat/state.js +75 -16
- package/server/assets/chat/system-messages.js +20 -0
- package/server/assets/conversation.css +29 -6
- package/server/chat-server.ts +12 -4
- package/server/inbox.ts +2 -2
- package/src/agent-receipts.ts +54 -9
- package/src/receiver-state.ts +5 -3
- package/src/sqlite-state.ts +3 -3
- package/src/store.ts +2 -2
- package/src/v2-plugin.ts +16 -3
- package/src/v2-receiver.ts +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.3 — 2026-11-04
|
|
4
|
+
|
|
5
|
+
- Added an always-visible copy button below every message, including system messages. It copies the original text, supports clipboard fallback, and preserves selection and focus.
|
|
6
|
+
- Moved per-message reader counts into circular badges beside message bubbles. Reader details remain available on desktop and mobile, with localized accessible labels.
|
|
7
|
+
- Fixed capped V2 notifications discarding receipts for complete short messages in the same batch. Only uniquely matched, fully rendered messages qualify; truncated, omitted, multiline capped, and ambiguous duplicate messages remain unreceipted.
|
|
8
|
+
- Flush up to eight ready receipt candidates per round with ordered rotation, so transient upload failures do not repeatedly block later candidates. Failed candidates remain queued for retry.
|
|
9
|
+
- Verified all 143 tests, including Edge browser coverage, and TypeScript checks. An isolated OpenCode 2.2.5 host using the modified engine recorded the complete message but not the truncated message in a mixed batch. The reported production incident has not been independently attributed to either fixed case.
|
|
10
|
+
- Upgrade the central server for the web changes and reload each V2 client plugin for receipt fixes. This release does not deploy servers, change OpenCode permissions, or implement image messages.
|
|
11
|
+
|
|
12
|
+
## 0.3.2 — 2026-11-02
|
|
13
|
+
|
|
14
|
+
- Fixed V2 context-receipt attribution when the verified host owner is discovered after plugin setup, and propagate that owner across project attachments. A full short message can now record `context` evidence without `room.poll`; capped previews remain unreceipted. A previously unready candidate becomes eligible only if its complete original message appears in agent context again—there is no read-all backfill or synthetic empty-context replay.
|
|
15
|
+
- Verified a short-message receipt and capped-preview negative case in an isolated native OpenCode 2.2.0 run against a local central server and mock model. The controlled owner-missing baseline produced no receipt. Delivery during active or backgrounded shell work was not verified.
|
|
16
|
+
- Added browser-profile-persistent identity, server-confirmed room restoration without auto-joining, and per-tab inbox cursors through optional read-only `afterTs`. Drafts and read positions remain tab-local. These browser APIs require central server 0.3.2. Membership system events and room previews now follow the selected locale; user-authored text is unchanged.
|
|
17
|
+
- Fixed the reproduced Edge/macOS selection loss when the 500-message window shifted: retained message rows are kept through polls and only rows outside the window are pruned. Browser coverage includes a held selection across polling and trimming. This does not establish that every selection issue is fixed; Windows was not physically tested.
|
|
18
|
+
- Upgrade the central server to 0.3.2 for browser identity restoration and `afterTs`. Reload V2 client plugins at 0.3.2 for the context-receipt fix. The receipt API itself is available from central 0.3.1; plugin upgrades do not deploy or reconfigure the server.
|
|
19
|
+
|
|
3
20
|
## 0.3.1 — 2026-10-31
|
|
4
21
|
|
|
5
22
|
- Added owner-sequenced V2 foreground presence and exact per-message receipts with `displayed`, `tool`, and `context` evidence. Idle does not mean background work is done; `waiting` is not auto-collected, V1 reports no heartbeat, and expired status is stale rather than proof of being offline. Owner- and membership-generation checks prevent receipts from crossing ownership or leave/rejoin boundaries. Capped previews do not count as full-message evidence.
|
package/README.md
CHANGED
|
@@ -79,17 +79,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
|
|
|
79
79
|
|
|
80
80
|
```bash
|
|
81
81
|
# Show CLI options:
|
|
82
|
-
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.
|
|
82
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --help
|
|
83
83
|
|
|
84
84
|
# Start the local central server (choose any one runner):
|
|
85
|
-
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.
|
|
86
|
-
pnpx --package=@alexsun-top/opencode-chat-room@0.3.
|
|
87
|
-
bunx @alexsun-top/opencode-chat-room@0.3.
|
|
85
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --host 0.0.0.0 --port 4399
|
|
86
|
+
pnpx --package=@alexsun-top/opencode-chat-room@0.3.3 opencode-chat-room --host 0.0.0.0 --port 4399
|
|
87
|
+
bunx @alexsun-top/opencode-chat-room@0.3.3 --host 0.0.0.0 --port 4399 --token secret
|
|
88
88
|
|
|
89
89
|
# Environment variables also work; CLI options take precedence:
|
|
90
90
|
CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
|
|
91
91
|
CHAT_ROOM_SERVER_TOKEN=secret \
|
|
92
|
-
bunx @alexsun-top/opencode-chat-room@0.3.
|
|
92
|
+
bunx @alexsun-top/opencode-chat-room@0.3.3
|
|
93
93
|
|
|
94
94
|
# Local checkout:
|
|
95
95
|
bun install
|
|
@@ -100,7 +100,11 @@ Open `http://<server-ip>:4399/chat` in a browser to join or create a room and ch
|
|
|
100
100
|
|
|
101
101
|
### Browser chat
|
|
102
102
|
|
|
103
|
-
|
|
103
|
+
For the same chat site, browser storage keeps a persistent session ID and preferred name shared by tabs and browser restarts. On an existing profile, the first tab migrates its prior tab ID; other tabs adopt the shared identity when loaded or reloaded. This is not an account or login. Clearing site storage, using a private window, or switching browser profiles creates a new identity; if both local and tab storage are blocked, the ID lasts only for the current page. A tab detects a conflicting identity change and asks to reload before making more requests.
|
|
104
|
+
|
|
105
|
+
Each tab keeps its own joined-room list, drafts, read position, unread counts, and in-memory inbox receive timestamp. `GET /rooms?sessionID=…` returns a `joined` flag for each visible room; this server membership determines what is restored on reload, without automatically joining rooms. Temporary network, token, or server errors retain rooms for retry, while a server response that the membership is gone removes it. Leaving or removal affects membership in every tab using that profile's shared session ID.
|
|
106
|
+
|
|
107
|
+
Switching the sidebar does not leave a room. Direct conversations are created with the selected registered member session. System join, leave, and removal events and their room previews use the selected locale; ordinary user messages are not translated.
|
|
104
108
|
|
|
105
109
|
The chat renders GitHub Flavored Markdown using locally bundled Marked and DOMPurify assets. Message text is sanitized before rendered HTML is inserted. No CDN is required.
|
|
106
110
|
|
|
@@ -122,9 +126,15 @@ Receipts identify exact messages; join, read, and queued cursors do not create t
|
|
|
122
126
|
|
|
123
127
|
`membershipID` identifies the current join generation. Leaving and rejoining creates a new ID; receipt submissions from the previous generation are rejected.
|
|
124
128
|
|
|
125
|
-
`displayed` means the message intersected the visible area of a focused browser tab. `tool` means a room poll fetched the full message; V1 receipts are limited to explicit polls. `context` means the full message reached primary agent-context preparation, not that it was understood. A 300-character push preview is not full-message evidence; poll the full message to record a receipt. Receipts remain visible after a reader leaves, marked as no longer a current member. These endpoints use the central server's shared-token permissions, not per-user access control.
|
|
129
|
+
`displayed` means the message intersected the visible area of a focused browser tab. `tool` means a room poll fetched the full message; V1 receipts are limited to explicit polls. `context` means the full message reached primary agent-context preparation, not that it was understood. V2 resolves the verified host owner on the context hook when it was unavailable during setup, allowing a full message in context to record a receipt without `room.poll`. A 300-character push preview is not full-message evidence; poll the full message to record a receipt. Older unready candidates qualify only if the complete original message appears in context again; there is no automatic read-all backfill or synthetic empty-context replay. Receipts remain visible after a reader leaves, marked as no longer a current member. These endpoints use the central server's shared-token permissions, not per-user access control.
|
|
130
|
+
|
|
131
|
+
Browser tabs fetch messages with `GET /inbox?sessionID=…&roomId=…&excludeSelf=0&afterTs=…`. `afterTs` must be a non-negative safe integer and is accepted only with a room ID and explicit `excludeSelf=0`; it is an exclusive lower bound for that request, replacing the stored-cursor filter for selection only. It does not advance read or queued cursors or create receipts. Calls without `afterTs` keep the existing agent-poll behavior.
|
|
132
|
+
|
|
133
|
+
Central server 0.3.2 is required for persistent browser identity restoration and `afterTs`; updating a client plugin does not deploy the server. Receipt APIs first appeared in 0.3.1. The V2 context-receipt fix requires upgrading and reloading each V2 client plugin to 0.3.2.
|
|
134
|
+
|
|
135
|
+
Version 0.3.3 adds a copy-original-text button below every message and circular reader-count badges beside message bubbles. Upgrade the central server for these web changes and reload V2 client plugins to 0.3.3 for batch receipt fixes. Complete, uniquely matched lines in capped notifications can receive receipts; truncated or ambiguous lines cannot. Ready receipts upload in rotating batches of up to eight so a transient failure does not block later candidates.
|
|
126
136
|
|
|
127
|
-
|
|
137
|
+
Image messages are not implemented in 0.3.3; see the [image-message proposal](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md).
|
|
128
138
|
|
|
129
139
|
On every client machine:
|
|
130
140
|
|
|
@@ -179,4 +189,4 @@ Note: `join` with `name:"alice"` registers the identity `alice` for that session
|
|
|
179
189
|
- SQLite retains message history without automatic deletion. The 500-message in-memory window does not limit persisted history; unread messages and history are read in bounded pages. Back up the database regularly.
|
|
180
190
|
- Only installations carrying retry rows from an intermediate development build are affected: records without a recoverable message timestamp migrate conservatively, permanently disabling backgrounding for that service/room. Normal notification steering continues.
|
|
181
191
|
- `notify.log` grows without rotation.
|
|
182
|
-
-
|
|
192
|
+
- The reproduced Edge/macOS text-selection failure at the 500-message window shift is fixed: rows still in the window are retained during polling and rows outside it are pruned. Browser coverage includes selections held across polls and trimming. Windows was not physically tested, and this does not claim unrelated selection issues are resolved.
|
package/README.zh-CN.md
CHANGED
|
@@ -77,17 +77,17 @@ OpenCode 2.2.1 会在默认 60 分钟无活动后卸载闲置项目的服务。W
|
|
|
77
77
|
|
|
78
78
|
```bash
|
|
79
79
|
# 查看 CLI 选项:
|
|
80
|
-
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.
|
|
80
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --help
|
|
81
81
|
|
|
82
82
|
# 启动本地中心服务器(三选一):
|
|
83
|
-
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.
|
|
84
|
-
pnpx --package=@alexsun-top/opencode-chat-room@0.3.
|
|
85
|
-
bunx @alexsun-top/opencode-chat-room@0.3.
|
|
83
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --host 0.0.0.0 --port 4399
|
|
84
|
+
pnpx --package=@alexsun-top/opencode-chat-room@0.3.3 opencode-chat-room --host 0.0.0.0 --port 4399
|
|
85
|
+
bunx @alexsun-top/opencode-chat-room@0.3.3 --host 0.0.0.0 --port 4399 --token secret
|
|
86
86
|
|
|
87
87
|
# 也可以使用环境变量;CLI 参数优先:
|
|
88
88
|
CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
|
|
89
89
|
CHAT_ROOM_SERVER_TOKEN=secret \
|
|
90
|
-
bunx @alexsun-top/opencode-chat-room@0.3.
|
|
90
|
+
bunx @alexsun-top/opencode-chat-room@0.3.3
|
|
91
91
|
|
|
92
92
|
# 本地 checkout:
|
|
93
93
|
bun install
|
|
@@ -98,7 +98,11 @@ bun run server
|
|
|
98
98
|
|
|
99
99
|
### 浏览器聊天
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
同一聊天站点的浏览器存储会持久保存会话 ID 和昵称,供多个标签页及浏览器重启后共用。旧配置首次迁移时,由第一个打开的标签页沿用原标签页 ID;其他标签页加载或重新加载后采用共享身份。这不是账户或登录。清除站点存储、使用无痕窗口或切换浏览器配置文件都会创建新身份;若本地存储和标签页存储都被阻止,身份只在当前页面内存中有效。若另一个标签页更改了共享身份,旧标签页会停止发送请求并提示重新加载。
|
|
102
|
+
|
|
103
|
+
每个标签页分别保存已加入房间列表、草稿、阅读位置、未读计数,并在内存中维护自己的收件时间戳。`GET /rooms?sessionID=…` 会为每个可见房间返回 `joined` 标志;重新加载时据此恢复服务器上的现有成员关系,不会自动重新加入。临时网络、令牌或服务器错误会保留房间并重试;服务器确认成员关系已不存在时才移除。离开或移除成员会影响所有使用该配置文件共享会话 ID 的标签页。
|
|
104
|
+
|
|
105
|
+
侧栏切换只切换当前视图,不会离开房间。私聊由成员列表中选中的已注册会话创建。系统加入、离开、移除事件及房间预览会使用当前语言;普通用户消息不会被翻译。
|
|
102
106
|
|
|
103
107
|
聊天内容使用本地打包的 Marked 解析 GitHub Flavored Markdown,并由 DOMPurify 清理后再插入页面,不依赖 CDN。
|
|
104
108
|
|
|
@@ -120,9 +124,15 @@ V2 使用 `POST /presence` 上报 owner 范围内递增的序号,每次最多
|
|
|
120
124
|
|
|
121
125
|
`membershipID` 标识当前加入代次。离开后重新加入会生成新 ID;使用旧代次提交回执会被拒绝。
|
|
122
126
|
|
|
123
|
-
`displayed` 表示消息出现在当前聚焦浏览器标签页的可视区域。`tool` 表示房间轮询已获取完整消息;V1 仅在显式轮询时产生此类回执。`context` 表示完整消息进入了 agent 的主要上下文准备阶段,不代表 agent
|
|
127
|
+
`displayed` 表示消息出现在当前聚焦浏览器标签页的可视区域。`tool` 表示房间轮询已获取完整消息;V1 仅在显式轮询时产生此类回执。`context` 表示完整消息进入了 agent 的主要上下文准备阶段,不代表 agent 已理解。若 V2 在插件启动时尚未获得宿主身份,会在上下文钩子中解析已验证的宿主身份,因此完整消息进入上下文后无需 `room.poll` 也可记录回执。被截为 300 字符的推送预览不算完整消息证据;需轮询完整消息才能记录回执。旧的未就绪候选只有在完整原消息再次进入上下文时才会生效;不会自动回填全部已读状态,也不会合成空上下文重放。成员离开后回执仍保留,并标记其已不是当前成员。这些接口使用中心服务器的共享令牌权限,不提供逐用户访问控制。
|
|
128
|
+
|
|
129
|
+
浏览器标签页通过 `GET /inbox?sessionID=…&roomId=…&excludeSelf=0&afterTs=…` 拉取消息。`afterTs` 必须是非负安全整数,且仅可与房间 ID 和显式的 `excludeSelf=0` 一起使用;它是本次请求的排他下界,仅替换本次查询的游标筛选,不会推进已读或排队游标,也不会生成回执。省略 `afterTs` 时,现有 agent 轮询行为不变。
|
|
130
|
+
|
|
131
|
+
浏览器持久身份恢复和 `afterTs` 需要中心服务器 0.3.2;只更新客户端插件不会部署服务端。回执 API 自 0.3.1 起提供。V2 上下文回执修复需要将每台 V2 客户端插件升级并重新加载到 0.3.2。
|
|
132
|
+
|
|
133
|
+
0.3.3 在每条消息下方增加复制原文按钮,并将已读人数改为消息旁的圆形标记。网页变化需升级中心服务器,批量回执修复需将各 V2 客户端插件升级并重新加载至 0.3.3。截断通知中完整且可唯一匹配的消息可以记录回执,截断或有歧义的消息不计完整已读;就绪回执每轮轮转上传最多八批,避免临时失败阻塞后续消息。
|
|
124
134
|
|
|
125
|
-
|
|
135
|
+
0.3.3 尚未实现图片消息;设计提案见[图片消息方案](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md)。
|
|
126
136
|
|
|
127
137
|
每台客户端机器上:
|
|
128
138
|
|
|
@@ -176,4 +186,4 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
176
186
|
- SQLite 持续保留历史消息,不自动删除。500 条只是内存工作窗口,不是磁盘保留上限;未读消息和历史记录均分页读取。请定期备份数据库。
|
|
177
187
|
- 仅包含某个过渡开发版重试记录的安装会受影响:若旧后台重试记录无法恢复消息时间戳,迁移会采取保守处理,永久停用该服务/房间的后台操作;正常通知 steer 仍会继续。
|
|
178
188
|
- `notify.log` 会持续增长,暂无轮转。
|
|
179
|
-
-
|
|
189
|
+
- 已修复 Edge/macOS 中复现的 500 条消息窗口滚动导致文本选区丢失问题:轮询时保留仍在窗口内的消息行,只清除窗口外的行。浏览器测试覆盖轮询及裁剪过程中保持选区;未在实体 Windows 设备上测试,也不代表其他选区问题均已解决。
|
package/package.json
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
-
import { copyCodeFromButton } from "./markdown.js";
|
|
2
|
+
import { copyCodeFromButton, copyTextToClipboard } from "./markdown.js";
|
|
3
3
|
|
|
4
4
|
export function initEvents(app) {
|
|
5
5
|
const $ = app.$;
|
|
6
6
|
document.querySelectorAll(".locale-select").forEach((select) => {
|
|
7
|
-
select.addEventListener("change", () =>
|
|
7
|
+
select.addEventListener("change", () => {
|
|
8
|
+
app.setLocale(select.value);
|
|
9
|
+
if (!app.state.availableRooms) return;
|
|
10
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
11
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
12
|
+
});
|
|
8
13
|
});
|
|
9
14
|
$("#joinForm").addEventListener("submit", (event) => {
|
|
10
15
|
event.preventDefault();
|
|
@@ -75,6 +80,8 @@ export function initEvents(app) {
|
|
|
75
80
|
$("#msgList").addEventListener("click", (event) => {
|
|
76
81
|
const button = event.target.closest("[data-copy-code]");
|
|
77
82
|
if (button) void copyCodeFromButton(button, app);
|
|
83
|
+
const messageButton = event.target.closest("[data-copy-message]");
|
|
84
|
+
if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
|
|
78
85
|
});
|
|
79
86
|
["#inRoomId", "#inName", "#inRoomName"].forEach((selector) => {
|
|
80
87
|
$(selector).addEventListener("input", app.hideJoinError);
|
|
@@ -58,8 +58,27 @@ function replaceMentionTokens(fragment, mentions, app) {
|
|
|
58
58
|
|
|
59
59
|
export function copyCodeFromButton(button, app) {
|
|
60
60
|
const code = button.parentElement.querySelector("code")?.textContent || "";
|
|
61
|
-
return
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
61
|
+
return copyTextToClipboard(code).then((copied) => copied ? app.flash(button, "copiedCode") : app.showSendError("copyCodeFailed"));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function copyTextToClipboard(text) {
|
|
65
|
+
try {
|
|
66
|
+
if (navigator.clipboard?.writeText) {
|
|
67
|
+
await navigator.clipboard.writeText(text);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
} catch { /* Use the legacy clipboard command when permission is unavailable. */ }
|
|
71
|
+
const field = document.createElement("textarea"), selection = getSelection(), active = document.activeElement;
|
|
72
|
+
const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) : [];
|
|
73
|
+
field.value = text;
|
|
74
|
+
field.setAttribute("readonly", "");
|
|
75
|
+
field.style.cssText = "position:fixed;left:-9999px;top:0";
|
|
76
|
+
document.body.append(field);
|
|
77
|
+
field.select();
|
|
78
|
+
let copied = false;
|
|
79
|
+
try { copied = document.execCommand("copy"); } catch { /* Clipboard access may be disabled. */ }
|
|
80
|
+
field.remove();
|
|
81
|
+
if (selection) { selection.removeAllRanges(); ranges.forEach((range) => selection.addRange(range)); }
|
|
82
|
+
if (active instanceof HTMLElement) active.focus({ preventScroll: true });
|
|
83
|
+
return copied;
|
|
65
84
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function pruneMessageRows(list, messages) {
|
|
2
|
+
const ids = new Set(messages.map((message) => message.id));
|
|
3
|
+
for (const row of list.querySelectorAll("[data-msg-id]")) if (!ids.has(row.dataset.msgId)) row.remove();
|
|
4
|
+
const days = new Set([...list.querySelectorAll("[data-msg-id]")].map((row) => row.dataset.day));
|
|
5
|
+
for (const separator of list.querySelectorAll(".day-sep")) if (!days.has(separator.dataset.day)) separator.remove();
|
|
6
|
+
if (!days.size) list.querySelectorAll(".gap").forEach((gap) => gap.remove());
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function hasMessageSelection(list) {
|
|
10
|
+
const selection = getSelection();
|
|
11
|
+
return Boolean(selection && !selection.isCollapsed
|
|
12
|
+
&& (list.contains(selection.anchorNode) || list.contains(selection.focusNode)));
|
|
13
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createRandomId, LS } from "./state.js";
|
|
2
2
|
import { renderMarkdown } from "./markdown.js";
|
|
3
|
+
import { hasMessageSelection, pruneMessageRows } from "./message-window.js";
|
|
4
|
+
import { formatSystemMessage, setRoomPreview } from "./system-messages.js";
|
|
3
5
|
|
|
4
6
|
export function initMessages(app) {
|
|
5
7
|
const $ = app.$;
|
|
@@ -52,7 +54,7 @@ export function initMessages(app) {
|
|
|
52
54
|
if (entry) {
|
|
53
55
|
entry.room = mergeRoom(entry.room, updated);
|
|
54
56
|
const latest = entry.room.messages.at(-1);
|
|
55
|
-
if (latest && latest.createdAt >= entry.previewAt)
|
|
57
|
+
if (latest && latest.createdAt >= entry.previewAt) setRoomPreview(entry, latest);
|
|
56
58
|
}
|
|
57
59
|
app.discardFailedMessage(roomId, failedId);
|
|
58
60
|
if (app.state.room?.id === roomId && entry) {
|
|
@@ -120,7 +122,7 @@ export function initMessages(app) {
|
|
|
120
122
|
if (message.senderId === "system") {
|
|
121
123
|
row.className = "sys";
|
|
122
124
|
const text = document.createElement("span");
|
|
123
|
-
text.textContent =
|
|
125
|
+
text.textContent = formatSystemMessage(message, app);
|
|
124
126
|
row.append(text);
|
|
125
127
|
} else {
|
|
126
128
|
const direct = app.state.room.kind === "direct";
|
|
@@ -142,8 +144,19 @@ export function initMessages(app) {
|
|
|
142
144
|
const body = document.createElement("div");
|
|
143
145
|
body.className = "msg-text";
|
|
144
146
|
renderMarkdown(body, message.text, app);
|
|
145
|
-
|
|
147
|
+
const content = document.createElement("div");
|
|
148
|
+
content.className = "msg-content";
|
|
149
|
+
content.append(body, receiptDetails(message, app));
|
|
150
|
+
row.append(meta, content);
|
|
146
151
|
}
|
|
152
|
+
const copy = document.createElement("button");
|
|
153
|
+
copy.type = "button";
|
|
154
|
+
copy.className = "message-copy";
|
|
155
|
+
copy.dataset.copyMessage = "";
|
|
156
|
+
copy.dataset.i18n = "copyMessage";
|
|
157
|
+
copy.textContent = app.t("copyMessage");
|
|
158
|
+
copy._copyText = String(message.text ?? "");
|
|
159
|
+
row.append(copy);
|
|
147
160
|
if (live) row.classList.add("in");
|
|
148
161
|
return row;
|
|
149
162
|
};
|
|
@@ -168,22 +181,21 @@ export function initMessages(app) {
|
|
|
168
181
|
app.renderMessages = (live = false) => {
|
|
169
182
|
const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
|
|
170
183
|
const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
|
|
171
|
-
let
|
|
184
|
+
let skipped = 0;
|
|
172
185
|
let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
|
|
173
|
-
let renderedIds = new Set([...list.children].map((node) => node.dataset.msgId).filter(Boolean));
|
|
174
186
|
const viewport = thread.getBoundingClientRect();
|
|
175
187
|
const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
|
|
176
188
|
anchorId = firstVisible?.dataset.msgId || null;
|
|
177
189
|
anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
}
|
|
184
|
-
for (let index =
|
|
190
|
+
pruneMessageRows(list, messages);
|
|
191
|
+
let last = list.lastElementChild;
|
|
192
|
+
const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
|
|
193
|
+
let startIndex = 0;
|
|
194
|
+
const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
|
|
195
|
+
if (lastId) for (let index = messages.length - 1; index >= 0; index--) if (messages[index].id === lastId) { startIndex = index + 1; break; }
|
|
196
|
+
for (let index = startIndex; index < messages.length; index++) {
|
|
185
197
|
const message = messages[index];
|
|
186
|
-
if (renderedIds.has(message.id)) continue;
|
|
198
|
+
if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id)) continue;
|
|
187
199
|
try {
|
|
188
200
|
const day = new Date(message.createdAt).toDateString();
|
|
189
201
|
if (!last || last.dataset.day !== day) {
|
|
@@ -277,7 +289,7 @@ export function initMessages(app) {
|
|
|
277
289
|
if (entry) {
|
|
278
290
|
entry.room = updated;
|
|
279
291
|
const latest = updated.messages.at(-1);
|
|
280
|
-
if (latest)
|
|
292
|
+
if (latest) setRoomPreview(entry, latest);
|
|
281
293
|
}
|
|
282
294
|
app.renderMessages(true);
|
|
283
295
|
$("#thread").scrollTop = $("#thread").scrollHeight;
|
|
@@ -334,15 +346,16 @@ export function initMessages(app) {
|
|
|
334
346
|
const roomId = app.state.room?.id;
|
|
335
347
|
if (!roomId || !isCurrentPoll(roomId, generation)) return;
|
|
336
348
|
try {
|
|
337
|
-
const
|
|
349
|
+
const entry = app.state.rooms.get(roomId);
|
|
350
|
+
const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, excludeSelf: "0", timeout: "25000", afterTs: String(entry?.receivedTs || 0) });
|
|
338
351
|
const data = await app.api(`/inbox?${query}`, { signal });
|
|
339
352
|
if (!isCurrentPoll(roomId, generation)) return;
|
|
340
|
-
if (
|
|
353
|
+
if (data.member === false) {
|
|
341
354
|
void app.removeJoinedRoom(roomId, { reason: true });
|
|
342
355
|
return;
|
|
343
356
|
}
|
|
344
|
-
|
|
345
|
-
const
|
|
357
|
+
if (data.member !== true || !Array.isArray(data.items)) return;
|
|
358
|
+
const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
|
|
346
359
|
const known = new Set(messages.map((message) => message.id));
|
|
347
360
|
let sawSystem = false, added = 0;
|
|
348
361
|
for (const item of items) {
|
|
@@ -351,9 +364,10 @@ export function initMessages(app) {
|
|
|
351
364
|
messages.push({ ...item, roomId });
|
|
352
365
|
known.add(item.id);
|
|
353
366
|
entry?.unreadIds.set(item.id, item);
|
|
354
|
-
if (entry && item.createdAt >= entry.previewAt)
|
|
367
|
+
if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
|
|
355
368
|
added++;
|
|
356
369
|
}
|
|
370
|
+
if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
|
|
357
371
|
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
358
372
|
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
359
373
|
const rendered = app.renderMessages(true);
|
|
@@ -373,7 +387,7 @@ export function initMessages(app) {
|
|
|
373
387
|
void app.reconcileRoom(roomId, generation);
|
|
374
388
|
}
|
|
375
389
|
app.setOnline(true);
|
|
376
|
-
pollDelay = 2000;
|
|
390
|
+
pollDelay = data.hasMore && (entry?.receivedTs || 0) > previousReceivedTs ? 0 : 2000;
|
|
377
391
|
} catch (error) {
|
|
378
392
|
if (!isCurrentPoll(roomId, generation)) return;
|
|
379
393
|
if (error.status === 401) {
|
|
@@ -434,7 +448,7 @@ export function initMessages(app) {
|
|
|
434
448
|
}
|
|
435
449
|
|
|
436
450
|
function trimMessages(list, app) {
|
|
437
|
-
if (list.children.length <= 400) return;
|
|
451
|
+
if (list.children.length <= 400 || hasMessageSelection(list)) return;
|
|
438
452
|
while (list.children.length > 300) list.removeChild(list.firstChild);
|
|
439
453
|
if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
|
|
440
454
|
const gap = document.createElement("li");
|
|
@@ -463,7 +477,10 @@ function updateReceiptDetails(row, message, app) {
|
|
|
463
477
|
const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
|
|
464
478
|
const readers = (app.state.receipts.get(detailsKey) || []).filter((reader) => reader.sessionID !== senderID);
|
|
465
479
|
details.hidden = readers.length === 0;
|
|
466
|
-
details.querySelector("
|
|
480
|
+
const summary = details.querySelector("summary"), label = app.t("receiptCount", { count: readers.length });
|
|
481
|
+
summary.setAttribute("aria-label", label);
|
|
482
|
+
summary.title = label;
|
|
483
|
+
details.querySelector(".receipt-count").textContent = String(readers.length);
|
|
467
484
|
const list = details.querySelector(".receipt-reader-list");
|
|
468
485
|
list.textContent = "";
|
|
469
486
|
const members = app.state.memberSessions.get(app.state.room?.id) || [];
|
|
@@ -480,10 +497,4 @@ function updateReceiptDetails(row, message, app) {
|
|
|
480
497
|
}
|
|
481
498
|
}
|
|
482
499
|
|
|
483
|
-
function systemMessage(text, app) {
|
|
484
|
-
const joined = /^(.*?)\s+joined the room$/.exec(String(text));
|
|
485
|
-
if (joined) return app.t("systemJoined", { name: joined[1] });
|
|
486
|
-
const left = /^(.*?)\s+left the room$/.exec(String(text));
|
|
487
|
-
return left ? app.t("systemLeft", { name: left[1] }) : String(text);
|
|
488
|
-
}
|
|
489
500
|
}
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
|
+
import { formatRoomPreview, setRoomPreview } from "./system-messages.js";
|
|
2
3
|
|
|
3
4
|
export function initRooms(app) {
|
|
4
5
|
const $ = app.$;
|
|
5
6
|
|
|
6
|
-
app.showJoin = () => {
|
|
7
|
+
app.showJoin = (refresh = true) => {
|
|
8
|
+
if (!$("#inName").value) $("#inName").value = LS.name;
|
|
7
9
|
$("#chatView").hidden = true;
|
|
8
10
|
$("#joinView").hidden = false;
|
|
9
11
|
app.updateTitle();
|
|
10
|
-
void app.refreshRoomList();
|
|
12
|
+
if (refresh) void app.refreshRoomList();
|
|
11
13
|
$("#inRoomId").focus();
|
|
12
14
|
};
|
|
13
15
|
app.showChat = () => {
|
|
@@ -34,13 +36,15 @@ export function initRooms(app) {
|
|
|
34
36
|
};
|
|
35
37
|
|
|
36
38
|
app.ensureJoinedRoom = (room, name) => {
|
|
37
|
-
const
|
|
39
|
+
const existing = app.state.rooms.get(room.id);
|
|
40
|
+
const entry = existing || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0, receivedTs: room.messages.at(-1)?.createdAt ?? 0 };
|
|
38
41
|
entry.unreadIds ||= new Map();
|
|
39
42
|
entry.unreadOverflow ||= false;
|
|
40
43
|
entry.room = room;
|
|
41
44
|
entry.name = name;
|
|
42
|
-
|
|
43
|
-
entry.
|
|
45
|
+
const latest = room.messages.at(-1);
|
|
46
|
+
entry.receivedTs ??= latest?.createdAt ?? 0;
|
|
47
|
+
if (latest && (!existing || latest.createdAt >= entry.previewAt)) setRoomPreview(entry, latest);
|
|
44
48
|
app.state.rooms.set(room.id, entry);
|
|
45
49
|
app.state.roomNames.set(room.id, name);
|
|
46
50
|
app.state.joinedIds.add(room.id);
|
|
@@ -68,7 +72,6 @@ export function initRooms(app) {
|
|
|
68
72
|
app.firstMessageId = null;
|
|
69
73
|
app.state.pendingAction = null;
|
|
70
74
|
LS.roomId = roomId;
|
|
71
|
-
LS.name = entry.name;
|
|
72
75
|
app.showChat();
|
|
73
76
|
app.renderHead();
|
|
74
77
|
$("#msgList").textContent = "";
|
|
@@ -102,6 +105,7 @@ export function initRooms(app) {
|
|
|
102
105
|
method: "POST",
|
|
103
106
|
body: JSON.stringify({ sessionID: LS.sessionID, participantId: name, participantName: name }),
|
|
104
107
|
});
|
|
108
|
+
LS.name = name;
|
|
105
109
|
app.enterRoom(room, name, intent);
|
|
106
110
|
} catch (error) {
|
|
107
111
|
if (error.status === 401) {
|
|
@@ -114,7 +118,7 @@ export function initRooms(app) {
|
|
|
114
118
|
|
|
115
119
|
app.createRoom = async (pending) => {
|
|
116
120
|
const fromChat = pending?.fromChat ?? Boolean(app.state.room);
|
|
117
|
-
const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || app.t("guest");
|
|
121
|
+
const name = pending?.name || (fromChat ? app.state.myName : $("#inName").value.trim()) || LS.name || app.t("guest");
|
|
118
122
|
const roomName = pending?.roomName || $(fromChat ? "#inRoomNameChat" : "#inRoomName").value.trim();
|
|
119
123
|
if (!roomName) return fromChat ? app.showSendError("roomNameRequired") : app.showJoinError("roomNameRequired");
|
|
120
124
|
const intent = ++app.state.navigationGeneration;
|
|
@@ -127,6 +131,7 @@ export function initRooms(app) {
|
|
|
127
131
|
method: "POST",
|
|
128
132
|
body: JSON.stringify({ name: roomName, ownerId: name, sessionID: LS.sessionID }),
|
|
129
133
|
});
|
|
134
|
+
LS.name = name;
|
|
130
135
|
if (fromChat) {
|
|
131
136
|
$("#inRoomNameChat").value = "";
|
|
132
137
|
$("#railRoomForm").hidden = true;
|
|
@@ -188,7 +193,6 @@ export function initRooms(app) {
|
|
|
188
193
|
if (next) app.activateRoom(next);
|
|
189
194
|
else {
|
|
190
195
|
LS.roomId = "";
|
|
191
|
-
LS.name = "";
|
|
192
196
|
app.showJoin();
|
|
193
197
|
if (reason) app.showJoinError("roomNotFound");
|
|
194
198
|
}
|
|
@@ -200,10 +204,11 @@ export function initRooms(app) {
|
|
|
200
204
|
|
|
201
205
|
app.startRoomWatcher = () => {
|
|
202
206
|
clearTimeout(app.state.watcherTimer);
|
|
203
|
-
if (!app.state.rooms.size) return;
|
|
207
|
+
if (!app.state.rooms.size && !app.state.restorePending?.size && !app.state.restoreRetry) return;
|
|
204
208
|
app.state.watcherTimer = setTimeout(async () => {
|
|
205
209
|
const inactive = [...app.state.rooms.keys()].filter((id) => id !== app.state.room?.id);
|
|
206
210
|
await bounded(inactive, 3, (roomId) => watchRoom(roomId, app));
|
|
211
|
+
if (app.state.restorePending?.size || app.state.restoreRetry) void app.refreshRoomList();
|
|
207
212
|
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
208
213
|
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
209
214
|
app.startRoomWatcher();
|
|
@@ -214,8 +219,9 @@ export function initRooms(app) {
|
|
|
214
219
|
const empty = $("#roomListEmpty"), chatEmpty = $("#roomListChatEmpty");
|
|
215
220
|
try {
|
|
216
221
|
const rooms = await app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`);
|
|
222
|
+
app.state.restoreRetry = false;
|
|
217
223
|
app.state.availableRooms = rooms;
|
|
218
|
-
if (!app.state.restored) await app.restoreJoinedRooms(rooms);
|
|
224
|
+
if (!app.state.restored || app.state.restorePending?.size) await app.restoreJoinedRooms(rooms);
|
|
219
225
|
else {
|
|
220
226
|
syncCachedRooms(rooms, app);
|
|
221
227
|
await app.discoverDirectRooms(rooms);
|
|
@@ -232,6 +238,11 @@ export function initRooms(app) {
|
|
|
232
238
|
empty.hidden = false;
|
|
233
239
|
chatEmpty.hidden = false;
|
|
234
240
|
}
|
|
241
|
+
if (!app.state.restored) {
|
|
242
|
+
app.state.restoreRetry = true;
|
|
243
|
+
app.state.restorePending = new Set([...app.state.joinedIds, LS.roomId].filter(Boolean));
|
|
244
|
+
app.startRoomWatcher();
|
|
245
|
+
}
|
|
235
246
|
}
|
|
236
247
|
};
|
|
237
248
|
|
|
@@ -244,8 +255,9 @@ export function initRooms(app) {
|
|
|
244
255
|
try {
|
|
245
256
|
const activeId = LS.roomId;
|
|
246
257
|
const directIds = rooms.filter((room) => room.kind === "direct" && room.directSessionIDs?.includes(LS.sessionID)).map((room) => room.id);
|
|
247
|
-
const candidates = [...new Set([...app.state.joinedIds, ...directIds])];
|
|
258
|
+
const candidates = [...new Set([activeId, ...rooms.filter((room) => room.joined).map((room) => room.id), ...app.state.joinedIds, ...directIds].filter(Boolean))];
|
|
248
259
|
const valid = new Set();
|
|
260
|
+
const unresolved = new Set();
|
|
249
261
|
await bounded(candidates, 3, async (roomId) => {
|
|
250
262
|
try {
|
|
251
263
|
const room = rooms.find((item) => item.id === roomId) || await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
@@ -254,18 +266,24 @@ export function initRooms(app) {
|
|
|
254
266
|
if (!me) return;
|
|
255
267
|
valid.add(roomId);
|
|
256
268
|
app.ensureJoinedRoom(room, me.name);
|
|
257
|
-
} catch {
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.status !== 404) {
|
|
271
|
+
unresolved.add(roomId);
|
|
272
|
+
if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
258
275
|
});
|
|
259
|
-
app.state.joinedIds = valid;
|
|
276
|
+
app.state.joinedIds = new Set([...valid, ...unresolved]);
|
|
277
|
+
app.state.restorePending = unresolved;
|
|
260
278
|
app.saveJoinedIds();
|
|
261
|
-
app.state.restored =
|
|
279
|
+
app.state.restored = unresolved.size === 0;
|
|
262
280
|
if (activeId && valid.has(activeId)) app.activateRoom(activeId);
|
|
281
|
+
else if (activeId && unresolved.has(activeId)) app.showJoin(false);
|
|
263
282
|
else {
|
|
264
283
|
LS.roomId = "";
|
|
265
|
-
LS.name = "";
|
|
266
284
|
const fallback = valid.values().next().value;
|
|
267
285
|
if (fallback) app.activateRoom(fallback);
|
|
268
|
-
else app.showJoin();
|
|
286
|
+
else app.showJoin(false);
|
|
269
287
|
}
|
|
270
288
|
app.startRoomWatcher();
|
|
271
289
|
} finally { app.state.restoring = false; }
|
|
@@ -278,8 +296,18 @@ export function initRooms(app) {
|
|
|
278
296
|
const members = await app.api(`/rooms/${encodeURIComponent(room.id)}/members`);
|
|
279
297
|
const me = members.find((member) => member.sessionID === LS.sessionID);
|
|
280
298
|
if (me) app.ensureJoinedRoom(room, me.name);
|
|
281
|
-
} catch {
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.status !== 404) {
|
|
301
|
+
app.state.restorePending ||= new Set();
|
|
302
|
+
app.state.restorePending.add(room.id);
|
|
303
|
+
app.state.joinedIds.add(room.id);
|
|
304
|
+
app.saveJoinedIds();
|
|
305
|
+
app.state.restored = false;
|
|
306
|
+
if (error.status === 401) app.state.room ? app.openChatSettings() : app.openTokenBox();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
282
309
|
});
|
|
310
|
+
if (app.state.restorePending?.size) app.startRoomWatcher();
|
|
283
311
|
};
|
|
284
312
|
|
|
285
313
|
app.renderRoomOptions = (list, rooms) => {
|
|
@@ -306,8 +334,7 @@ export function initRooms(app) {
|
|
|
306
334
|
meta.textContent = app.t("roomMeta", { members: shownRoom.participants.length, count: shownRoom.messages.length });
|
|
307
335
|
const preview = document.createElement("span");
|
|
308
336
|
preview.className = "r-preview";
|
|
309
|
-
|
|
310
|
-
preview.textContent = entry ? lastMessage : "";
|
|
337
|
+
preview.textContent = entry ? formatRoomPreview(entry, room.messages.at(-1), app) : "";
|
|
311
338
|
const status = document.createElement("span");
|
|
312
339
|
status.className = "r-status";
|
|
313
340
|
app.setText(status, entry ? "joined" : "joinAction");
|
|
@@ -398,12 +425,12 @@ function syncCachedRooms(rooms, app) {
|
|
|
398
425
|
const remote = new Map(rooms.map((room) => [room.id, room]));
|
|
399
426
|
for (const [roomId, entry] of app.state.rooms) {
|
|
400
427
|
const fresh = remote.get(roomId);
|
|
401
|
-
if (!fresh) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
|
|
428
|
+
if (!fresh || fresh.joined === false) { void app.removeJoinedRoom(roomId, { reason: app.state.room?.id === roomId }); continue; }
|
|
402
429
|
if (app.state.room?.id === roomId) continue;
|
|
403
430
|
const messages = new Map([...entry.room.messages, ...fresh.messages].map((message) => [message.id, message]));
|
|
404
431
|
entry.room = { ...fresh, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
405
432
|
const latest = entry.room.messages.at(-1);
|
|
406
|
-
if (latest)
|
|
433
|
+
if (latest) setRoomPreview(entry, latest);
|
|
407
434
|
}
|
|
408
435
|
}
|
|
409
436
|
|
|
@@ -412,19 +439,22 @@ async function watchRoom(roomId, app) {
|
|
|
412
439
|
if (!entry || app.state.room?.id === roomId) return;
|
|
413
440
|
try {
|
|
414
441
|
const query = new URLSearchParams({ sessionID: app.LS.sessionID, roomId, excludeSelf: "0", timeout: "0" });
|
|
442
|
+
query.set("afterTs", String(entry.receivedTs || 0));
|
|
415
443
|
const result = await app.api(`/inbox?${query}`);
|
|
416
444
|
if (app.state.rooms.get(roomId) !== entry) return;
|
|
417
|
-
if (
|
|
445
|
+
if (result.member === false) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
|
|
446
|
+
if (result.member !== true || !Array.isArray(result.items)) return;
|
|
418
447
|
if (app.state.room?.id === roomId) return;
|
|
448
|
+
const previousReceivedTs = entry.receivedTs || 0;
|
|
419
449
|
const sawSystem = (result.items || []).some((message) => message.senderId === "system");
|
|
420
450
|
for (const message of result.items || []) {
|
|
421
451
|
if (!entry.unreadIds.has(message.id)) entry.unreadIds.set(message.id, message);
|
|
422
452
|
if (!entry.room.messages.some((item) => item.id === message.id)) entry.room.messages.push({ ...message, roomId });
|
|
423
453
|
if (message.createdAt >= entry.previewAt) {
|
|
424
|
-
entry
|
|
425
|
-
entry.previewAt = message.createdAt;
|
|
454
|
+
setRoomPreview(entry, message);
|
|
426
455
|
}
|
|
427
456
|
}
|
|
457
|
+
entry.receivedTs = (result.items || []).reduce((latest, message) => Number.isSafeInteger(message.createdAt) ? Math.max(latest, message.createdAt) : latest, previousReceivedTs);
|
|
428
458
|
if (sawSystem || result.hasMore) {
|
|
429
459
|
const latest = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
430
460
|
if (app.state.rooms.get(roomId) !== entry || app.state.room?.id === roomId) return;
|
|
@@ -432,10 +462,11 @@ async function watchRoom(roomId, app) {
|
|
|
432
462
|
const messages = new Map([...entry.room.messages, ...latest.messages].map((message) => [message.id, message]));
|
|
433
463
|
entry.room.messages = [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500);
|
|
434
464
|
const newest = latest.messages.at(-1);
|
|
435
|
-
if (newest && newest.createdAt >= entry.previewAt)
|
|
465
|
+
if (newest && newest.createdAt >= entry.previewAt) setRoomPreview(entry, newest);
|
|
436
466
|
}
|
|
437
467
|
entry.unreadOverflow = Boolean(result.hasMore);
|
|
438
468
|
if (entry.room.messages.length > 500) entry.room.messages.splice(0, entry.room.messages.length - 500);
|
|
469
|
+
if (result.hasMore && entry.receivedTs > previousReceivedTs) await watchRoom(roomId, app);
|
|
439
470
|
} catch (error) {
|
|
440
471
|
if (error.status === 401) app.openChatSettings();
|
|
441
472
|
else if (error.status === 404) await app.removeJoinedRoom(roomId, { reason: false });
|
|
@@ -29,7 +29,16 @@ export function createRandomId() {
|
|
|
29
29
|
|
|
30
30
|
export function createAuth(storage, fetcher, translate = (key) => key, sessionStore) {
|
|
31
31
|
const memory = Object.create(null);
|
|
32
|
-
let
|
|
32
|
+
let browserIdentity, identityPersistent = false, identityConflict = false;
|
|
33
|
+
const identityKey = "chat.browserIdentity";
|
|
34
|
+
const validSessionID = (id) => typeof id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id);
|
|
35
|
+
const parseIdentity = (value) => {
|
|
36
|
+
try {
|
|
37
|
+
const identity = JSON.parse(value);
|
|
38
|
+
return validSessionID(identity?.sessionID) && typeof identity.name === "string" && identity.name.length <= 64
|
|
39
|
+
? { sessionID: identity.sessionID, name: identity.name } : undefined;
|
|
40
|
+
} catch { return undefined; }
|
|
41
|
+
};
|
|
33
42
|
const read = (key) => {
|
|
34
43
|
if (Object.hasOwn(memory, key)) return memory[key];
|
|
35
44
|
try { return (storage ?? globalThis.localStorage).getItem(key); } catch { return null; }
|
|
@@ -53,19 +62,63 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
53
62
|
else store.setItem(key, value);
|
|
54
63
|
} catch { /* Tab-scoped state is best effort. */ }
|
|
55
64
|
};
|
|
65
|
+
const syncTabIdentity = () => {
|
|
66
|
+
writeSession("chat.sessionID", browserIdentity.sessionID);
|
|
67
|
+
writeSession("chat.name", browserIdentity.name || null);
|
|
68
|
+
};
|
|
69
|
+
const ensureIdentity = () => {
|
|
70
|
+
if (browserIdentity) return browserIdentity;
|
|
71
|
+
let store;
|
|
72
|
+
try {
|
|
73
|
+
store = storage ?? globalThis.localStorage;
|
|
74
|
+
const canonical = parseIdentity(store.getItem(identityKey));
|
|
75
|
+
if (canonical) { browserIdentity = canonical; identityPersistent = true; syncTabIdentity(); return canonical; }
|
|
76
|
+
} catch { /* Keep this tab's identity in memory when storage is blocked. */ }
|
|
77
|
+
const previousID = readSession("chat.sessionID");
|
|
78
|
+
browserIdentity = { sessionID: validSessionID(previousID) ? previousID : createRandomId(), name: validSessionID(previousID) ? (readSession("chat.name") || "").slice(0, 64) : "" };
|
|
79
|
+
syncTabIdentity();
|
|
80
|
+
try {
|
|
81
|
+
store ||= storage ?? globalThis.localStorage;
|
|
82
|
+
store.setItem(identityKey, JSON.stringify(browserIdentity));
|
|
83
|
+
const saved = parseIdentity(store.getItem(identityKey));
|
|
84
|
+
if (saved?.sessionID === browserIdentity.sessionID) { browserIdentity = saved; identityPersistent = true; }
|
|
85
|
+
else if (saved) identityConflict = true;
|
|
86
|
+
} catch { /* This page keeps its in-memory identity without claiming persistence. */ }
|
|
87
|
+
return browserIdentity;
|
|
88
|
+
};
|
|
89
|
+
const identityError = () => {
|
|
90
|
+
const error = new Error(translate("identityChanged"));
|
|
91
|
+
error.identityConflict = true;
|
|
92
|
+
return error;
|
|
93
|
+
};
|
|
94
|
+
const assertIdentity = () => {
|
|
95
|
+
ensureIdentity();
|
|
96
|
+
if (identityConflict) throw identityError();
|
|
97
|
+
try {
|
|
98
|
+
const current = parseIdentity((storage ?? globalThis.localStorage).getItem(identityKey));
|
|
99
|
+
if (current && current.sessionID !== browserIdentity.sessionID || identityPersistent && !current) {
|
|
100
|
+
identityConflict = true;
|
|
101
|
+
throw identityError();
|
|
102
|
+
}
|
|
103
|
+
if (current) identityPersistent = true;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error?.identityConflict) throw error;
|
|
106
|
+
identityPersistent = false;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const saveIdentity = () => {
|
|
110
|
+
if (!identityPersistent) return;
|
|
111
|
+
try {
|
|
112
|
+
const store = storage ?? globalThis.localStorage;
|
|
113
|
+
const current = parseIdentity(store.getItem(identityKey));
|
|
114
|
+
if (current?.sessionID !== browserIdentity.sessionID) { identityConflict = true; return; }
|
|
115
|
+
store.setItem(identityKey, JSON.stringify(browserIdentity));
|
|
116
|
+
if (parseIdentity(store.getItem(identityKey))?.sessionID !== browserIdentity.sessionID) identityConflict = true;
|
|
117
|
+
} catch { /* Keep the preferred name in memory when persistence is blocked. */ }
|
|
118
|
+
};
|
|
56
119
|
const auth = {
|
|
57
120
|
get sessionID() {
|
|
58
|
-
|
|
59
|
-
try {
|
|
60
|
-
const store = sessionStore ?? globalThis.sessionStorage;
|
|
61
|
-
memorySessionID = store.getItem("chat.sessionID") || "";
|
|
62
|
-
} catch { /* Keep one identity in memory when tab storage is blocked. */ }
|
|
63
|
-
if (!memorySessionID) {
|
|
64
|
-
memorySessionID = createRandomId();
|
|
65
|
-
try { (sessionStore ?? globalThis.sessionStorage).setItem("chat.sessionID", memorySessionID); }
|
|
66
|
-
catch { /* In-memory identity remains stable. */ }
|
|
67
|
-
}
|
|
68
|
-
return memorySessionID;
|
|
121
|
+
return ensureIdentity().sessionID;
|
|
69
122
|
},
|
|
70
123
|
get roomId() {
|
|
71
124
|
const active = readSession("chat.roomId");
|
|
@@ -75,8 +128,8 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
75
128
|
return legacy || "";
|
|
76
129
|
},
|
|
77
130
|
set roomId(value) { writeSession("chat.roomId", value || null); write("chat.roomId", null); },
|
|
78
|
-
get name() { return
|
|
79
|
-
set name(value) {
|
|
131
|
+
get name() { return ensureIdentity().name; },
|
|
132
|
+
set name(value) { ensureIdentity(); browserIdentity.name = String(value ?? "").slice(0, 64); writeSession("chat.name", browserIdentity.name || null); saveIdentity(); },
|
|
80
133
|
get token() { return read("chat.token") || ""; }, set token(value) { write("chat.token", value || null); },
|
|
81
134
|
get locale() { return read("chat.locale") || "en"; }, set locale(value) { write("chat.locale", value || null); },
|
|
82
135
|
get joinedRoomIds() {
|
|
@@ -102,6 +155,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
102
155
|
};
|
|
103
156
|
const saveToken = (value) => { auth.token = String(value ?? "").trim(); return auth.token; };
|
|
104
157
|
const api = async (url, options = {}) => {
|
|
158
|
+
assertIdentity();
|
|
105
159
|
const headers = { ...options.headers };
|
|
106
160
|
if (options.body) headers["Content-Type"] = "application/json";
|
|
107
161
|
if (auth.token) headers.Authorization = `Bearer ${auth.token}`;
|
|
@@ -113,6 +167,7 @@ export function createAuth(storage, fetcher, translate = (key) => key, sessionSt
|
|
|
113
167
|
throw error;
|
|
114
168
|
}
|
|
115
169
|
const data = await response.json().catch(() => ({}));
|
|
170
|
+
assertIdentity();
|
|
116
171
|
if (!response.ok) {
|
|
117
172
|
const error = new Error(data.error || translate("requestFailed", { status: response.status }));
|
|
118
173
|
error.status = response.status;
|
|
@@ -149,6 +204,8 @@ const messages = {
|
|
|
149
204
|
earlierMessages: "Earlier messages omitted", you: "You", saved: "Saved",
|
|
150
205
|
savedMemory: "Saved for this tab only", copyFailed: ({ id }) => `Copy failed. Copy manually: ${id}`,
|
|
151
206
|
copyCode: "Copy code", copiedCode: "Copied", copyCodeFailed: "Could not copy code. Select and copy it manually.",
|
|
207
|
+
copyMessage: "Copy", copiedMessage: "Copied", copyMessageFailed: "Could not copy. Select and copy the message manually.",
|
|
208
|
+
identityChanged: "This browser identity changed in another tab. Reload this tab before continuing.",
|
|
152
209
|
networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
|
|
153
210
|
roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
|
|
154
211
|
networkRetry: "Unable to connect to the server. Check your network and try again.",
|
|
@@ -165,7 +222,7 @@ const messages = {
|
|
|
165
222
|
deleteRoom: "Delete room", deleteConfirm: ({ name }) => `Delete “${name}” and all its messages? This cannot be undone.`,
|
|
166
223
|
allMembers: "Everyone", messageCount: ({ count }) => `${count} / 2000`,
|
|
167
224
|
privacyNote: "Anyone with the shared token can read direct messages and manage rooms; the server can read them too.",
|
|
168
|
-
systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`,
|
|
225
|
+
systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`, systemRemoved: ({ name }) => `${name} was removed from the room`,
|
|
169
226
|
activity_working: "Working", activity_idle: "Foreground idle", activity_waiting: "Waiting", activity_unknown: "Status unknown", activity_offline: "Status stale",
|
|
170
227
|
activityHint_working: "The agent reports active work.", activityHint_idle: "Foreground is idle; background work may continue.", activityHint_waiting: "The agent reports that it is waiting.", activityHint_unknown: "No activity report is available.", activityHint_offline: "The last status is stale; this does not prove the agent is offline.",
|
|
171
228
|
receiptCount: ({ count }) => `Read by ${count}`, departedMember: "left",
|
|
@@ -192,6 +249,8 @@ const messages = {
|
|
|
192
249
|
today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", you: "我", saved: "已保存",
|
|
193
250
|
savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
|
|
194
251
|
copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
|
|
252
|
+
copyMessage: "复制", copiedMessage: "已复制", copyMessageFailed: "复制失败,请手动选择并复制消息。",
|
|
253
|
+
identityChanged: "此浏览器身份已在另一个标签页中更改,请重新加载此标签页后继续。",
|
|
195
254
|
networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
|
|
196
255
|
roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
|
|
197
256
|
networkRetry: "无法连接服务器,请检查网络后重试", joinFailed: ({ message }) => `加入失败:${message}`,
|
|
@@ -205,7 +264,7 @@ const messages = {
|
|
|
205
264
|
deleteRoom: "删除房间", deleteConfirm: ({ name }) => `删除“${name}”及全部聊天记录?此操作无法撤销。`,
|
|
206
265
|
allMembers: "所有人", messageCount: ({ count }) => `${count} / 2000`,
|
|
207
266
|
privacyNote: "持有共享令牌的人都可以读取私聊内容和管理房间;服务器也可以读取私聊内容。",
|
|
208
|
-
systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`,
|
|
267
|
+
systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`, systemRemoved: ({ name }) => `${name} 被移出了房间`,
|
|
209
268
|
activity_working: "工作中", activity_idle: "前台空闲", activity_waiting: "等待中", activity_unknown: "状态未知", activity_offline: "状态已过期",
|
|
210
269
|
activityHint_working: "Agent 正在报告工作状态。", activityHint_idle: "前台空闲;后台任务仍可能继续。", activityHint_waiting: "Agent 正在报告等待状态。", activityHint_unknown: "暂无活动状态报告。", activityHint_offline: "最近的状态已过期;这不能证明 Agent 已离线。",
|
|
211
270
|
receiptCount: ({ count }) => `已读 ${count} 人`, departedMember: "已离开",
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function formatSystemMessage(message, app) {
|
|
2
|
+
const text = String(message?.text ?? "");
|
|
3
|
+
if (message?.senderId !== "system") return text;
|
|
4
|
+
const joined = /^(.*?)\s+joined the room$/.exec(text);
|
|
5
|
+
if (joined) return app.t("systemJoined", { name: joined[1] });
|
|
6
|
+
const left = /^(.*?)\s+left the room$/.exec(text);
|
|
7
|
+
if (left) return app.t("systemLeft", { name: left[1] });
|
|
8
|
+
const removed = /^(.*?)\s+was removed from the room$/.exec(text);
|
|
9
|
+
return removed ? app.t("systemRemoved", { name: removed[1] }) : text;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function setRoomPreview(entry, message) {
|
|
13
|
+
entry.preview = message.text;
|
|
14
|
+
entry.previewAt = message.createdAt;
|
|
15
|
+
entry.previewSenderId = message.senderId;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function formatRoomPreview(entry, latest, app) {
|
|
19
|
+
return formatSystemMessage(entry?.preview ? { senderId: entry.previewSenderId, text: entry.preview } : latest, app);
|
|
20
|
+
}
|
|
@@ -181,9 +181,29 @@
|
|
|
181
181
|
overflow-wrap: anywhere;
|
|
182
182
|
}
|
|
183
183
|
.msg.own .msg-text { background: var(--accent-soft); border-bottom-left-radius: 14px; border-bottom-right-radius: 4px; }
|
|
184
|
-
.
|
|
185
|
-
.
|
|
186
|
-
.
|
|
184
|
+
.msg-content { position: relative; display: flex; align-items: flex-end; gap: 6px; width: fit-content; max-width: 100%; }
|
|
185
|
+
.msg.own .msg-content { flex-direction: row-reverse; }
|
|
186
|
+
.message-copy {
|
|
187
|
+
align-self: flex-start;
|
|
188
|
+
margin: 2px 0 0 4px;
|
|
189
|
+
padding: 2px 6px;
|
|
190
|
+
border: 0;
|
|
191
|
+
border-radius: 5px;
|
|
192
|
+
color: var(--ink-3);
|
|
193
|
+
background: transparent;
|
|
194
|
+
font: inherit;
|
|
195
|
+
font-size: 11px;
|
|
196
|
+
cursor: pointer;
|
|
197
|
+
}
|
|
198
|
+
.msg.own .message-copy { align-self: flex-end; margin-right: 4px; }
|
|
199
|
+
.message-copy:hover, .message-copy:focus-visible { color: var(--ink); background: var(--surface-2); }
|
|
200
|
+
.message-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
201
|
+
.message-readers { position: static; flex: 0 0 22px; margin: 0 0 4px; color: var(--ink-3); font-size: 11px; }
|
|
202
|
+
.message-readers summary { display: grid; place-items: center; width: 22px; height: 22px; box-sizing: border-box; border: 1px solid var(--line); border-radius: 50%; background: var(--surface); cursor: pointer; list-style: none; }
|
|
203
|
+
.message-readers summary::-webkit-details-marker { display: none; }
|
|
204
|
+
.message-readers summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
205
|
+
.receipt-reader-list { position: absolute; z-index: 5; left: 0; top: 100%; min-width: min(210px, calc(100vw - 32px)); max-width: calc(100vw - 24px); box-sizing: border-box; margin: 4px 0 0; padding: 5px 8px; list-style: none; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); box-shadow: var(--shadow); }
|
|
206
|
+
.msg.own .receipt-reader-list { right: 0; left: auto; }
|
|
187
207
|
.receipt-reader-list li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; }
|
|
188
208
|
.receipt-reader-list li + li { margin-top: 4px; }
|
|
189
209
|
.receipt-reader-list li span:last-child { color: var(--ink-3); }
|
|
@@ -297,15 +317,18 @@
|
|
|
297
317
|
}
|
|
298
318
|
|
|
299
319
|
.sys {
|
|
320
|
+
position: relative;
|
|
300
321
|
display: flex;
|
|
322
|
+
flex-direction: column;
|
|
301
323
|
align-items: center;
|
|
302
|
-
gap:
|
|
324
|
+
gap: 8px;
|
|
303
325
|
margin: 20px 0;
|
|
304
326
|
font-size: 12.5px;
|
|
305
327
|
color: var(--ink-2);
|
|
306
328
|
}
|
|
307
|
-
.sys::before
|
|
308
|
-
.sys span {
|
|
329
|
+
.sys::before { content: ""; position: absolute; top: 9px; left: 0; right: 0; height: 1px; background: var(--line); }
|
|
330
|
+
.sys span { position: relative; padding: 0 10px; background: var(--surface); }
|
|
331
|
+
.sys .message-copy { align-self: center; margin: -8px 0 0; }
|
|
309
332
|
|
|
310
333
|
.day-sep {
|
|
311
334
|
display: flex;
|
package/server/chat-server.ts
CHANGED
|
@@ -145,8 +145,10 @@ async function handle(req: Request): Promise<Response> {
|
|
|
145
145
|
}
|
|
146
146
|
if (req.method === "GET" && p === "/rooms") {
|
|
147
147
|
const caller = url.searchParams.get("sessionID");
|
|
148
|
-
const rooms = await
|
|
149
|
-
|
|
148
|
+
const rooms = await readState((svc, registry) => svc.listRooms()
|
|
149
|
+
.filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller))
|
|
150
|
+
.map((room) => ({ ...serializeRoom(room), joined: Boolean(caller && registry[room.id]?.[caller]) })));
|
|
151
|
+
return json(rooms);
|
|
150
152
|
}
|
|
151
153
|
const members = await memberRoutes(req, url);
|
|
152
154
|
if (members) return members;
|
|
@@ -197,6 +199,12 @@ async function handle(req: Request): Promise<Response> {
|
|
|
197
199
|
if (req.method === "GET" && p === "/inbox") {
|
|
198
200
|
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
199
201
|
const roomFilter = url.searchParams.get("roomId");
|
|
202
|
+
const afterValue = url.searchParams.get("afterTs");
|
|
203
|
+
const afterTs = afterValue === null ? undefined : Number(afterValue);
|
|
204
|
+
if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") ||
|
|
205
|
+
!Number.isSafeInteger(afterTs) || afterTs! < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
|
|
206
|
+
return json({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
|
|
207
|
+
}
|
|
200
208
|
// ponytail: poll includes the caller's own messages (echo), the
|
|
201
209
|
// notification self-pull excludes them — aligned with standalone poll
|
|
202
210
|
const excludeSelf = url.searchParams.get("excludeSelf") === "1";
|
|
@@ -208,12 +216,12 @@ async function handle(req: Request): Promise<Response> {
|
|
|
208
216
|
30000,
|
|
209
217
|
);
|
|
210
218
|
const deadline = Date.now() + timeout;
|
|
211
|
-
let result = await readInbox(sessionID, roomFilter, excludeSelf);
|
|
219
|
+
let result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
212
220
|
while (result.items.length === 0 && Date.now() < deadline) {
|
|
213
221
|
// ponytail: 2s between disk scans (orc-1 #7) — 1s × 25 iterations
|
|
214
222
|
// doubles the file reads on shared-mount deployments
|
|
215
223
|
await sleep(2000);
|
|
216
|
-
result = await readInbox(sessionID, roomFilter, excludeSelf);
|
|
224
|
+
result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
|
|
217
225
|
}
|
|
218
226
|
return json(result);
|
|
219
227
|
}
|
package/server/inbox.ts
CHANGED
|
@@ -4,6 +4,6 @@ import type { Message } from "../src/room-service";
|
|
|
4
4
|
export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "senderSessionID" | "text" | "createdAt"> & { roomName: string; roomKind?: "group" | "direct" };
|
|
5
5
|
export type InboxResult = { member: boolean; items: InboxItem[]; queuedTs: Record<string, number>; hasMore: boolean };
|
|
6
6
|
|
|
7
|
-
export async function readInbox(sessionID: string, roomFilter: string | null, excludeSelf: boolean): Promise<InboxResult> {
|
|
8
|
-
return readInboxMessages(sessionID, roomFilter, excludeSelf, excludeSelf ? 20 : 100);
|
|
7
|
+
export async function readInbox(sessionID: string, roomFilter: string | null, excludeSelf: boolean, afterTs?: number): Promise<InboxResult> {
|
|
8
|
+
return readInboxMessages(sessionID, roomFilter, excludeSelf, excludeSelf ? 20 : 100, afterTs);
|
|
9
9
|
}
|
package/src/agent-receipts.ts
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { databasePath, recordMessageReceipts } from "./store";
|
|
3
|
+
import { databasePath, formatNotificationLines, NOTIFY_INSTRUCTION, recordMessageReceipts, timeOf } from "./store";
|
|
4
4
|
import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "./receiver-state";
|
|
5
5
|
|
|
6
6
|
// shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
|
|
7
7
|
const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
|
|
8
|
-
type Item = { id?: string; text: string };
|
|
8
|
+
type Item = { id?: string; text: string; senderId?: string; createdAt?: number };
|
|
9
|
+
type CappedItem = Item & { senderId: string; createdAt: number };
|
|
9
10
|
export type ReceiptCandidate = {
|
|
10
11
|
admissionID: string; sessionID: string; roomID: string; membershipID: string;
|
|
11
12
|
receiverOwnerID: string; destination: string; messageIDs: string[]; textHash: string; createdAt: number;
|
|
12
13
|
};
|
|
13
14
|
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
|
|
15
|
+
function hasCappedMetadata(item: Item): item is CappedItem {
|
|
16
|
+
return typeof item.senderId === "string" && typeof item.createdAt === "number" && Number.isSafeInteger(item.createdAt) &&
|
|
17
|
+
!/[\r\n]/.test(item.senderId) && !/[\r\n]/.test(item.text);
|
|
18
|
+
}
|
|
14
19
|
|
|
15
20
|
export function receiptDestination(center: string): string {
|
|
16
21
|
if (!center) return path.resolve(databasePath());
|
|
@@ -23,13 +28,41 @@ export function prepareReceiptCandidate(input: {
|
|
|
23
28
|
admissionID: string; sessionID: string; roomID: string; membershipID?: string;
|
|
24
29
|
receiverOwnerID?: string; destination: string; items: Item[]; prompt: string; capped: boolean;
|
|
25
30
|
}): ReceiptCandidate | undefined {
|
|
26
|
-
if (
|
|
31
|
+
if (!input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
|
|
27
32
|
!input.sessionID || input.sessionID.length > 128 || !input.roomID || input.roomID.length > 128 ||
|
|
28
33
|
!input.items.length || input.items.length > 500 || input.items.some((item) => typeof item.id !== "string" || !item.id || item.id.length > 128 || typeof item.text !== "string")) return undefined;
|
|
34
|
+
// shortcut: capped multiline notifications fail closed; use structured rendered-line metadata if partial proofs become necessary.
|
|
35
|
+
let evidenceItems = input.items;
|
|
36
|
+
if (input.capped) {
|
|
37
|
+
const cappedItems = input.items.filter(hasCappedMetadata);
|
|
38
|
+
if (cappedItems.length !== input.items.length) return undefined;
|
|
39
|
+
const instruction = input.prompt.lastIndexOf(`\n${NOTIFY_INSTRUCTION}\n</notification>`);
|
|
40
|
+
if (instruction < 0) return undefined;
|
|
41
|
+
const renderedCounts = new Map<string, number>();
|
|
42
|
+
for (const item of cappedItems) {
|
|
43
|
+
const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
|
|
44
|
+
const key = `${prefix}${item.text}`;
|
|
45
|
+
renderedCounts.set(key, (renderedCounts.get(key) ?? 0) + 1);
|
|
46
|
+
}
|
|
47
|
+
let tail = input.prompt.slice(0, instruction);
|
|
48
|
+
evidenceItems = [];
|
|
49
|
+
for (let index = cappedItems.length - 1; index >= 0; index--) {
|
|
50
|
+
const item = cappedItems[index]!;
|
|
51
|
+
const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
|
|
52
|
+
const line = tail.lastIndexOf(prefix);
|
|
53
|
+
if (line < 0) break;
|
|
54
|
+
const displayedText = tail.slice(line + prefix.length);
|
|
55
|
+
if (displayedText.includes("\n")) break;
|
|
56
|
+
if (displayedText === item.text && renderedCounts.get(`${prefix}${item.text}`) === 1 && !formatNotificationLines([item]).capped) evidenceItems.push(item);
|
|
57
|
+
tail = tail.slice(0, line);
|
|
58
|
+
}
|
|
59
|
+
evidenceItems.reverse();
|
|
60
|
+
}
|
|
61
|
+
if (!evidenceItems.length) return undefined;
|
|
29
62
|
const candidate: ReceiptCandidate = {
|
|
30
63
|
admissionID: input.admissionID, sessionID: input.sessionID, roomID: input.roomID,
|
|
31
64
|
membershipID: input.membershipID, receiverOwnerID: input.receiverOwnerID,
|
|
32
|
-
destination: input.destination, messageIDs:
|
|
65
|
+
destination: input.destination, messageIDs: evidenceItems.map((item) => item.id!),
|
|
33
66
|
textHash: hash(input.prompt), createdAt: Date.now(),
|
|
34
67
|
};
|
|
35
68
|
const key = hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
|
|
@@ -61,25 +94,37 @@ export function observeReceiptContext(sessionID: string, messages: readonly unkn
|
|
|
61
94
|
}
|
|
62
95
|
|
|
63
96
|
const receiptFlushes = new Map<string, Promise<void>>();
|
|
97
|
+
// shortcut: cursor resets on process restart; persist it if restart storms delay backlog progress.
|
|
98
|
+
const receiptFlushCursors = new Map<string, string>();
|
|
99
|
+
const RECEIPT_FLUSH_LIMIT = 8;
|
|
100
|
+
const RECEIPT_FLUSH_LEASE_MS = 30_000;
|
|
64
101
|
export function flushReceiptCandidates(input: {
|
|
65
102
|
destination: string; receiverOwnerID?: string; center?: string; token?: string;
|
|
66
103
|
}): Promise<void> {
|
|
67
104
|
const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
|
|
68
105
|
const running = receiptFlushes.get(key);
|
|
69
106
|
if (running) return running;
|
|
70
|
-
const task = flushOneReceiptCandidate(input).finally(() => receiptFlushes.delete(key));
|
|
107
|
+
const task = flushOneReceiptCandidate(input, key).finally(() => receiptFlushes.delete(key));
|
|
71
108
|
receiptFlushes.set(key, task);
|
|
72
109
|
return task;
|
|
73
110
|
}
|
|
74
111
|
|
|
75
|
-
async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }): Promise<void> {
|
|
76
|
-
const leaseKey = `receipt-flush:${hash(
|
|
112
|
+
async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }, cursorKey: string): Promise<void> {
|
|
113
|
+
const leaseKey = `receipt-flush:${hash(cursorKey)}`;
|
|
77
114
|
const holder = randomUUID(), now = Date.now();
|
|
78
|
-
if (!acquireDeliveryLease(leaseKey, holder, now, now +
|
|
115
|
+
if (!acquireDeliveryLease(leaseKey, holder, now, now + RECEIPT_FLUSH_LEASE_MS)) return;
|
|
79
116
|
try {
|
|
80
117
|
let candidates: Array<{ id: string; value: ReceiptCandidate }>;
|
|
81
|
-
|
|
118
|
+
let cursor = receiptFlushCursors.get(cursorKey) ?? "";
|
|
119
|
+
try {
|
|
120
|
+
candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT, cursor);
|
|
121
|
+
if (!candidates.length && cursor) {
|
|
122
|
+
cursor = "";
|
|
123
|
+
candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
82
126
|
catch { return; }
|
|
127
|
+
if (candidates.length) receiptFlushCursors.set(cursorKey, candidates.at(-1)!.id);
|
|
83
128
|
for (const { id, value } of candidates) {
|
|
84
129
|
try {
|
|
85
130
|
if (input.center) {
|
package/src/receiver-state.ts
CHANGED
|
@@ -121,11 +121,13 @@ export function markReceiptCandidateReady(id: string): boolean {
|
|
|
121
121
|
return immediate((db) => db.query("UPDATE receipt_candidates SET ready=1,expires_at=? WHERE candidate_id=? AND ready=0")
|
|
122
122
|
.run(Number.MAX_SAFE_INTEGER, id).changes === 1);
|
|
123
123
|
}
|
|
124
|
-
export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number): Array<{ id: string; value: T }> {
|
|
124
|
+
export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number, afterID?: string): Array<{ id: string; value: T }> {
|
|
125
125
|
return immediate((db) => {
|
|
126
126
|
db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(now);
|
|
127
|
-
const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" +
|
|
128
|
-
|
|
127
|
+
const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" +
|
|
128
|
+
(afterID !== undefined ? " AND candidate_id>?" : "") + " ORDER BY candidate_id" + (limit ? " LIMIT ?" : "");
|
|
129
|
+
const args = [destination, ownerID ?? "", ...(afterID !== undefined ? [afterID] : []), ...(limit ? [limit] : [])];
|
|
130
|
+
const rows = db.query(query).all(...args) as Array<{ candidate_id: string; candidate: string }>;
|
|
129
131
|
return rows.map((row) => ({ id: row.candidate_id, value: JSON.parse(row.candidate) as T }));
|
|
130
132
|
});
|
|
131
133
|
}
|
package/src/sqlite-state.ts
CHANGED
|
@@ -261,7 +261,7 @@ export async function readUnreadPage(file: string, roomID: string, afterTs: numb
|
|
|
261
261
|
return { items: newest ? items.reverse() : items, hasMore };
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
-
export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100) {
|
|
264
|
+
export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100, afterTs?: number) {
|
|
265
265
|
const db = await open(file);
|
|
266
266
|
return db.transaction(() => {
|
|
267
267
|
const take = Math.min(200, Math.max(1, limit));
|
|
@@ -269,9 +269,9 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
|
|
|
269
269
|
const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,r.name AS room_name,r.kind AS room_kind
|
|
270
270
|
FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
|
|
271
271
|
WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
|
|
272
|
-
m.created_at > CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END AND
|
|
272
|
+
m.created_at > coalesce(?,CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END) AND
|
|
273
273
|
(?=0 OR (m.sender_session_id IS NOT NULL AND m.sender_session_id!=?) OR (m.sender_session_id IS NULL AND m.sender_id!=g.name))
|
|
274
|
-
ORDER BY m.created_at,m.seq LIMIT ?`).all(sessionID, roomFilter, roomFilter, excludeSelf ? 1 : 0,
|
|
274
|
+
ORDER BY m.created_at,m.seq LIMIT ?`).all(sessionID, roomFilter, roomFilter, afterTs ?? null, excludeSelf ? 1 : 0,
|
|
275
275
|
excludeSelf ? 1 : 0, sessionID, take + 1) as Array<Record<string, string | number | null>>;
|
|
276
276
|
const hasMore = rows.length > take;
|
|
277
277
|
const items = rows.slice(0, take).map((row) => {
|
package/src/store.ts
CHANGED
|
@@ -28,8 +28,8 @@ export async function readState<T>(callback: (service: RoomService, registry: Re
|
|
|
28
28
|
export async function readUnreadMessages(roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false) {
|
|
29
29
|
return readUnreadPage(databasePath(), roomID, afterTs, limit, sessionID, senderName, newest);
|
|
30
30
|
}
|
|
31
|
-
export async function readInboxMessages(sessionID: string, roomID: string | null, excludeSelf: boolean, limit = 100) {
|
|
32
|
-
return sqliteInboxPage(databasePath(), sessionID, roomID, excludeSelf, limit);
|
|
31
|
+
export async function readInboxMessages(sessionID: string, roomID: string | null, excludeSelf: boolean, limit = 100, afterTs?: number) {
|
|
32
|
+
return sqliteInboxPage(databasePath(), sessionID, roomID, excludeSelf, limit, afterTs);
|
|
33
33
|
}
|
|
34
34
|
export async function readHistory(roomID: string, beforeSeq?: number, limit = 100, exclude?: { sessionID: string; name: string }): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
|
|
35
35
|
return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
|
package/src/v2-plugin.ts
CHANGED
|
@@ -21,6 +21,8 @@ export function createV2Setup(deps: {
|
|
|
21
21
|
execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string): Promise<string>;
|
|
22
22
|
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
23
23
|
poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
|
|
24
|
+
resolveOwner?: () => Promise<string | undefined>;
|
|
25
|
+
attachReceiver?: typeof attachV2Receiver;
|
|
24
26
|
}) {
|
|
25
27
|
return async (context: Plugin.Context): Promise<() => Promise<void>> => {
|
|
26
28
|
const sessions = new Set<string>();
|
|
@@ -50,8 +52,15 @@ export function createV2Setup(deps: {
|
|
|
50
52
|
sessions.add(input.sessionID);
|
|
51
53
|
await deps.run(runtime, () => deps.observe(runtime, input.sessionID));
|
|
52
54
|
});
|
|
53
|
-
contextRegistration = await context.session.hook("context", (input) => {
|
|
55
|
+
contextRegistration = await context.session.hook("context", async (input) => {
|
|
54
56
|
try {
|
|
57
|
+
if (!transport.receiverOwnerID) {
|
|
58
|
+
if (deps.resolveOwner) transport.receiverOwnerID = await deps.resolveOwner();
|
|
59
|
+
else if (version) {
|
|
60
|
+
const host = await discoverVerifiedHost(version).catch(() => undefined);
|
|
61
|
+
if (host) transport.receiverOwnerID = await receiverOwnerID(host.origin);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
55
64
|
if (transport.receiverOwnerID) observeReceiptContext(input.sessionID, input.messages,
|
|
56
65
|
receiptDestination(runtime.center.center), transport.receiverOwnerID);
|
|
57
66
|
} catch { /* Context evidence never fails model preparation. */ }
|
|
@@ -85,9 +94,13 @@ export function createV2Setup(deps: {
|
|
|
85
94
|
});
|
|
86
95
|
},
|
|
87
96
|
}));
|
|
88
|
-
|
|
97
|
+
const attachReceiver = deps.attachReceiver ?? attachV2Receiver;
|
|
98
|
+
releaseReceiver = attachReceiver({
|
|
89
99
|
sessions, version, transport, center: runtime.center,
|
|
90
|
-
poll: (ids, target, center) =>
|
|
100
|
+
poll: (ids, target, center) => {
|
|
101
|
+
if (target.receiverOwnerID) transport.receiverOwnerID = target.receiverOwnerID;
|
|
102
|
+
return deps.run(runtime, () => deps.poll(ids, target, center));
|
|
103
|
+
},
|
|
91
104
|
});
|
|
92
105
|
} catch (error) {
|
|
93
106
|
releaseReceiver?.();
|
package/src/v2-receiver.ts
CHANGED
|
@@ -64,7 +64,9 @@ export async function pollAttachmentsByCenter(
|
|
|
64
64
|
members: readonly Attachment[],
|
|
65
65
|
memberships: (attachment: Attachment) => Promise<Set<string>>,
|
|
66
66
|
restore: (owned: Set<string>, restored: Set<string>, attachment: Attachment) => Promise<void>,
|
|
67
|
+
ownerID?: string,
|
|
67
68
|
): Promise<void> {
|
|
69
|
+
if (ownerID) for (const member of members) if (attached.has(member)) member.transport.receiverOwnerID = ownerID;
|
|
68
70
|
await Promise.all([...groupByCenter(members).values()].map((group) => pollAttachmentGroup(group, memberships, restore)));
|
|
69
71
|
}
|
|
70
72
|
|
|
@@ -107,7 +109,7 @@ async function sweep(): Promise<void> {
|
|
|
107
109
|
? attachment.poll(ids, target, attachment.center) : Promise.resolve());
|
|
108
110
|
if (!owned.size) await flushReceiptCandidates({ destination: receiptDestination(attachment.center.center), receiverOwnerID: ownerID,
|
|
109
111
|
...(attachment.center.center ? { center: attachment.center.center, token: attachment.center.token } : {}) }).catch(() => {});
|
|
110
|
-
});
|
|
112
|
+
}, ownerID);
|
|
111
113
|
observedPolled = true;
|
|
112
114
|
} catch {
|
|
113
115
|
if (!observedPolled) await pollObserved(values, new Set()).catch(() => {});
|