@alexsun-top/opencode-chat-room 0.3.1 → 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,13 @@
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
+
3
11
  ## 0.3.1 — 2026-10-31
4
12
 
5
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.
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.1 -- 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.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
86
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.1 opencode-chat-room --host 0.0.0.0 --port 4399
87
- bunx @alexsun-top/opencode-chat-room@0.3.1 --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.1
92
+ bunx @alexsun-top/opencode-chat-room@0.3.2
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
- 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
 
@@ -122,9 +126,13 @@ 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.
126
134
 
127
- Upgrade the central server and every client plugin separately; updating only a local plugin does not deploy the server APIs. The package does not automatically deploy or reconfigure the server service.
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).
128
136
 
129
137
  On every client machine:
130
138
 
@@ -179,4 +187,4 @@ Note: `join` with `name:"alice"` registers the identity `alice` for that session
179
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.
180
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.
181
189
  - `notify.log` grows without rotation.
182
- - 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.
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.1 -- 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.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
84
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.1 opencode-chat-room --host 0.0.0.0 --port 4399
85
- bunx @alexsun-top/opencode-chat-room@0.3.1 --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.1
90
+ bunx @alexsun-top/opencode-chat-room@0.3.2
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,13 @@ V2 使用 `POST /presence` 上报 owner 范围内递增的序号,每次最多
120
124
 
121
125
  `membershipID` 标识当前加入代次。离开后重新加入会生成新 ID;使用旧代次提交回执会被拒绝。
122
126
 
123
- `displayed` 表示消息出现在当前聚焦浏览器标签页的可视区域。`tool` 表示房间轮询已获取完整消息;V1 仅在显式轮询时产生此类回执。`context` 表示完整消息进入了 agent 的主要上下文准备阶段,不代表 agent 已理解。被截为 300 字符的推送预览不算完整消息证据;需轮询完整消息才能记录回执。成员离开后回执仍保留,并标记其已不是当前成员。这些接口使用中心服务器的共享令牌权限,不提供逐用户访问控制。
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。
124
132
 
125
- 需分别升级中心服务器和每台客户端的插件;只更新本地插件不会部署服务端 API。此包不会自动部署或重新配置服务器服务。
133
+ 0.3.2 尚未实现图片消息;设计提案见[图片消息方案](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md)。
126
134
 
127
135
  每台客户端机器上:
128
136
 
@@ -176,4 +184,4 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
176
184
  - SQLite 持续保留历史消息,不自动删除。500 条只是内存工作窗口,不是磁盘保留上限;未读消息和历史记录均分页读取。请定期备份数据库。
177
185
  - 仅包含某个过渡开发版重试记录的安装会受影响:若旧后台重试记录无法恢复消息时间戳,迁移会采取保守处理,永久停用该服务/房间的后台操作;正常通知 steer 仍会继续。
178
186
  - `notify.log` 会持续增长,暂无轮转。
179
- - 已知问题:有用户报告在 macOS 和 Windows 的 Edge 中无法选中自己的消息文本,但问题尚未复现。在实际 Mac 的 Edge 156 和镜像在线资源中均未复现;仍需用户提供录屏。
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.1",
3
+ "version": "0.3.2",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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();
@@ -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) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
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 = systemMessage(message.text, app);
125
+ text.textContent = formatSystemMessage(message, app);
124
126
  row.append(text);
125
127
  } else {
126
128
  const direct = app.state.room.kind === "direct";
@@ -168,22 +170,21 @@ export function initMessages(app) {
168
170
  app.renderMessages = (live = false) => {
169
171
  const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
170
172
  const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
171
- let last = list.lastElementChild, skipped = 0;
173
+ let skipped = 0;
172
174
  let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
173
- let renderedIds = new Set([...list.children].map((node) => node.dataset.msgId).filter(Boolean));
174
175
  const viewport = thread.getBoundingClientRect();
175
176
  const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
176
177
  anchorId = firstVisible?.dataset.msgId || null;
177
178
  anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
178
- if (messages.length && app.firstMessageId && messages[0].id !== app.firstMessageId) {
179
- list.textContent = "";
180
- app.rendered = 0;
181
- last = null;
182
- renderedIds = new Set();
183
- }
184
- for (let index = app.rendered; index < messages.length; index++) {
179
+ pruneMessageRows(list, messages);
180
+ let last = list.lastElementChild;
181
+ const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
182
+ let startIndex = 0;
183
+ const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
184
+ if (lastId) for (let index = messages.length - 1; index >= 0; index--) if (messages[index].id === lastId) { startIndex = index + 1; break; }
185
+ for (let index = startIndex; index < messages.length; index++) {
185
186
  const message = messages[index];
186
- if (renderedIds.has(message.id)) continue;
187
+ if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id)) continue;
187
188
  try {
188
189
  const day = new Date(message.createdAt).toDateString();
189
190
  if (!last || last.dataset.day !== day) {
@@ -277,7 +278,7 @@ export function initMessages(app) {
277
278
  if (entry) {
278
279
  entry.room = updated;
279
280
  const latest = updated.messages.at(-1);
280
- if (latest) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
281
+ if (latest) setRoomPreview(entry, latest);
281
282
  }
282
283
  app.renderMessages(true);
283
284
  $("#thread").scrollTop = $("#thread").scrollHeight;
@@ -334,15 +335,16 @@ export function initMessages(app) {
334
335
  const roomId = app.state.room?.id;
335
336
  if (!roomId || !isCurrentPoll(roomId, generation)) return;
336
337
  try {
337
- const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, excludeSelf: "0", timeout: "25000" });
338
+ const entry = app.state.rooms.get(roomId);
339
+ const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, excludeSelf: "0", timeout: "25000", afterTs: String(entry?.receivedTs || 0) });
338
340
  const data = await app.api(`/inbox?${query}`, { signal });
339
341
  if (!isCurrentPoll(roomId, generation)) return;
340
- if (!data.member) {
342
+ if (data.member === false) {
341
343
  void app.removeJoinedRoom(roomId, { reason: true });
342
344
  return;
343
345
  }
344
- const items = Array.isArray(data.items) ? data.items : [];
345
- const entry = app.state.rooms.get(roomId), messages = app.state.room.messages;
346
+ if (data.member !== true || !Array.isArray(data.items)) return;
347
+ const items = data.items, previousReceivedTs = entry?.receivedTs || 0, messages = app.state.room.messages;
346
348
  const known = new Set(messages.map((message) => message.id));
347
349
  let sawSystem = false, added = 0;
348
350
  for (const item of items) {
@@ -351,9 +353,10 @@ export function initMessages(app) {
351
353
  messages.push({ ...item, roomId });
352
354
  known.add(item.id);
353
355
  entry?.unreadIds.set(item.id, item);
354
- if (entry && item.createdAt >= entry.previewAt) { entry.preview = item.text; entry.previewAt = item.createdAt; }
356
+ if (entry && item.createdAt >= entry.previewAt) setRoomPreview(entry, item);
355
357
  added++;
356
358
  }
359
+ if (entry) entry.receivedTs = items.reduce((latest, item) => Number.isSafeInteger(item.createdAt) ? Math.max(latest, item.createdAt) : latest, previousReceivedTs);
357
360
  if (entry) entry.unreadOverflow = Boolean(data.hasMore);
358
361
  if (messages.length > 500) messages.splice(0, messages.length - 500);
359
362
  const rendered = app.renderMessages(true);
@@ -373,7 +376,7 @@ export function initMessages(app) {
373
376
  void app.reconcileRoom(roomId, generation);
374
377
  }
375
378
  app.setOnline(true);
376
- pollDelay = 2000;
379
+ pollDelay = data.hasMore && (entry?.receivedTs || 0) > previousReceivedTs ? 0 : 2000;
377
380
  } catch (error) {
378
381
  if (!isCurrentPoll(roomId, generation)) return;
379
382
  if (error.status === 401) {
@@ -434,7 +437,7 @@ export function initMessages(app) {
434
437
  }
435
438
 
436
439
  function trimMessages(list, app) {
437
- if (list.children.length <= 400) return;
440
+ if (list.children.length <= 400 || hasMessageSelection(list)) return;
438
441
  while (list.children.length > 300) list.removeChild(list.firstChild);
439
442
  if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
440
443
  const gap = document.createElement("li");
@@ -480,10 +483,4 @@ function updateReceiptDetails(row, message, app) {
480
483
  }
481
484
  }
482
485
 
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
486
  }
@@ -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 entry = app.state.rooms.get(room.id) || { unreadIds: new Map(), unreadOverflow: false, preview: "", previewAt: 0, position: 0, readTs: 0 };
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
- entry.preview ||= room.messages.at(-1)?.text || "";
43
- entry.previewAt ||= room.messages.at(-1)?.createdAt || 0;
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 { /* Missing or inaccessible rooms are removed without rejoining them. */ }
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 = true;
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 { /* A direct room can be deleted while the sidebar refreshes. */ }
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
- const lastMessage = entry?.preview || room.messages.at(-1)?.text || "";
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) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
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 (!result.member) { await app.removeJoinedRoom(roomId, { reason: false }); return; }
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.preview = message.text;
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) { entry.preview = newest.text; entry.previewAt = newest.createdAt; }
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 memorySessionID = "";
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
- if (memorySessionID) return memorySessionID;
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 readSession("chat.name") || read("chat.name") || ""; },
79
- set name(value) { writeSession("chat.name", value || null); write("chat.name", null); },
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,7 @@ 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
+ identityChanged: "This browser identity changed in another tab. Reload this tab before continuing.",
152
208
  networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
153
209
  roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
154
210
  networkRetry: "Unable to connect to the server. Check your network and try again.",
@@ -165,7 +221,7 @@ const messages = {
165
221
  deleteRoom: "Delete room", deleteConfirm: ({ name }) => `Delete “${name}” and all its messages? This cannot be undone.`,
166
222
  allMembers: "Everyone", messageCount: ({ count }) => `${count} / 2000`,
167
223
  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`,
224
+ systemJoined: ({ name }) => `${name} joined the room`, systemLeft: ({ name }) => `${name} left the room`, systemRemoved: ({ name }) => `${name} was removed from the room`,
169
225
  activity_working: "Working", activity_idle: "Foreground idle", activity_waiting: "Waiting", activity_unknown: "Status unknown", activity_offline: "Status stale",
170
226
  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
227
  receiptCount: ({ count }) => `Read by ${count}`, departedMember: "left",
@@ -192,6 +248,7 @@ const messages = {
192
248
  today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", you: "我", saved: "已保存",
193
249
  savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
194
250
  copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
251
+ identityChanged: "此浏览器身份已在另一个标签页中更改,请重新加载此标签页后继续。",
195
252
  networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
196
253
  roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
197
254
  networkRetry: "无法连接服务器,请检查网络后重试", joinFailed: ({ message }) => `加入失败:${message}`,
@@ -205,7 +262,7 @@ const messages = {
205
262
  deleteRoom: "删除房间", deleteConfirm: ({ name }) => `删除“${name}”及全部聊天记录?此操作无法撤销。`,
206
263
  allMembers: "所有人", messageCount: ({ count }) => `${count} / 2000`,
207
264
  privacyNote: "持有共享令牌的人都可以读取私聊内容和管理房间;服务器也可以读取私聊内容。",
208
- systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`,
265
+ systemJoined: ({ name }) => `${name} 加入了房间`, systemLeft: ({ name }) => `${name} 离开了房间`, systemRemoved: ({ name }) => `${name} 被移出了房间`,
209
266
  activity_working: "工作中", activity_idle: "前台空闲", activity_waiting: "等待中", activity_unknown: "状态未知", activity_offline: "状态已过期",
210
267
  activityHint_working: "Agent 正在报告工作状态。", activityHint_idle: "前台空闲;后台任务仍可能继续。", activityHint_waiting: "Agent 正在报告等待状态。", activityHint_unknown: "暂无活动状态报告。", activityHint_offline: "最近的状态已过期;这不能证明 Agent 已离线。",
211
268
  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
+ }
@@ -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 read((svc) => svc.listRooms().filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller)));
149
- return json(rooms.map(serializeRoom));
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
  }
@@ -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
- releaseReceiver = attachV2Receiver({
97
+ const attachReceiver = deps.attachReceiver ?? attachV2Receiver;
98
+ releaseReceiver = attachReceiver({
89
99
  sessions, version, transport, center: runtime.center,
90
- poll: (ids, target, center) => deps.run(runtime, () => deps.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?.();
@@ -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(() => {});