@alexsun-top/opencode-chat-room 0.5.3 → 0.5.5

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +13 -1
  3. package/README.zh-CN.md +13 -1
  4. package/docs/administrator-rooms.md +6 -8
  5. package/package.json +2 -1
  6. package/server/admin-auth.ts +4 -2
  7. package/server/assets/base.css +5 -1
  8. package/server/assets/chat/admin.js +4 -9
  9. package/server/assets/chat/announcements.js +17 -1
  10. package/server/assets/chat/attachments.js +4 -1
  11. package/server/assets/chat/editor.js +15 -2
  12. package/server/assets/chat/events.js +25 -7
  13. package/server/assets/chat/markdown.js +31 -11
  14. package/server/assets/chat/mentions.js +3 -1
  15. package/server/assets/chat/messages.js +96 -32
  16. package/server/assets/chat/questions.js +12 -6
  17. package/server/assets/chat/reminders.js +4 -4
  18. package/server/assets/chat/replies.js +1 -5
  19. package/server/assets/chat/room-watcher.js +12 -4
  20. package/server/assets/chat/rooms.js +17 -6
  21. package/server/assets/chat/state.js +8 -7
  22. package/server/assets/chat/system-messages.js +2 -1
  23. package/server/assets/conversation.css +1 -3
  24. package/server/chat-server.ts +39 -38
  25. package/server/chat.html +2 -3
  26. package/server/json-body.ts +8 -0
  27. package/server/member-routes.ts +9 -11
  28. package/server/wake.ts +11 -2
  29. package/skills/chatroom/SKILL.md +5 -2
  30. package/src/admin-client.ts +3 -3
  31. package/src/agent-receipts.ts +3 -3
  32. package/src/center-inbox.ts +2 -2
  33. package/src/plugin-notifications.ts +6 -3
  34. package/src/resources.ts +4 -1
  35. package/src/sqlite-state.ts +56 -5
  36. package/src/store.ts +11 -4
  37. package/src/v2-plugin.ts +17 -0
  38. package/src/supervision-inbox.ts +0 -50
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.5 — 2026-11-13
4
+
5
+ - Clear own messages and entries older than the read watermark from the unread set, so a badge can no longer stick.
6
+ - Reopen a room at its first unread when the previous visit ended at the bottom; a deliberate scroll position is restored exactly.
7
+ - Show `<at>@name</at>` as `@name` in system rows, room previews, reminder text and notifications, and keep receipt verification aligned.
8
+ - Retry host discovery until the receiver owner resolves instead of staying silent after a slow start.
9
+ - Remove the composer's "Send as a question" toggle. Agents still ask questions through the room tool, and answering them in the room works as before.
10
+ - Clear a question from unread as soon as its answer arrives, even while the room is open.
11
+ - Keep a replied-to message as the saved position instead of jumping to unread on the next open.
12
+ - Show the unread total for all rooms in the browser tab title.
13
+ - Publish a `ghcr.io` container image with every release, so self-hosting no longer needs a local build.
14
+ - Start from a state directory owned by another user, such as a mounted container volume, instead of failing to tighten its permissions.
15
+ - Create the state database file with owner-only permissions from the start, and warn if they cannot be tightened, so chat history is not briefly readable by other users on the host.
16
+ - Show the running version next to the app title.
17
+ - Ship `server/json-body.ts`; 0.5.4 omitted it, so the published standalone server could not start.
18
+ - Start a new tab from the read watermark the server stores for that session, so messages read before the tab opened do not appear as read.
19
+ - Join and leave notices no longer raise unread badges.
20
+ - Show the jump-to-latest button whenever the room is far enough down to count as unread.
21
+ - Stop a position that could not be restored from blocking every later scroll position for that room.
22
+ - Sending from inside the history no longer jumps to the newest message or advances the read watermark.
23
+ - Keep messages whose row failed to render unread instead of advancing the watermark past them.
24
+ - Return the text of a reply to an already answered question to the draft instead of queueing an answer that can never succeed.
25
+ - Log every failed notification delivery with its room and session id.
26
+ - Run a scheduled plan when its reminder fires, without asking for the schedule to be confirmed again.
27
+
28
+ ## 0.5.4 — 2026-11-11
29
+
30
+ - Keep unanswered questions unread, including when they are answered from another room, and stop own messages from raising unread counts. The sidebar badge now clears once the conversation is read.
31
+ - Fix the first character being dropped when typing with an IME, and keep the caret stable after inserting a mention.
32
+ - Merge a send response with the polling result so a stale snapshot no longer erases newer messages.
33
+ - Make timestamps increase monotonically inside the write transaction and resume long polling from the exact cursor.
34
+ - Write sends, read acknowledgements, and queued watermarks directly instead of rewriting the whole state file.
35
+ - Keep per-room drafts, including mentions, and restore them after a reload.
36
+ - Show the next run only for recurring reminders; one-shot reminders show just their trigger time.
37
+ - Preview attachments you sent automatically and keep other people's attachments collapsed.
38
+ - Increase text selection contrast with an inverted accent background in both themes.
39
+ - Designate administrators in one step: the designation applies immediately and stays until revoked. The enrollment code and claim step are gone; existing claimed capabilities keep working.
40
+ - Render AVIF images and show a visible banner when an attachment upload fails.
41
+ - Keep the attachment preview toggle clickable and correctly labelled while a preview loads, and clear a preview that cannot be decoded.
42
+ - Stop rebuilding the question panel every few seconds and fix the CRON timezone label.
43
+ - Reject malformed JSON bodies with 400 instead of failing with 500.
44
+ - Re-check the operator token on every admin request and cap the in-memory wake table.
45
+ - Trim the queued watermark per room and remove the unused supervision inbox.
46
+
3
47
  ## 0.5.3 — 2026-11-11
4
48
 
5
49
  - Fix reply preview overflow and add an accessible cancel button and reply icon.
package/README.md CHANGED
@@ -22,7 +22,7 @@ Restart OpenCode. Ask an agent to create a room named `dev`, or enter `/room cre
22
22
  On a machine reachable by the other devices, start the server. Replace `your-password` with a shared password:
23
23
 
24
24
  ```bash
25
- bunx @alexsun-top/opencode-chat-room@0.5.3 --host 0.0.0.0 --port 4399 --token 'your-password'
25
+ bunx @alexsun-top/opencode-chat-room@0.5.5 --host 0.0.0.0 --port 4399 --token 'your-password'
26
26
  ```
27
27
 
28
28
  On each machine running OpenCode, set the server address and the same password, then start OpenCode from that environment:
@@ -37,6 +37,18 @@ Open `http://SERVER_IP:4399/chat` in a browser and enter the same password in se
37
37
 
38
38
  **Security:** Anyone with the shared password can access and manage rooms, including direct chats. Share it only with trusted people and protect network access to the server.
39
39
 
40
+ ### Docker
41
+
42
+ Every release also publishes a container image, so nothing needs to be built:
43
+
44
+ ```bash
45
+ docker run --rm -p 4399:4399 -v chat-room-data:/data \
46
+ -e CHAT_ROOM_SERVER_TOKEN='your-password' \
47
+ ghcr.io/agentsyaml/opencode-chat-room:latest
48
+ ```
49
+
50
+ Pin a release with `ghcr.io/agentsyaml/opencode-chat-room:v0.5.5`. Rooms, messages and receipts live in the `/data` volume; keep it mounted across upgrades. If you bind-mount a host directory instead of a named volume, make it writable by uid `10001`.
51
+
40
52
  ## 3. Start chatting
41
53
 
42
54
  - Ask an agent to create a room, join a room, or send a message; you can also use the web interface.
package/README.zh-CN.md CHANGED
@@ -22,7 +22,7 @@
22
22
  在一台可被其他设备访问的机器上启动服务器,把 `换成自己的密码` 换成共享密码:
23
23
 
24
24
  ```bash
25
- bunx @alexsun-top/opencode-chat-room@0.5.3 --host 0.0.0.0 --port 4399 --token '换成自己的密码'
25
+ bunx @alexsun-top/opencode-chat-room@0.5.5 --host 0.0.0.0 --port 4399 --token '换成自己的密码'
26
26
  ```
27
27
 
28
28
  在每台运行 OpenCode 的机器上设置服务器地址和相同密码,再从该环境启动 OpenCode:
@@ -37,6 +37,18 @@ opencode
37
37
 
38
38
  **安全提示:**共享密码的持有人可以访问和管理房间,包括私聊;请只分享给可信任的人,并保护服务器网络访问。
39
39
 
40
+ ### Docker
41
+
42
+ 每次发版同时发布容器镜像,不需要自己构建:
43
+
44
+ ```bash
45
+ docker run --rm -p 4399:4399 -v chat-room-data:/data \
46
+ -e CHAT_ROOM_SERVER_TOKEN='换成自己的密码' \
47
+ ghcr.io/agentsyaml/opencode-chat-room:latest
48
+ ```
49
+
50
+ 用 `ghcr.io/agentsyaml/opencode-chat-room:v0.5.5` 可以固定到具体版本。房间、消息和回执都保存在 `/data` 卷里,升级时保留该卷即可。如果改用宿主目录做挂载,需要让该目录对 uid `10001` 可写。
51
+
40
52
  ## 3. 开始聊天
41
53
 
42
54
  - 让 Agent 创建房间、加入房间或发送消息;也可以在网页里操作。
@@ -6,16 +6,14 @@ Administration is opt-in. Configure `CHAT_ROOM_ADMIN_TOKEN` on the central serve
6
6
 
7
7
  Both server tokens must be set to enable administration. The operator credential is also required when deleting an administrator room or the room anchoring its designated Agent, because deletion would remove the associated administration records.
8
8
 
9
- ## Enroll the designated Agent
9
+ ## Designate the Agent
10
10
 
11
11
  1. Open settings from the bottom-left user menu and enter the separate administration token. The browser retains it only for that tab.
12
- 2. Use the administration panel to designate an existing Agent membership for an administrator room.
13
- 3. Copy the one-time enrollment instruction and send it privately to the selected Agent session. Do not post it in a room.
14
- 4. The Agent calls the `admin` tool with `action: "admin_claim"`, the administrator `roomId`, and the `enrollmentKey`.
12
+ 2. Use the administration panel to select a normal room and a registered Agent in it, then designate that Agent.
15
13
 
16
- The plugin binds the claim to its native session and receiver owner. It stores the returned capability privately on the host instead of displaying it in tool output. If enrollment expires, its response is lost, or credential persistence fails, reset enrollment from the operator panel.
14
+ The designation applies immediately and stays in effect until it is revoked. No enrollment code, claim call, or private instruction is needed. The server authorizes the `admin` tool when the request carries the designated Agent's native session and receiver owner; capabilities claimed by older versions keep working.
17
15
 
18
- Reassigning the designation revokes the previous capability. Joining or rejoining a room never grants administrator privileges. Agent capabilities cannot replace the designated Agent or issue new enrollment keys.
16
+ Reassigning the designation takes effect for the new Agent right away. Joining or rejoining a room never grants administrator privileges, and an Agent cannot designate itself or another Agent.
19
17
 
20
18
  ## Inspect rooms and assign work
21
19
 
@@ -30,6 +28,6 @@ To assign work, send a message in the target room and mention the Agent. For sch
30
28
 
31
29
  ## Security and operations
32
30
 
33
- Use HTTPS outside loopback. Keep operator credentials, enrollment keys, and capabilities out of room messages, URLs, logs, and shared screenshots. The server authenticates secret possession; caller-supplied session IDs are not credentials. Processes with unrestricted access to the same OS account can read one another's files, so private file modes do not provide sandbox isolation between such Agents.
31
+ Use HTTPS outside loopback. Keep operator and legacy capability credentials out of room messages, URLs, logs, and shared screenshots. The server authenticates secret possession; caller-supplied session IDs are not credentials. Processes with unrestricted access to the same OS account can read one another's files, so private file modes do not provide sandbox isolation between such Agents.
34
32
 
35
- Back up server SQLite state to preserve designations, messages, and room reminders. Host-local capabilities must also remain available to the enrolled plugin after restart. Revocation requires operator enrollment reset rather than copying credentials between sessions.
33
+ Back up server SQLite state to preserve designations, messages, and room reminders. Revoking a designation removes the Agent's administrator rights immediately; it does not change the room itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,6 +26,7 @@
26
26
  "!src/**/*.test.ts",
27
27
  "skills/chatroom/SKILL.md",
28
28
  "server/chat-server.ts",
29
+ "server/json-body.ts",
29
30
  "server/inbox.ts",
30
31
  "server/history-route.ts",
31
32
  "server/newrooms.ts",
@@ -11,6 +11,8 @@ export function agentHeadersMatch(request: Request, binding: Binding): boolean {
11
11
  }
12
12
 
13
13
  export function hasAdminCapability(request: Request, binding: Binding): boolean {
14
- return Boolean(binding.capability_hash && agentHeadersMatch(request, binding) &&
15
- matchesHash(request.headers.get("x-chat-admin-capability") ?? "", binding.capability_hash));
14
+ if (!agentHeadersMatch(request, binding)) return false;
15
+ // Operator designation is the grant; the optional claim capability is legacy.
16
+ if (!binding.capability_hash) return true;
17
+ return matchesHash(request.headers.get("x-chat-admin-capability") ?? "", binding.capability_hash);
16
18
  }
@@ -54,7 +54,7 @@
54
54
  var(--bg);
55
55
  -webkit-tap-highlight-color: transparent;
56
56
  }
57
- ::selection { background: var(--accent-soft); }
57
+ ::selection { color: var(--accent-ink); background: var(--accent); }
58
58
 
59
59
  #app {
60
60
  max-width: 760px;
@@ -99,6 +99,7 @@
99
99
  .locale-control label { font-weight: 600; }
100
100
  .locale-select { appearance: auto; min-height: 36px; font: inherit; font-size: 12.5px; line-height: 1.25; color: var(--ink); background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 5px 9px; cursor: pointer; }
101
101
  .chat-head-actions .locale-control { margin: 0; }
102
+ .wordmark-row { display: flex; align-items: baseline; gap: 10px; }
102
103
  .wordmark {
103
104
  margin: 0;
104
105
  font-family: var(--font-display);
@@ -107,6 +108,9 @@
107
108
  letter-spacing: -.03em;
108
109
  color: var(--ink);
109
110
  }
111
+ .version-tag { font: 600 10px/1 var(--font-mono); color: var(--ink-3); background: var(--surface-2); border: 1px solid var(--line); border-radius: 999px; padding: 3px 7px; white-space: nowrap; }
112
+ .version-tag:empty { display: none; }
113
+ .rail-brand .version-tag { align-self: center; }
110
114
  .tagline { margin: 8px 0 26px; font-size: 13.5px; color: var(--ink-2); }
111
115
 
112
116
  .field { display: block; margin-bottom: 14px; }
@@ -85,6 +85,7 @@ export function initAdmin(app) {
85
85
  if (!agents.length) status(app.t("noAgents")); else status("");
86
86
  }
87
87
  $("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
88
+ app.verifyAdminToken = verifyToken;
88
89
  $("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
89
90
  $("#btnRefreshAdmin").addEventListener("click", async () => {
90
91
  const id = $("#adminRoomSelect").value;
@@ -110,15 +111,9 @@ export function initAdmin(app) {
110
111
  setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
111
112
  await loadBinding(generation);
112
113
  if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value) return;
113
- const box = $("#adminEnrollment"), instruction = `admin(action='admin_claim',roomId='${roomId}',enrollmentKey='${result.enrollmentKey}')`, copy = document.createElement("button"), warning = document.createElement("p"), fallback = document.createElement("textarea");
114
- warning.textContent = app.t("privateEnrollment", { expires: new Date(result.expiresAt).toLocaleString() });
115
- warning.id = "adminEnrollmentHelp"; fallback.className = "input"; fallback.readOnly = true; fallback.rows = 3; fallback.setAttribute("aria-label", app.t("copyEnrollment")); fallback.setAttribute("aria-describedby", warning.id);
116
- copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
117
- copy.addEventListener("click", async () => {
118
- try { if (!navigator.clipboard?.writeText) throw new Error(); await navigator.clipboard.writeText(instruction); status(app.t("enrollmentCopied")); }
119
- catch { fallback.value = instruction; box.replaceChildren(warning, fallback, copy); fallback.focus(); fallback.select(); status(warning.textContent || ""); }
120
- });
121
- box.replaceChildren(warning, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
114
+ const box = $("#adminEnrollment"), note = document.createElement("p");
115
+ note.textContent = app.t("adminDesignated");
116
+ box.replaceChildren(note); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
122
117
  } catch (error) { if (generation === viewGeneration) status(error.message, true); }
123
118
  finally { button.disabled = false; }
124
119
  });
@@ -54,7 +54,14 @@ export function initAnnouncements(app) {
54
54
  items = Array.isArray(result.announcements) ? result.announcements : [];
55
55
  status("");
56
56
  const chosen = items.find((item) => item.name === selected);
57
- if (!chosen) select(null); else select(chosen);
57
+ if (!chosen) {
58
+ const stale = selected && draft(id, selected);
59
+ if (stale) {
60
+ drafts.set(key(id, ""), { ...stale, name: $("#announcementName").value.trim() || stale.name });
61
+ drafts.delete(key(id, selected));
62
+ }
63
+ select(null);
64
+ } else select(chosen);
58
65
  render();
59
66
  } catch (error) {
60
67
  if (roomId() !== id || context !== roomGeneration || generation !== request) return;
@@ -83,6 +90,15 @@ export function initAnnouncements(app) {
83
90
  generation++; items = [...items.filter((item) => item.name !== name), result.announcement]; render();
84
91
  clearDraftIfUnchanged(id, draftName, captured);
85
92
  if (editorMatches(captured)) { select(result.announcement); status(app.t("announcementSaved")); }
93
+ else if (!selected) {
94
+ // Keep editing the newer draft under the name the create just reserved.
95
+ drafts.delete(key(id, draftName));
96
+ selected = result.announcement.name;
97
+ $("#announcementName").value = selected; $("#announcementName").readOnly = true;
98
+ $("#btnDeleteAnnouncement").hidden = false;
99
+ drafts.set(key(id, selected), { name: selected, content: $("#announcementContent").value });
100
+ render();
101
+ }
86
102
  }
87
103
  } catch (error) {
88
104
  if (currentRoom(id, context) && editorMatches(captured)) status(error.status === 403 ? error.message : app.t("announcementLoadFailed"));
@@ -112,7 +112,10 @@ export function initAttachments(app) {
112
112
  item.cancelled = true; item.xhr?.abort();
113
113
  if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
114
114
  const remaining = filesFor(id).filter((entry) => entry !== item);
115
- if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
115
+ if (remaining.length) {
116
+ drafts.set(id, remaining);
117
+ if (statuses.get(id)?.error && !remaining.some((entry) => entry.status === "failed")) statuses.delete(id);
118
+ } else { drafts.delete(id); statuses.delete(id); }
116
119
  if (roomId() === id) render();
117
120
  }
118
121
  function clearRoom(id) {
@@ -91,11 +91,24 @@ function lengthBefore(root, target, position) {
91
91
  }
92
92
 
93
93
  export function setCaret(editor, offset) {
94
- const selection = getSelection(), range = document.createRange(), point = editorPoint(editor, offset);
95
- range.setStart(point[0], point[1]); range.collapse(true);
94
+ const selection = getSelection(), range = document.createRange();
95
+ // Chromium starts IME composition poorly at an element boundary next to a
96
+ // non-editable chip; keep the caret inside a real text node instead.
97
+ const [container, index] = textPoint(editorPoint(editor, offset));
98
+ range.setStart(container, index); range.collapse(true);
96
99
  selection.removeAllRanges(); selection.addRange(range);
97
100
  }
98
101
 
102
+ function textPoint([container, offset]) {
103
+ if (container.nodeType !== Node.ELEMENT_NODE) return [container, offset];
104
+ const child = container.childNodes[offset], previous = container.childNodes[offset - 1];
105
+ if (child?.nodeType === Node.TEXT_NODE) return [child, 0];
106
+ if (previous?.nodeType === Node.TEXT_NODE) return [previous, previous.length];
107
+ const text = document.createTextNode("");
108
+ container.insertBefore(text, child || null);
109
+ return [text, 0];
110
+ }
111
+
99
112
  export function setEditorSelection(editor, start, end = start) {
100
113
  const range = document.createRange(), selection = getSelection();
101
114
  const first = editorPoint(editor, start), last = editorPoint(editor, end);
@@ -1,5 +1,6 @@
1
1
  import { LS } from "./state.js";
2
2
  import { copyTextToClipboard } from "./markdown.js";
3
+ import { isUnreadMessage } from "./messages.js";
3
4
 
4
5
  export function initEvents(app) {
5
6
  const $ = app.$;
@@ -19,9 +20,16 @@ export function initEvents(app) {
19
20
  const anchor = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((row) => row.getBoundingClientRect().bottom > top);
20
21
  readingPosition = { roomId: app.state.room?.id, messageId: anchor?.dataset.msgId, offset: anchor ? anchor.getBoundingClientRect().top - top : 0,
21
22
  atBottom: thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 4 };
22
- const missing = app.state.readAnchorGuard?.roomId === readingPosition.roomId && app.state.readAnchorGuard.missing;
23
+ const guard = app.state.readAnchorGuard;
24
+ let missing = guard?.roomId === readingPosition.roomId && guard.missing;
25
+ // A failed restore keeps its anchor while the landing stays put; scrolling to a
26
+ // different message means the reader chose a new position and the old one is stale.
27
+ if (missing) {
28
+ if (!guard.landingId) guard.landingId = readingPosition.messageId;
29
+ else if (readingPosition.messageId !== guard.landingId) missing = guard.missing = false;
30
+ }
23
31
  if (readingPosition.roomId && anchor && (!missing || performance.now() <= app.state.userScrollIntentUntil)) {
24
- app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId, offset: readingPosition.offset });
32
+ app.savePosition(readingPosition.roomId, { messageId: readingPosition.messageId, offset: readingPosition.offset, atBottom: readingPosition.atBottom });
25
33
  }
26
34
  }
27
35
  app.captureReadingPosition = captureReadingPosition;
@@ -50,17 +58,23 @@ export function initEvents(app) {
50
58
  };
51
59
  app.restoreReadingPosition = (roomId) => {
52
60
  const thread = $("#thread"), saved = app.state.positions.get(roomId), entry = app.state.rooms.get(roomId);
61
+ const atBottom = () => thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 4;
53
62
  const align = (messageId, offset) => {
54
63
  const row = [...$("#msgList").querySelectorAll("[data-msg-id]")].find((item) => item.dataset.msgId === messageId);
55
64
  if (!row) return false;
56
65
  thread.scrollTop += row.getBoundingClientRect().top - (thread.getBoundingClientRect().top + thread.clientTop + offset);
57
66
  captureReadingPosition(); return true;
58
67
  };
59
- if (typeof saved === "number") { thread.scrollTop = saved; captureReadingPosition(); return { messageId: readingPosition?.messageId }; }
60
- if (saved?.messageId && align(saved.messageId, Number(saved.offset) || 0)) return { messageId: saved.messageId };
68
+ if (typeof saved === "number") { thread.scrollTop = saved; captureReadingPosition(); return { messageId: readingPosition?.messageId, atBottom: atBottom() }; }
61
69
  const readTs = entry?.readTs || app.state.lastReadTs.get(roomId) || 0;
62
- const boundary = readTs && entry?.room.messages.find((message) => message.createdAt > readTs);
63
- if (boundary && align(boundary.id, 0)) return { messageId: boundary.id };
70
+ // Own messages never form an unread boundary; landing on them hides the newest activity.
71
+ const boundary = readTs && entry?.room.messages.find((message) => message.createdAt > readTs && isUnreadMessage(message, app, entry.room, entry.name));
72
+ // Leaving at the bottom and returning to new messages lands on the first unread;
73
+ // a deliberate scroll position is restored exactly.
74
+ if ((entry?.unreadIds.size || entry?.unreadOverflow) && saved?.atBottom !== false && boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
75
+ if (saved?.messageId && align(saved.messageId, Number(saved.offset) || 0)) return { messageId: saved.messageId, atBottom: atBottom() };
76
+ if (boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
77
+ if (!saved && !boundary) return false;
64
78
  return saved?.messageId || readTs ? { messageId: saved?.messageId || null, missing: true } : false;
65
79
  };
66
80
  function closeRoomDrawer(restore = true) {
@@ -227,6 +241,9 @@ export function initEvents(app) {
227
241
  if (event.deltaY < 0 && thread.scrollTop <= 0 || event.deltaY > 0 && gap <= 2) event.preventDefault();
228
242
  }, { passive: false });
229
243
  thread.addEventListener("touchmove", markScrollIntent, { passive: true });
244
+ thread.addEventListener("keydown", (event) => {
245
+ if (/^(PageDown|PageUp|End|Home|ArrowDown|ArrowUp| )$/.test(event.key)) markScrollIntent();
246
+ });
230
247
  thread.addEventListener("pointerdown", (event) => {
231
248
  if (event.clientX >= thread.getBoundingClientRect().right - 18) markScrollIntent();
232
249
  });
@@ -234,7 +251,7 @@ export function initEvents(app) {
234
251
  const adjusting = (app.state.resizeScrollAdjusting || app.state.layoutScrollAdjusting)
235
252
  && performance.now() > app.state.userScrollIntentUntil;
236
253
  if (!adjusting || performance.now() <= app.state.userScrollIntentUntil) captureReadingPosition();
237
- if (!adjusting && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) void app.markActiveRoomRead();
254
+ if (!adjusting && thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) void app.markActiveRoomRead(performance.now() <= app.state.userScrollIntentUntil);
238
255
  app.queueReceiptRefresh();
239
256
  if (!adjusting) app.queueReceiptObservation();
240
257
  app.updateJump();
@@ -327,6 +344,7 @@ function saveAccessToken(button, app) {
327
344
  try { persistent = localStorage.getItem("chat.token") === LS.token; } catch { /* Memory fallback is tab-scoped. */ }
328
345
  app.flash(button, persistent ? "saved" : "savedMemory");
329
346
  void app.refreshRoomList();
347
+ void app.verifyAdminToken?.();
330
348
  app.retryPendingAction();
331
349
  }
332
350
 
@@ -132,14 +132,19 @@ async function loadResourceCard(card, roomId, app) {
132
132
  if (previewKind(type)) {
133
133
  const preview = resourceButton("resourcePreview", resource.name, () => previewResource(card, roomId, id, resource, type, preview, app, status), app);
134
134
  actions.append(preview);
135
+ // Media you sent yourself is shown inline; other people's media stays collapsed.
136
+ if (card.closest(".msg.own")) void previewResource(card, roomId, id, resource, type, preview, app, status);
135
137
  }
136
138
  } catch { if (card.isConnected) setResourceError(card, app); }
137
139
  }
140
+ function setResourceButton(button, key, name, app) {
141
+ button.dataset.i18n = key; button.textContent = app.t(key);
142
+ button.setAttribute("aria-label", `${app.t(key)}: ${name}`);
143
+ }
138
144
  function resourceButton(key, name, action, app) {
139
145
  const button = document.createElement("button");
140
146
  button.type = "button"; button.className = "btn ghost small resource-button";
141
- button.dataset.i18n = key; button.textContent = app.t(key);
142
- button.setAttribute("aria-label", `${app.t(key)}: ${name}`);
147
+ setResourceButton(button, key, name, app);
143
148
  button.addEventListener("click", action); return button;
144
149
  }
145
150
  async function downloadResource(card, roomId, id, resource, app, status, button) {
@@ -161,30 +166,45 @@ async function previewResource(card, roomId, id, resource, type, button, app, st
161
166
  button.disabled = true;
162
167
  if (card._previewElement) {
163
168
  try {
164
- await app.preserveReadingLayout(() => card._previewElement.remove());
169
+ await app.preserveReadingLayout(() => {
170
+ card._previewElement.remove();
171
+ setResourceButton(button, "resourcePreview", resource.name, app); button.disabled = false;
172
+ });
165
173
  URL.revokeObjectURL(card._resourceUrl); previewUrls.delete(card); delete card._resourceUrl; delete card._previewElement;
166
- if (card.isConnected) { button.dataset.i18n = "resourcePreview"; button.textContent = app.t("resourcePreview"); }
167
174
  } catch {
168
175
  if (!card.isConnected) return;
169
176
  } finally { if (card.isConnected) button.disabled = false; }
170
177
  return;
171
178
  }
172
179
  status.textContent = app.t("resourceLoading");
173
- let url;
180
+ let url, media;
181
+ const fail = () => {
182
+ media?.remove(); media = undefined;
183
+ if (url) { URL.revokeObjectURL(url); url = undefined; }
184
+ setResourceButton(button, "resourcePreview", resource.name, app); button.disabled = false;
185
+ if (card.isConnected) status.textContent = app.t("resourceFailed");
186
+ };
174
187
  try {
175
188
  const blob = await app.apiBlob(`/rooms/${encodeURIComponent(roomId)}/resources/${encodeURIComponent(id)}/content`);
176
189
  if (!card.isConnected) return;
177
190
  url = URL.createObjectURL(blob);
178
- const kind = previewKind(type), media = document.createElement(kind), ready = waitForMediaSize(media, kind);
191
+ const kind = previewKind(type);
192
+ media = document.createElement(kind);
193
+ const ready = waitForMediaSize(media, kind);
179
194
  if (kind === "img") media.alt = resource.name;
180
195
  else { media.controls = true; media.preload = "metadata"; }
181
- media.addEventListener("error", () => { if (card.isConnected) status.textContent = app.t("resourceFailed"); });
196
+ media.addEventListener("error", fail, { once: true });
182
197
  media.src = url;
183
- await app.preserveReadingLayout(async () => { status.textContent = ""; card.append(media); await ready; });
184
- if (!card.isConnected) { URL.revokeObjectURL(url); return; }
198
+ // Update the control inside the layout step: a stalled animation frame must not
199
+ // leave the preview open with a disabled button.
200
+ await app.preserveReadingLayout(async () => {
201
+ status.textContent = ""; card.append(media);
202
+ setResourceButton(button, "resourceHide", resource.name, app); button.disabled = false;
203
+ await ready;
204
+ });
205
+ if (!card.isConnected) { fail(); return; }
185
206
  card._resourceUrl = url; card._previewElement = media; previewUrls.set(card, url); watchPreviewRemoval();
186
- button.dataset.i18n = "resourceHide"; button.textContent = app.t("resourceHide");
187
- } catch { if (url) URL.revokeObjectURL(url); if (card.isConnected) status.textContent = app.t("resourceFailed"); }
207
+ } catch { fail(); }
188
208
  finally { if (card.isConnected) button.disabled = false; }
189
209
  }
190
210
  function waitForMediaSize(media, kind) {
@@ -77,8 +77,10 @@ export function initMentions(app) {
77
77
  if (input.value.slice(mention.start, end) !== `@${mention.query}`) return app.closeMention();
78
78
  replaceEditorRange(input, mention.start, end, `<at>@${name}</at>`);
79
79
  app.closeMention();
80
- input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
80
+ // Chrome can reset the selection while focus() lands; restore the caret last.
81
81
  input.focus({ preventScroll: true });
82
+ input.setCaret?.(mention.start + `<at>@${name}</at>`.length);
83
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }));
82
84
  };
83
85
  }
84
86