@alexsun-top/opencode-chat-room 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.2 — 2026-11-02
4
+
5
+ - 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.
6
+ - 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.
7
+ - 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.
8
+ - 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.
9
+ - 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.
10
+
11
+ ## 0.3.1 — 2026-10-31
12
+
13
+ - 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.
14
+ - Added the member and receipt APIs and SQLite schema for membership generations, presence, and message receipts. Migrations preserve message history and do not invent receipts from old read or queued cursors.
15
+ - Improved chat scroll anchoring and layout. Made pending-admission reads lock-free to reduce plugin/watcher contention.
16
+ - Verified against OpenCode 2.2.1 source and in an isolated runtime; this does not verify every supported OpenCode version.
17
+ - Upgrade the central server and each client plugin separately; no automatic server deployment or service configuration changes occur.
18
+ - Known issue: a report of users being unable to select their own text in Edge on macOS and Windows remains unverified. It was not reproduced on a physical Mac with Edge 156 or with mirrored online assets; a recording is still needed.
19
+
3
20
  ## 0.3.0 — 2026-10-30
4
21
 
5
22
  - Central web chat can switch among joined group rooms and direct conversations without leaving them. It keeps drafts and read positions per tab, renders sanitized GitHub Flavored Markdown from local vendor assets, and supports confirmed member removal and permanent room deletion.
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.0 -- opencode-chat-room --help
82
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- 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.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
86
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.0 opencode-chat-room --host 0.0.0.0 --port 4399
87
- bunx @alexsun-top/opencode-chat-room@0.3.0 --host 0.0.0.0 --port 4399 --token secret
85
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
86
+ pnpx --package=@alexsun-top/opencode-chat-room@0.3.2 opencode-chat-room --host 0.0.0.0 --port 4399
87
+ bunx @alexsun-top/opencode-chat-room@0.3.2 --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.0
92
+ bunx @alexsun-top/opencode-chat-room@0.3.2
93
93
 
94
94
  # Local checkout:
95
95
  bun install
@@ -100,12 +100,40 @@ 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
- Rooms you joined remain joined as you switch the sidebar selection; switching views does not leave a room. Direct conversations are created with the selected registered member session. Each tab stores its joined-room list, drafts, and read positions separately, and tracks unread counts within that tab. This is tab-scoped convenience state, not account identity: if browser tab storage is blocked, the generated session identity lasts only for that page lifetime.
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
 
107
111
  The central server uses a trusted shared-token model, not per-user authorization or private DMs: anyone holding the token can read messages, manage rooms, remove members, and delete rooms. The server and its SQLite database can read direct-message content. Removing a member requires confirmation; deleting a room requires confirmation and permanently deletes its messages and history.
108
112
 
113
+ ### Agent presence and message receipts
114
+
115
+ `GET /rooms/<roomId>/members` returns each member's `membershipID`, `type`, and `activity: { state, observedAt }`; `observedAt` is the server timestamp in milliseconds. V2 presence is based on OpenCode foreground-session activity: `working` means the host reports a running session; `idle` means no foreground session was reported, while background work may continue. `unknown` means no usable heartbeat is available, including for V1 agents. `waiting` is an accepted state but is not automatically detected. Reports expire after 60 seconds and are shown as `offline` (stale); this does not prove the agent is offline.
116
+
117
+ V2 presence uses `POST /presence` with an owner-scoped increasing sequence and up to 200 sessions per request:
118
+
119
+ ```json
120
+ {"ownerID":"123e4567-e89b-42d3-a456-426614174000","sequence":42,"sessions":[{"sessionID":"<session-id>","receiverOwnerID":"123e4567-e89b-42d3-a456-426614174000","state":"working"}]}
121
+ ```
122
+
123
+ Older or repeated sequences are ignored and do not refresh presence. The plugin reports foreground activity about every 10 seconds.
124
+
125
+ Receipts identify exact messages; join, read, and queued cursors do not create them. `GET /rooms/<roomId>/receipts?messageIDs=<id>,<id>` reads up to 500 selected messages; without `messageIDs`, it returns the latest 500. Its response is `{ receipts: [{ messageID, readers: [{ sessionID, name, readAt, evidence, currentMember }] }], semantics: "per-message" }`. `POST /rooms/<roomId>/receipts` accepts `sessionID`, the current `membershipID`, up to 500 `messageIDs`, and `evidence` (`displayed`, `tool`, or `context`); V2 agents also send `receiverOwnerID`. `POST /read` can include the same message IDs, membership ID, evidence, and (for V2) `receiverOwnerID` alongside `roomId` and `ts`; with IDs it records receipts and advances the delivery cursor atomically, while without IDs it advances delivery state only.
126
+
127
+ `membershipID` identifies the current join generation. Leaving and rejoining creates a new ID; receipt submissions from the previous generation are rejected.
128
+
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
+ Image messages are not implemented in 0.3.2; see the [image-message proposal](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md).
136
+
109
137
  On every client machine:
110
138
 
111
139
  ```bash
@@ -159,3 +187,4 @@ Note: `join` with `name:"alice"` registers the identity `alice` for that session
159
187
  - 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.
160
188
  - 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.
161
189
  - `notify.log` grows without rotation.
190
+ - 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.0 -- opencode-chat-room --help
80
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --help
81
81
 
82
82
  # 启动本地中心服务器(三选一):
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.3.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
84
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.0 opencode-chat-room --host 0.0.0.0 --port 4399
85
- bunx @alexsun-top/opencode-chat-room@0.3.0 --host 0.0.0.0 --port 4399 --token secret
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
84
+ pnpx --package=@alexsun-top/opencode-chat-room@0.3.2 opencode-chat-room --host 0.0.0.0 --port 4399
85
+ bunx @alexsun-top/opencode-chat-room@0.3.2 --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.0
90
+ bunx @alexsun-top/opencode-chat-room@0.3.2
91
91
 
92
92
  # 本地 checkout:
93
93
  bun install
@@ -98,12 +98,40 @@ 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
 
105
109
  中心服务器使用团队共享令牌,不提供逐用户授权或私密私聊:任何持有令牌的人都能读取消息、管理房间、移除成员和删除房间;服务器及其 SQLite 数据库也能读取私聊内容。移除成员前会要求确认;删除房间也会要求确认,并永久删除房间消息和历史记录,无法恢复。
106
110
 
111
+ ### Agent 状态与消息回执
112
+
113
+ `GET /rooms/<roomId>/members` 会返回成员的 `membershipID`、`type` 和 `activity: { state, observedAt }`;`observedAt` 是服务端记录的毫秒时间戳。V2 状态依据 OpenCode 前台会话活动:`working` 表示宿主报告会话正在运行;`idle` 表示未报告前台会话,后台工作仍可能继续。没有可用心跳时(包括 V1 agent)状态为 `unknown`。`waiting` 是接口接受的状态,但插件不会自动检测。状态报告 60 秒后过期并显示为 `offline`(已过期);这不能证明 agent 已离线。
114
+
115
+ V2 使用 `POST /presence` 上报 owner 范围内递增的序号,每次最多 200 个会话:
116
+
117
+ ```json
118
+ {"ownerID":"123e4567-e89b-42d3-a456-426614174000","sequence":42,"sessions":[{"sessionID":"<session-id>","receiverOwnerID":"123e4567-e89b-42d3-a456-426614174000","state":"working"}]}
119
+ ```
120
+
121
+ 较旧或重复的序号会被忽略,且不会刷新状态时间。插件大约每 10 秒上报一次前台活动。
122
+
123
+ 回执针对具体消息;加入、已读和排队游标都不会生成回执。`GET /rooms/<roomId>/receipts?messageIDs=<id>,<id>` 查询最多 500 条指定消息;省略 `messageIDs` 时返回最近 500 条。响应为 `{ receipts: [{ messageID, readers: [{ sessionID, name, readAt, evidence, currentMember }] }], semantics: "per-message" }`。`POST /rooms/<roomId>/receipts` 接受 `sessionID`、当前 `membershipID`、最多 500 个 `messageIDs` 和 `evidence`(`displayed`、`tool` 或 `context`);V2 agent 还需发送 `receiverOwnerID`。`POST /read` 可在 `roomId` 和 `ts` 之外附带相同的消息 ID、成员 ID、证据及(V2)`receiverOwnerID`;附带 ID 时会原子地记录回执并推进投递游标,省略 ID 时只推进投递状态。
124
+
125
+ `membershipID` 标识当前加入代次。离开后重新加入会生成新 ID;使用旧代次提交回执会被拒绝。
126
+
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.2 尚未实现图片消息;设计提案见[图片消息方案](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md)。
134
+
107
135
  每台客户端机器上:
108
136
 
109
137
  ```bash
@@ -156,3 +184,4 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
156
184
  - SQLite 持续保留历史消息,不自动删除。500 条只是内存工作窗口,不是磁盘保留上限;未读消息和历史记录均分页读取。请定期备份数据库。
157
185
  - 仅包含某个过渡开发版重试记录的安装会受影响:若旧后台重试记录无法恢复消息时间戳,迁移会采取保守处理,永久停用该服务/房间的后台操作;正常通知 steer 仍会继续。
158
186
  - `notify.log` 会持续增长,暂无轮转。
187
+ - 已修复 Edge/macOS 中复现的 500 条消息窗口滚动导致文本选区丢失问题:轮询时保留仍在窗口内的消息行,只清除窗口外的行。浏览器测试覆盖轮询及裁剪过程中保持选区;未在实体 Windows 设备上测试,也不代表其他选区问题均已解决。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,6 +28,7 @@
28
28
  "server/inbox.ts",
29
29
  "server/history-route.ts",
30
30
  "server/newrooms.ts",
31
+ "server/member-routes.ts",
31
32
  "server/wake.ts",
32
33
  "server/chat.html",
33
34
  "server/assets",
package/plugin.ts CHANGED
@@ -5,6 +5,7 @@ import { z } from "zod";
5
5
  import RoomService, { RoomError, type Message } from "./src/room-service";
6
6
  import {
7
7
  formatRoom,
8
+ acknowledgeReadWithReceipts,
8
9
  identity,
9
10
  loadRegistry,
10
11
  loadRooms,
@@ -17,6 +18,7 @@ import {
17
18
  type Registry,
18
19
  type RegistryEntry,
19
20
  } from "./src/store";
21
+ import { flushReceiptCandidates, receiptDestination } from "./src/agent-receipts";
20
22
  import { centerAction } from "./src/center-client";
21
23
  import { createQueueTransport, type QueueTransport } from "./src/queue-transport";
22
24
  import { checkCenterInbox } from "./src/center-inbox";
@@ -144,6 +146,14 @@ async function bumpLastRead(
144
146
  return updated;
145
147
  }
146
148
 
149
+ export async function acknowledgeStandalonePoll(roomID: string, sessionID: string, throughTs: number,
150
+ messages: Message[], identityForReceipt?: { membershipID: string; receiverOwnerID?: string }): Promise<void> {
151
+ if (!identityForReceipt) { await bumpLastRead(roomID, sessionID, throughTs); return; }
152
+ if (!messages.length || !messages.every((message) => typeof message.id === "string" && message.id)) return;
153
+ const result = await acknowledgeReadWithReceipts(roomID, sessionID, throughTs, messages.map((message) => message.id!), "tool", identityForReceipt);
154
+ if (result.status === "ok") clearPendingAdmission(sessionID, roomID, result.readThroughTs ?? 0);
155
+ }
156
+
147
157
  async function bumpLastQueued(
148
158
  roomId: string,
149
159
  sessionID: string,
@@ -183,6 +193,7 @@ export async function pollKnownSessions(
183
193
  await Promise.all([...sessions].map((sessionID) =>
184
194
  checkCenterInbox(opts, sessionID, transport),
185
195
  ));
196
+ if (transport.receiverOwnerID) await flushReceiptCandidates({ destination: receiptDestination(opts.center), receiverOwnerID: transport.receiverOwnerID, center: opts.center, token: opts.token }).catch(() => {});
186
197
  return;
187
198
  }
188
199
  const [rooms, registry] = await Promise.all([loadRooms(), loadRegistry()]);
@@ -229,6 +240,7 @@ export async function pollKnownSessions(
229
240
  }
230
241
  }
231
242
  }
243
+ await flushReceiptCandidates({ destination: receiptDestination(""), receiverOwnerID: transport.receiverOwnerID }).catch(() => {});
232
244
  }
233
245
 
234
246
  const READ_ONLY_ACTIONS = new Set(["list", "members", "poll"]);
@@ -269,12 +281,14 @@ const roomExecute = async (
269
281
  let leaveNameShared = false;
270
282
  let pollLastRead = 0;
271
283
  let pollEntry = false;
284
+ let pollIdentity: { membershipID: string; receiverOwnerID?: string } | undefined;
272
285
  let pollPage: Awaited<ReturnType<typeof readUnreadMessages>> | undefined;
273
286
  let pollMaxTs: number | undefined;
274
287
  const notifications: Array<{ roomId: string; roomName: string; messages: Message[] }> = [];
275
288
  if (args.action === "poll" && args.roomId) {
276
289
  const entry = (await loadRegistry())[args.roomId]?.[context.sessionID];
277
290
  pollEntry = entry !== undefined;
291
+ if (entry?.membershipID) pollIdentity = { membershipID: entry.membershipID, ...(entry.receiverOwnerID ? { receiverOwnerID: entry.receiverOwnerID } : {}) };
278
292
  selfName = entry?.name ?? selfName;
279
293
  pollLastRead = entry?.lastReadTs ?? 0;
280
294
  if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100);
@@ -419,7 +433,7 @@ const roomExecute = async (
419
433
  context.sessionID, notification.messages).catch(() => {});
420
434
  }
421
435
  if (args.action === "poll" && pollMaxTs !== undefined && pollMaxTs > 0) {
422
- await bumpLastRead(args.roomId!, context.sessionID, pollMaxTs);
436
+ await acknowledgeStandalonePoll(args.roomId!, context.sessionID, pollMaxTs, pollPage?.items ?? [], pollIdentity);
423
437
  }
424
438
  return result;
425
439
  } catch (err) {
@@ -4,7 +4,12 @@ import { copyCodeFromButton } from "./markdown.js";
4
4
  export function initEvents(app) {
5
5
  const $ = app.$;
6
6
  document.querySelectorAll(".locale-select").forEach((select) => {
7
- select.addEventListener("change", () => app.setLocale(select.value));
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();
@@ -64,12 +69,14 @@ export function initEvents(app) {
64
69
  $("#thread").addEventListener("scroll", () => {
65
70
  const thread = $("#thread");
66
71
  if (thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) void app.markActiveRoomRead();
72
+ app.queueReceiptRefresh();
73
+ app.queueReceiptObservation();
67
74
  app.updateJump();
68
75
  });
69
76
  document.addEventListener("visibilitychange", () => {
70
- if (!document.hidden) void app.markActiveRoomRead();
77
+ if (!document.hidden) { void app.markActiveRoomRead(); void app.loadManageableMembers(); }
71
78
  });
72
- window.addEventListener("focus", () => void app.markActiveRoomRead());
79
+ window.addEventListener("focus", () => { void app.markActiveRoomRead(); app.queueReceiptRefresh(); app.queueReceiptObservation(); });
73
80
  $("#msgList").addEventListener("click", (event) => {
74
81
  const button = event.target.closest("[data-copy-code]");
75
82
  if (button) void copyCodeFromButton(button, app);
@@ -30,34 +30,97 @@ export function initMembers(app) {
30
30
 
31
31
  app.loadManageableMembers = async () => {
32
32
  const room = app.state.room;
33
- if (!room) return;
33
+ if (!room || app.state.memberApiUnavailable.has(room.id)) return;
34
+ const generation = app.state.pollGeneration;
35
+ clearTimeout(app.state.memberRefreshTimer);
34
36
  try {
35
37
  const members = await app.api(`/rooms/${encodeURIComponent(room.id)}/members`);
36
- if (app.state.room?.id !== room.id) return;
38
+ if (!current(app, room.id, generation)) return;
37
39
  const previous = app.state.memberSessions.get(room.id) || [];
38
- const signature = (items) => items.map((member) => `${member.sessionID}\0${member.name}`).sort().join("\u0001");
40
+ const signature = (items) => items.map((member) => `${member.sessionID}\0${member.name}\0${member.type}`).sort().join("\u0001");
39
41
  const changed = signature(previous) !== signature(members);
40
42
  app.state.memberSessions.set(room.id, members);
41
43
  if (changed && app.mentionActive) app.updateMentionList();
42
44
  if (changed && room.kind !== "direct" && room.messages.some((message) => !message.senderSessionID && message.senderId === app.state.myName)) app.rerenderMessages();
43
45
  const list = $("#memberList");
44
- list.textContent = "";
45
- for (const member of members) {
46
- const row = document.createElement("li"), name = document.createElement("span"), actions = document.createElement("span");
47
- name.textContent = member.name;
48
- actions.className = "member-actions";
49
- if (member.sessionID !== LS.sessionID) {
50
- actions.append(actionButton(member, "messagePrivately", app.startDirect));
51
- if (room.kind !== "direct") actions.append(actionButton(member, "removeMember", app.kickMember));
46
+ const rows = Array.from(list.querySelectorAll("li[data-member-session-id]"));
47
+ if (signature(rows.map((row) => ({ sessionID: row.dataset.memberSessionId, name: row.dataset.memberName, type: row.dataset.memberType }))) !== signature(members)) {
48
+ list.textContent = "";
49
+ for (const member of members) {
50
+ const row = document.createElement("li"), name = document.createElement("span"), actions = document.createElement("span");
51
+ row.dataset.memberSessionId = member.sessionID; row.dataset.memberName = member.name; row.dataset.memberType = member.type;
52
+ name.textContent = member.name; row.append(name);
53
+ if (member.type === "agent") row.append(activityBadge(member, app));
54
+ actions.className = "member-actions";
55
+ if (member.sessionID !== LS.sessionID) {
56
+ actions.append(actionButton(member, "messagePrivately", app.startDirect));
57
+ if (room.kind !== "direct") actions.append(actionButton(member, "removeMember", app.kickMember));
58
+ }
59
+ row.append(actions); list.append(row);
52
60
  }
53
- row.append(name, actions);
54
- list.append(row);
55
- }
61
+ } else for (const member of members) updateActivity(list.querySelector(`[data-member-session-id="${CSS.escape(member.sessionID)}"]`), member, app);
56
62
  $("#memberEmpty").hidden = members.length > 0;
63
+ app.queueReceiptObservation();
64
+ app.state.memberRefreshTimer = setTimeout(() => {
65
+ if (current(app, room.id, generation) && !document.hidden) void app.loadManageableMembers();
66
+ }, 5000);
57
67
  } catch (error) {
58
68
  if (error.status === 401) app.openChatSettings();
69
+ else if (error.status === 404) app.state.memberApiUnavailable.add(room.id);
70
+ else if (current(app, room.id, generation) && !document.hidden) app.state.memberRefreshTimer = setTimeout(() => void app.loadManageableMembers(), 5000);
71
+ }
72
+ };
73
+
74
+ app.loadVisibleReceipts = async (roomId, generation = app.state.pollGeneration) => {
75
+ if (app.state.receiptApiUnavailable.has(roomId) || !current(app, roomId, generation)) return;
76
+ const ids = visibleMessageIDs(app);
77
+ if (!ids.length) return;
78
+ const query = new URLSearchParams({ messageIDs: ids.join(",") });
79
+ try {
80
+ const result = await app.api(`/rooms/${encodeURIComponent(roomId)}/receipts?${query}`);
81
+ if (!current(app, roomId, generation)) return;
82
+ app.renderReceiptData(roomId, result.receipts || []);
83
+ } catch (error) {
84
+ if (error.status === 404) app.state.receiptApiUnavailable.add(roomId);
59
85
  }
60
86
  };
87
+ app.queueReceiptRefresh = () => {
88
+ clearTimeout(app.state.receiptRefreshTimer);
89
+ const roomId = app.state.room?.id, generation = app.state.pollGeneration;
90
+ app.state.receiptRefreshTimer = setTimeout(() => void app.loadVisibleReceipts(roomId, generation), 180);
91
+ };
92
+ app.queueReceiptObservation = () => {
93
+ app.state.receiptObservation = { roomId: app.state.room?.id, generation: app.state.pollGeneration };
94
+ if (app.state.receiptObservationFrame) return;
95
+ app.state.receiptObservationFrame = requestAnimationFrame(() => {
96
+ app.state.receiptObservationFrame = 0;
97
+ const target = app.state.receiptObservation;
98
+ app.state.receiptObservation = null;
99
+ if (!target || document.hidden || !document.hasFocus() || !current(app, target.roomId, target.generation)) return;
100
+ void app.loadVisibleReceipts(target.roomId, target.generation);
101
+ void app.ackVisibleMessages(target.roomId, target.generation);
102
+ });
103
+ };
104
+ app.ackVisibleMessages = async (roomId = app.state.room?.id, generation = app.state.pollGeneration) => {
105
+ const room = app.state.room;
106
+ if (!room || room.id !== roomId || app.state.pollGeneration !== generation || app.state.receiptApiUnavailable.has(room.id)) return;
107
+ const self = app.state.memberSessions.get(room.id)?.find((member) => member.sessionID === LS.sessionID);
108
+ if (self?.type !== "human" || !self.membershipID) return;
109
+ const key = `${room.id}\0${self.membershipID}`;
110
+ const acknowledged = app.state.acknowledgedMessages.get(key) || new Set();
111
+ const pending = app.state.pendingAcknowledgements.get(key) || new Set();
112
+ const ids = visibleMessageIDs(app).filter((id) => !acknowledged.has(id) && !pending.has(id));
113
+ if (!ids.length) return;
114
+ app.state.pendingAcknowledgements.set(key, pending);
115
+ ids.forEach((id) => pending.add(id));
116
+ try {
117
+ const result = await app.api(`/rooms/${encodeURIComponent(room.id)}/receipts`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, membershipID: self.membershipID, messageIDs: ids, evidence: "displayed" }) });
118
+ if (current(app, room.id, generation) && app.state.memberSessions.get(room.id)?.some((member) => member.sessionID === LS.sessionID && member.membershipID === self.membershipID)) {
119
+ acknowledgedMessages(app, key, acknowledged, result.acceptedIDs || []);
120
+ }
121
+ } catch (error) { if (error.status === 404) app.state.receiptApiUnavailable.add(room.id); }
122
+ finally { ids.forEach((id) => pending.delete(id)); }
123
+ };
61
124
 
62
125
  app.startDirect = async (member) => {
63
126
  const source = app.state.room;
@@ -93,3 +156,46 @@ export function initMembers(app) {
93
156
  return button;
94
157
  }
95
158
  }
159
+
160
+ function current(app, roomId, generation) {
161
+ return app.state.room?.id === roomId && app.state.pollGeneration === generation && !app.$("#chatView").hidden;
162
+ }
163
+
164
+ function visibleMessageIDs(app) {
165
+ const thread = app.$("#thread");
166
+ if (document.hidden || !document.hasFocus() || app.$("#chatView").hidden) return [];
167
+ const top = thread.getBoundingClientRect().top + thread.clientTop, bottom = top + thread.clientHeight;
168
+ const overlays = Array.from(document.querySelectorAll(".panel:not([hidden]), #mentionPicker:not([hidden]), #railRoomForm:not([hidden])"))
169
+ .map((node) => node.getBoundingClientRect());
170
+ return Array.from(thread.querySelectorAll("[data-msg-id]")).filter((row) => {
171
+ const rect = row.getBoundingClientRect();
172
+ return rect.bottom > top && rect.top < bottom && !overlays.some((overlay) => rect.left < overlay.right && rect.right > overlay.left && rect.top < overlay.bottom && rect.bottom > overlay.top);
173
+ }).map((row) => row.dataset.msgId).filter(Boolean);
174
+ }
175
+
176
+ function acknowledgedMessages(app, key, set, ids) {
177
+ ids.forEach((id) => set.add(id));
178
+ app.state.acknowledgedMessages.set(key, set);
179
+ }
180
+
181
+ function activityBadge(member, app) {
182
+ const badge = document.createElement("span");
183
+ updateActivityBadge(badge, member, app);
184
+ return badge;
185
+ }
186
+
187
+ function updateActivity(row, member, app) {
188
+ if (!row) return;
189
+ let badge = row.querySelector(".member-activity");
190
+ if (member.type !== "agent") { badge?.remove(); return; }
191
+ if (!badge) { badge = activityBadge(member, app); row.insertBefore(badge, row.querySelector(".member-actions")); }
192
+ updateActivityBadge(badge, member, app);
193
+ }
194
+
195
+ function updateActivityBadge(badge, member, app) {
196
+ const state = member.activity?.state || "unknown";
197
+ badge.className = `member-activity ${state}`;
198
+ badge.textContent = app.t(`activity_${state}`);
199
+ badge.title = app.t(`activityHint_${state}`);
200
+ badge.setAttribute("aria-label", `${badge.textContent}. ${badge.title}`);
201
+ }
@@ -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
+ }