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

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,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 — 2026-11-13
4
+
5
+ - Open rooms from a local IndexedDB snapshot first and merge the server delta afterwards, so revisiting a room renders instantly instead of re-downloading its history.
6
+ - Fetch only the newest 100 messages when opening a room; scrolling up loads older pages with a loading indicator, like an IM app.
7
+ - Raise the loaded-message window in the browser from 500 to 5,000, with older history available on demand.
8
+ - Keep up to 1,000,000 messages per room on the server, trimming the oldest lazily so writes stay fast.
9
+ - Fix the room ID showing "undefined" after clicking copy.
10
+ - Keep typing after cancelling an IME composition next to an @mention: the caret no longer gets stuck inside the mention chip, and the chip's own name is not mistaken for a mention query that pops the picker.
11
+ - Clicking a reply's quote now aligns the original message's top with the thread's top edge so the following conversation stays visible, and flashes the message bubble twice.
12
+ - Copy a message (or a composer selection) containing @mentions and paste it back to rebuild the mention chips; pasting external text that merely looks like mention markup stays literal.
13
+ - Reopen a room at the live bottom when the previous visit ended at the bottom with nothing unread, and flush the read watermark when the tab hides or closes.
14
+ - Edit a room's name and description from Options → Edit room (owner only); each change posts a system notice to the room and shows the description under the room title.
15
+ - Show a question-mark badge on rooms with unanswered questions, in the same slot as the unread count. Reading to the bottom clears the unread badge; pending questions stay visible in the Questions panel.
16
+ - Let room owners designate the room's administrator agent from the edit dialog and remove the separate operator administration token. Existing designations and claimed capabilities keep working; deleting a room removes its designation.
17
+
3
18
  ## 0.5.5 — 2026-11-13
4
19
 
5
20
  - Clear own messages and entries older than the read watermark from the unread set, so a badge can no longer stick.
@@ -1,19 +1,10 @@
1
1
  # Administrator rooms
2
2
 
3
- An administrator room is a normal group room with one operator-designated Agent. That Agent can inspect rooms and their history without joining them.
3
+ An administrator room is a normal group room whose owner designates one registered Agent as its administrator. That Agent can inspect rooms and their history without joining them.
4
4
 
5
- Administration is opt-in. Configure `CHAT_ROOM_ADMIN_TOKEN` on the central server with a secret different from `CHAT_ROOM_SERVER_TOKEN`. Ordinary room access still uses the existing server token. This change does not update an existing deployment or its configuration automatically.
5
+ There is no separate operator credential. The room owner manages the designation from the room's **Options → Edit room** dialog: pick a registered Agent member as the administrator, or choose **None** to revoke. The change applies immediately and stays in effect until the owner revokes it or designates a different Agent.
6
6
 
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
-
9
- ## Designate the Agent
10
-
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 select a normal room and a registered Agent in it, then designate that Agent.
13
-
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.
15
-
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.
7
+ Only the room owner can edit the room or change its administrator. Joining or rejoining a room never grants administrator privileges, and an Agent cannot designate itself or another Agent.
17
8
 
18
9
  ## Inspect rooms and assign work
19
10
 
@@ -24,10 +15,12 @@ The `admin` tool uses `roomId` for the administrator room.
24
15
  | `admin_overview` | None | Inspect rooms and members |
25
16
  | `admin_history` | `targetRoomId`, optional `limit` | Inspect bounded target-room history |
26
17
 
18
+ The server authorizes these calls from the designated Agent's native session and receiver owner identity; a normal room token, a mention, or room membership does not grant administrator privileges. Capabilities claimed by older versions keep working.
19
+
27
20
  To assign work, send a message in the target room and mention the Agent. For scheduled work, create a room reminder containing the instruction and mention. The host must be available to execute the Agent; sending a reminder does not itself guarantee completion.
28
21
 
29
22
  ## Security and operations
30
23
 
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.
24
+ Use HTTPS outside loopback. Keep legacy capability credentials out of room messages, URLs, logs, and shared screenshots. The server authenticates the Agent's native identity; 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.
32
25
 
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.
26
+ 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. Deleting an administrator room removes its designation along with the room.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.5.5",
3
+ "version": "0.6.0",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,6 +29,7 @@
29
29
  "server/json-body.ts",
30
30
  "server/inbox.ts",
31
31
  "server/history-route.ts",
32
+ "server/room-payload.ts",
32
33
  "server/newrooms.ts",
33
34
  "server/member-routes.ts",
34
35
  "server/announcement-routes.ts",
@@ -1,9 +1,4 @@
1
- import { matchesHash, safeEqual, type Binding } from "./admin-state";
2
-
3
- const operatorSecret = process.env.CHAT_ROOM_ADMIN_TOKEN ?? "";
4
- const serverSecret = process.env.CHAT_ROOM_SERVER_TOKEN ?? "";
5
- export const adminEnabled = Boolean(operatorSecret && serverSecret && !safeEqual(operatorSecret, serverSecret));
6
- export const isOperator = (request: Request) => adminEnabled && safeEqual(request.headers.get("x-chat-admin-token") ?? "", operatorSecret);
1
+ import { matchesHash, type Binding } from "./admin-state";
7
2
 
8
3
  export function agentHeadersMatch(request: Request, binding: Binding): boolean {
9
4
  return request.headers.get("x-chat-agent-session") === binding.session_id &&
@@ -12,7 +7,7 @@ export function agentHeadersMatch(request: Request, binding: Binding): boolean {
12
7
 
13
8
  export function hasAdminCapability(request: Request, binding: Binding): boolean {
14
9
  if (!agentHeadersMatch(request, binding)) return false;
15
- // Operator designation is the grant; the optional claim capability is legacy.
10
+ // Owner designation is the grant; the optional claim capability is legacy.
16
11
  if (!binding.capability_hash) return true;
17
12
  return matchesHash(request.headers.get("x-chat-admin-capability") ?? "", binding.capability_hash);
18
13
  }
@@ -1,16 +1,16 @@
1
1
  import { databasePath } from "../src/store";
2
2
  import { readHistoryPage } from "../src/sqlite-state";
3
- import { adminEnabled, hasAdminCapability, isOperator } from "./admin-auth";
4
- import { binding, digest, ensureAdminSchema, exec, isAgentMember, many, matchesHash, newSecret, one, publicRoom, tx, validCurrent, enroll } from "./admin-state";
5
- import type { Binding } from "./admin-state";
3
+ import { hasAdminCapability } from "./admin-auth";
4
+ import { binding, digest, ensureAdminSchema, exec, isAgentMember, many, matchesHash, newSecret, one, publicRoom, tx, validCurrent } from "./admin-state";
6
5
 
7
6
  const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
8
7
  const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
9
8
  await ensureAdminSchema();
10
9
 
10
+ // Designation is managed by room owners through PATCH /rooms/:id; these routes
11
+ // only serve the designated agent (overview/history) and the legacy claim flow.
11
12
  export async function adminRoutes(request: Request, url: URL): Promise<Response | undefined> {
12
13
  if (!url.pathname.startsWith("/admin/") && !url.pathname.startsWith("/supervision/")) return undefined;
13
- if (!adminEnabled) return json({ error: "admin API is disabled" }, 503);
14
14
  try {
15
15
  await ensureAdminSchema();
16
16
  return await rootRoutes(request, url);
@@ -22,48 +22,16 @@ export async function adminRoutes(request: Request, url: URL): Promise<Response
22
22
 
23
23
  async function rootRoutes(request: Request, url: URL): Promise<Response> {
24
24
  const path = url.pathname;
25
- if (request.method === "GET" && path === "/admin/rooms") return listRooms(request);
26
- if (request.method === "POST" && path === "/admin/rooms") return createBinding(request);
27
25
  const claim = path.match(/^\/admin\/rooms\/([^/]+)\/claim$/);
28
26
  if (claim && request.method === "POST") return claimBinding(request, decodeURIComponent(claim[1]!));
29
27
  const room = path.match(/^\/admin\/rooms\/([^/]+)(?:\/(overview|history))?$/);
30
28
  if (!room) return json({ error: "not found" }, 404);
31
29
  const roomID = decodeURIComponent(room[1]!);
32
- if (request.method === "PUT" && !room[2]) return rotateBinding(request, roomID);
33
- if (request.method === "DELETE" && !room[2]) return revokeBinding(request, roomID);
34
30
  if (request.method === "GET" && room[2] === "overview") return overview(request, roomID);
35
31
  if (request.method === "GET" && room[2] === "history") return history(request, url, roomID);
36
32
  return json({ error: "method not allowed" }, 405);
37
33
  }
38
34
 
39
- async function listRooms(request: Request): Promise<Response> {
40
- if (!isOperator(request)) return json({ error: "operator token required" }, 401);
41
- return json({ rooms: await tx(db => many<Binding>(db, "SELECT * FROM admin_rooms ORDER BY created_at LIMIT 200").map(publicRoom)) });
42
- }
43
-
44
- async function createBinding(request: Request): Promise<Response> {
45
- if (!isOperator(request)) return json({ error: "operator token required" }, 401);
46
- const body: unknown = await request.json();
47
- if (!object(body) || !bounded(body.roomId, 128) || !bounded(body.targetRoomId, 128) ||
48
- !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 ||
49
- !bounded(body.membershipID, 128)) return json({ error: "invalid admin binding" }, 400);
50
- const { roomId, targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
51
- roomId: string; targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
52
- };
53
- const result = await tx(db => {
54
- const admin = one<{ kind: string }>(db, "SELECT kind FROM rooms WHERE id=?", roomId);
55
- if (!admin) return { status: 404 as const, error: "admin room not found" };
56
- if (admin.kind !== "group") return { status: 400 as const, error: "admin room must be a group room" };
57
- if (one(db, "SELECT 1 FROM admin_rooms WHERE room_id=?", roomId)) return { status: 409 as const, error: "admin room already designated; use PUT to rotate" };
58
- if (!one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomId)) return { status: 404 as const, error: "target room not found" };
59
- if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return { status: 409 as const, error: "target agent binding is not active" };
60
- const issued = enroll(db, roomId, targetRoomId, sessionID, receiverOwnerID, membershipID, 1);
61
- const adminBinding = binding(db, roomId);
62
- return issued && adminBinding ? { status: 201 as const, issued, adminRoom: publicRoom(adminBinding) } : { status: 409 as const, error: "admin room cannot be designated" };
63
- });
64
- return "issued" in result ? json({ adminRoom: result.adminRoom, ...result.issued }, result.status) : json({ error: result.error }, result.status);
65
- }
66
-
67
35
  function bounded(value: unknown, max: number): value is string {
68
36
  return typeof value === "string" && value.trim().length > 0 && value.length <= max;
69
37
  }
@@ -86,37 +54,12 @@ async function claimBinding(request: Request, roomID: string): Promise<Response>
86
54
  return result ? json(result) : json({ error: "claim rejected" }, 409);
87
55
  }
88
56
 
89
- async function rotateBinding(request: Request, roomID: string): Promise<Response> {
90
- if (!isOperator(request)) return json({ error: "operator token required" }, 401);
91
- const body: unknown = await request.json();
92
- if (!object(body) || !bounded(body.targetRoomId, 128) || !bounded(body.sessionID, 128) ||
93
- typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 || !bounded(body.membershipID, 128)) return json({ error: "invalid binding" }, 400);
94
- const { targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
95
- targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
96
- };
97
- const result = await tx(db => {
98
- const old = binding(db, roomID);
99
- if (!old) return null;
100
- if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return null;
101
- const issued = enroll(db, roomID, targetRoomId, sessionID, receiverOwnerID, membershipID, old.generation + 1);
102
- const current = binding(db, roomID);
103
- return issued && current ? { issued, adminRoom: publicRoom(current) } : null;
104
- });
105
- return result ? json({ adminRoom: result.adminRoom, ...result.issued }) : json({ error: "admin room or active agent binding not found" }, 409);
106
- }
107
-
108
- async function revokeBinding(request: Request, roomID: string): Promise<Response> {
109
- if (!isOperator(request)) return json({ error: "operator token required" }, 401);
110
- const deleted = await tx(db => exec(db, "DELETE FROM admin_rooms WHERE room_id=?", roomID).changes);
111
- return deleted ? json({ ok: true }) : json({ error: "admin room not found" }, 404);
112
- }
113
-
114
57
  async function overview(request: Request, roomID: string): Promise<Response> {
115
58
  const result = await tx(db => {
116
59
  const b = binding(db, roomID);
117
60
  if (!b) return { status: 404 as const };
118
- if (!authorized(request, b)) return { status: 401 as const };
119
- if (!isOperator(request) && !validCurrent(db, b)) return { status: 409 as const };
61
+ if (!hasAdminCapability(request, b)) return { status: 401 as const };
62
+ if (!validCurrent(db, b)) return { status: 409 as const };
120
63
  const rooms = many<{ id: string; name: string; createdAt: number }>(db, "SELECT id,name,created_at AS createdAt FROM rooms ORDER BY created_at DESC LIMIT 200")
121
64
  .map(room => ({ ...room, members: many(db, "SELECT g.session_id AS sessionID,g.name,g.protocol,g.receiver_owner_id AS receiverOwnerID,g.work_state AS workState,g.last_seen_at AS lastSeenAt FROM registry g WHERE g.room_id=? ORDER BY g.name", room.id) }));
122
65
  return { rooms };
@@ -132,14 +75,10 @@ async function history(request: Request, url: URL, roomID: string): Promise<Resp
132
75
  const allowed = await tx(db => {
133
76
  const b = binding(db, roomID);
134
77
  if (!b) return 404;
135
- if (!authorized(request, b)) return 401;
136
- if (!isOperator(request) && !validCurrent(db, b)) return 409;
78
+ if (!hasAdminCapability(request, b)) return 401;
79
+ if (!validCurrent(db, b)) return 409;
137
80
  return one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomID) ? 200 : 404;
138
81
  });
139
82
  if (allowed !== 200) return json({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
140
83
  return json(await readHistoryPage(databasePath(), targetRoomID, undefined, limit));
141
84
  }
142
-
143
- function authorized(request: Request, b: import("./admin-state").Binding): boolean {
144
- return isOperator(request) || hasAdminCapability(request, b);
145
- }
@@ -18,6 +18,8 @@
18
18
  --accent-soft: #e1eee6;
19
19
  --danger: #a84437;
20
20
  --danger-soft: #f7e8e1;
21
+ --warning: #a9761c;
22
+ --warning-ink: #fffdf6;
21
23
  --mention-blue: #266c72;
22
24
  --shadow: 0 2px 5px rgb(34 53 47 / .05), 0 18px 44px rgb(34 53 47 / .09);
23
25
  }
@@ -36,6 +38,8 @@
36
38
  --accent-soft: #263d34;
37
39
  --danger: #ef9580;
38
40
  --danger-soft: #3a2924;
41
+ --warning: #d9a441;
42
+ --warning-ink: #241a09;
39
43
  --mention-blue: #8bc8c2;
40
44
  --shadow: 0 2px 6px rgb(0 0 0 / .22), 0 18px 44px rgb(0 0 0 / .32);
41
45
  }
@@ -1,19 +1,18 @@
1
1
  import { LS } from "./state.js";
2
2
 
3
+ // Admin badges come from the room payload (adminSessionID); room owners manage
4
+ // the designation through the edit-room dialog instead of an operator token.
3
5
  export function initAdmin(app) {
4
- const $ = app.$, dialog = $("#adminDialog");
5
- let rooms = [], bindings = [], agents = [], viewGeneration = 0, designationGeneration = 0, tokenGeneration = 0;
6
- const status = (text, error = false) => { $("#adminStatus").textContent = text; $("#adminStatus").classList.toggle("danger-text", error); };
7
- const json = (body) => JSON.stringify(body);
8
- const select = (node, values, label, id = (item) => item.id) => {
9
- node.replaceChildren(new Option(label, ""), ...values.map((item) => new Option(item.name, id(item))));
10
- };
11
- app.state.adminRoomIds = new Set();
6
+ const $ = app.$, dialog = $("#editRoomDialog");
7
+ let agents = [], generation = 0, agentsReady = false;
8
+
12
9
  const renderRoomOptions = app.renderRoomOptions;
13
10
  app.renderRoomOptions = (list, available) => {
14
11
  renderRoomOptions(list, available);
12
+ const byId = new Map((available || []).map((room) => [room.id, room]));
15
13
  for (const button of list?.querySelectorAll(".room-row[data-room-id]") || []) {
16
- if (!app.state.adminRoomIds.has(button.dataset.roomId)) continue;
14
+ const room = app.state.rooms.get(button.dataset.roomId)?.room || byId.get(button.dataset.roomId);
15
+ if (!room?.adminSessionID) continue;
17
16
  const badge = document.createElement("span"); badge.className = "room-admin-badge"; badge.textContent = app.t("adminRoomBadge");
18
17
  button.querySelector(".r-name")?.after(badge);
19
18
  }
@@ -22,109 +21,58 @@ export function initAdmin(app) {
22
21
  app.renderHead = () => {
23
22
  renderHead();
24
23
  const badge = $("#activeAdminBadge");
25
- if (badge) badge.hidden = !app.state.adminRoomIds.has(app.state.room?.id);
24
+ if (badge) badge.hidden = !app.state.room?.adminSessionID;
26
25
  };
27
- function setAdminRooms(items) {
28
- app.state.adminRoomIds = new Set(items.map((item) => item.roomId));
29
- app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
30
- app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
31
- if (app.state.room) app.renderHead();
32
- }
33
- function renderAdminRooms() {
34
- $("#adminRoomSelect").replaceChildren(new Option(app.t("chooseAdminRoom"), ""), ...rooms.map((room) => new Option(`${room.name}${bindings.some((item) => item.roomId === room.id) ? ` · ${app.t("adminRoomBadge")}` : ""}`, room.id)));
35
- }
36
- const clearEnrollment = () => { $("#adminEnrollment").replaceChildren(); $("#adminEnrollment").hidden = true; };
37
- async function verifyToken() {
38
- const generation = ++tokenGeneration, token = LS.adminToken, error = $("#adminAccessError"), button = $("#btnOpenAdmin");
39
- error.hidden = true; button.hidden = true;
40
- if (!token) { setAdminRooms([]); return; }
41
- try {
42
- const result = await app.adminApi("/admin/rooms");
43
- if (generation !== tokenGeneration || token !== LS.adminToken) return;
44
- setAdminRooms(result.rooms || []); button.hidden = false;
45
- } catch (failure) {
46
- if (generation === tokenGeneration && token === LS.adminToken) { setAdminRooms([]); error.textContent = failure.message; error.hidden = false; }
47
- }
48
- }
49
- async function open() {
50
- const generation = ++viewGeneration;
51
- clearEnrollment();
52
- dialog.showModal(); status(app.t("adminLoading"));
53
- $("#adminRoomSelect").disabled = $("#adminTargetAgent").disabled = $("#btnDesignateAgent").disabled = true; $("#btnRevokeAdmin").hidden = true;
54
- try {
55
- const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
56
- if (generation !== viewGeneration || !dialog.open) return;
57
- bindings = adminResult.rooms || []; setAdminRooms(bindings); rooms = roomResult || [];
58
- renderAdminRooms();
59
- $("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
60
- status(""); await loadBinding(generation);
61
- } catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
62
- finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#adminTargetAgent").disabled = false; } }
63
- }
64
- async function registryAgents(roomId) {
65
- return roomId ? Object.entries(await app.api(`/rooms/${encodeURIComponent(roomId)}/registry`)).map(([sessionID, value]) => ({ sessionID, ...value })).filter((agent) => agent.membershipID && (agent.protocol === "v1" || agent.protocol === "v2" || agent.receiverOwnerID || agent.host)) : [];
66
- }
67
- async function loadDesignationAgents() {
68
- const generation = ++designationGeneration, roomId = $("#adminRoomSelect").value;
69
- agents = []; $("#adminTargetAgent").disabled = $("#btnDesignateAgent").disabled = true; select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
26
+
27
+ async function loadAgents(gen) {
28
+ const room = app.state.room; if (!room) return;
29
+ const select = $("#editRoomAdmin");
30
+ select.replaceChildren(new Option(app.t("noAdminAgent"), ""));
31
+ agentsReady = false;
70
32
  try {
71
- const found = await registryAgents(roomId);
72
- if (generation !== designationGeneration || roomId !== $("#adminRoomSelect").value) return;
73
- agents = found; select($("#adminTargetAgent"), agents, app.t("chooseAgent"), (agent) => agent.sessionID); $("#adminTargetAgent").disabled = false;
74
- } catch (error) { if (generation === designationGeneration) { status(error.message, true); $("#btnDesignateAgent").disabled = true; } }
33
+ const registry = await app.api(`/rooms/${encodeURIComponent(room.id)}/registry`);
34
+ if (gen !== generation || !dialog.open) return;
35
+ agents = Object.entries(registry).map(([sessionID, value]) => ({ sessionID, ...value }))
36
+ .filter((agent) => agent.membershipID && (agent.protocol === "v1" || agent.protocol === "v2" || agent.receiverOwnerID || agent.host));
37
+ for (const agent of agents) select.append(new Option(agent.name, agent.sessionID));
38
+ select.value = agents.some((agent) => agent.sessionID === room.adminSessionID) ? room.adminSessionID : "";
39
+ agentsReady = true;
40
+ } catch (error) { if (gen === generation) $("#editRoomStatus").textContent = error.message; }
75
41
  }
76
- async function loadBinding(generation = ++viewGeneration) {
77
- const id = $("#adminRoomSelect").value;
78
- const binding = bindings.find((item) => item.roomId === id);
79
- $("#btnRevokeAdmin").hidden = !binding;
80
- if (!id) { agents = []; $("#btnDesignateAgent").disabled = true; status(app.t("createAdminRoomFirst")); select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID); return; }
81
- await loadDesignationAgents();
82
- if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || !dialog.open) return;
83
- if (binding) $("#adminTargetAgent").value = binding.sessionID;
84
- $("#btnDesignateAgent").disabled = !agents.some((agent) => agent.sessionID === $("#adminTargetAgent").value);
85
- if (!agents.length) status(app.t("noAgents")); else status("");
42
+
43
+ function open() {
44
+ const room = app.state.room; if (!room) return;
45
+ $("#editRoomName").value = room.name;
46
+ $("#editRoomDescription").value = room.description || "";
47
+ $("#editRoomStatus").textContent = "";
48
+ dialog.showModal();
49
+ void loadAgents(++generation);
86
50
  }
87
- $("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
88
- app.verifyAdminToken = verifyToken;
89
- $("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
90
- $("#btnRefreshAdmin").addEventListener("click", async () => {
91
- const id = $("#adminRoomSelect").value;
92
- const generation = ++viewGeneration;
93
- try { const [result, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]); if (generation !== viewGeneration || !dialog.open) return; bindings = result.rooms || []; rooms = roomResult || []; setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = id; await loadBinding(generation); }
94
- catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
95
- });
96
- $("#btnCloseAdmin").addEventListener("click", () => dialog.close());
97
- dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); });
51
+
52
+ $("#btnEditRoom").addEventListener("click", () => { app.closePanels(); open(); });
53
+ $("#btnCloseEditRoom").addEventListener("click", () => dialog.close());
98
54
  dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
99
- $("#adminRoomSelect").addEventListener("change", () => { clearEnrollment(); void loadBinding(); });
100
- $("#adminTargetAgent").addEventListener("change", () => { clearEnrollment(); $("#btnDesignateAgent").disabled = !agents.some((agent) => agent.sessionID === $("#adminTargetAgent").value); });
101
- $("#btnDesignateAgent").addEventListener("click", async () => {
102
- const roomId = $("#adminRoomSelect").value, agent = agents.find((item) => item.sessionID === $("#adminTargetAgent").value);
103
- if (!roomId || !agent || !agent.membershipID) return status(app.t("selectAdminAgent"), true);
104
- const body = { targetRoomId: roomId, sessionID: agent.sessionID, receiverOwnerID: agent.receiverOwnerID || "", membershipID: agent.membershipID };
105
- const generation = viewGeneration, button = $("#btnDesignateAgent"); button.disabled = true;
55
+ $("#editRoomForm").addEventListener("submit", async (event) => {
56
+ event.preventDefault();
57
+ const room = app.state.room; if (!room) return;
58
+ const name = $("#editRoomName").value.trim();
59
+ if (!name) { $("#editRoomStatus").textContent = app.t("roomNameRequired"); return; }
60
+ // Until the agent list loads, "None" is a placeholder, not a revocation.
61
+ const body = { sessionID: LS.sessionID, name, description: $("#editRoomDescription").value.trim(), ...(agentsReady ? { adminSessionID: $("#editRoomAdmin").value || null } : {}) };
62
+ const button = event.submitter; if (button) button.disabled = true;
106
63
  try {
107
- const existing = bindings.some((item) => item.roomId === roomId);
108
- const result = await app.adminApi(existing ? `/admin/rooms/${encodeURIComponent(roomId)}` : "/admin/rooms", { method: existing ? "PUT" : "POST", body: json(existing ? body : { roomId, ...body }) });
109
- if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value || agent.sessionID !== $("#adminTargetAgent").value) return;
110
- if (!existing) bindings.push(result.adminRoom); else bindings = bindings.map((item) => item.roomId === roomId ? result.adminRoom : item);
111
- setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
112
- await loadBinding(generation);
113
- if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value) return;
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("");
117
- } catch (error) { if (generation === viewGeneration) status(error.message, true); }
118
- finally { button.disabled = false; }
119
- });
120
- $("#btnRevokeAdmin").addEventListener("click", async () => {
121
- const id = $("#adminRoomSelect").value;
122
- if (!id || !confirm(app.t("revokeConfirm"))) return;
123
- const generation = viewGeneration, button = $("#btnRevokeAdmin"); button.disabled = true;
124
- try { await app.adminApi(`/admin/rooms/${encodeURIComponent(id)}`, { method: "DELETE", body: json({}) }); if (generation !== viewGeneration || id !== $("#adminRoomSelect").value) return; bindings = bindings.filter((item) => item.roomId !== id); setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = id; clearEnrollment(); await loadBinding(generation); }
125
- catch (error) { if (generation === viewGeneration) status(error.message, true); }
126
- finally { button.disabled = false; }
64
+ const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}`, { method: "PATCH", body: JSON.stringify(body) });
65
+ const meta = { name: updated.name, description: updated.description, adminSessionID: updated.adminSessionID, openQuestions: updated.openQuestions };
66
+ const entry = app.state.rooms.get(room.id);
67
+ if (entry) { Object.assign(entry.room, meta); app.state.room = entry.room; }
68
+ const listed = app.state.availableRooms?.find((item) => item.id === room.id);
69
+ if (listed) Object.assign(listed, meta);
70
+ app.renderHead();
71
+ app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
72
+ app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
73
+ app.cacheRoomSoon?.(room.id);
74
+ dialog.close();
75
+ } catch (error) { $("#editRoomStatus").textContent = error.message; }
76
+ finally { if (button) button.disabled = false; }
127
77
  });
128
- $("#inAdminToken").value = LS.adminToken;
129
- void verifyToken();
130
- }
78
+ }
@@ -57,7 +57,18 @@ export function editorSelectionOffsets(editor) {
57
57
  const selection = getSelection();
58
58
  if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return [editorText(editor).length, editorText(editor).length];
59
59
  const selected = selection.getRangeAt(0);
60
- const offset = (node, position) => lengthBefore(editor, node, position);
60
+ const offset = (node, position) => {
61
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
62
+ const chip = element?.closest(".editor-mention");
63
+ const raw = lengthBefore(editor, node, position);
64
+ if (chip && editor.contains(chip) && mentionName(chip) !== null) {
65
+ const start = lengthBefore(editor, chip, 0), end = start + `<at>@${mentionName(chip)}</at>`.length;
66
+ // A caret strictly inside a non-editable chip (e.g. left there by an
67
+ // ESC-cancelled IME composition) is not a text position; snap to the end.
68
+ if (raw > start && raw < end) return end;
69
+ }
70
+ return raw;
71
+ };
61
72
  return [offset(selected.startContainer, selected.startOffset), offset(selected.endContainer, selected.endOffset)];
62
73
  }
63
74
 
@@ -239,11 +250,25 @@ export function installEditor(editor) {
239
250
  editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
240
251
  editor.addEventListener("input", pruneTrustedChipNames);
241
252
  editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
253
+ editor.addEventListener("copy", (event) => {
254
+ const [start, end] = editorSelectionOffsets(editor);
255
+ if (start === end) return;
256
+ const text = editorText(editor).slice(start, end);
257
+ if (!text) return;
258
+ // Copy mentions in their token form so a paste rebuilds the same chips.
259
+ event.preventDefault();
260
+ event.clipboardData?.setData("text/plain", text);
261
+ if (/<at>@[^<]+<\/at>/.test(text)) event.clipboardData?.setData("text/html", `<div data-chatroom-mentions>${escapeHTML(text)}</div>`);
262
+ });
242
263
  editor.addEventListener("paste", (event) => {
243
264
  if (event.defaultPrevented || event.clipboardData?.files.length) return;
244
265
  event.preventDefault();
245
266
  const [start, end] = editorSelectionOffsets(editor);
246
- replaceEditorRange(editor, start, end, event.clipboardData?.getData("text/plain") || "", false);
267
+ const text = event.clipboardData?.getData("text/plain") || "";
268
+ // Rebuild chips only for copies this app marked; external text stays literal
269
+ // and keeps the native insert path, which handles newlines correctly.
270
+ const marked = (event.clipboardData?.getData("text/html") || "").includes("data-chatroom-mentions");
271
+ replaceEditorRange(editor, start, end, text, marked && /<at>@[^<]+<\/at>/.test(text));
247
272
  editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
248
273
  });
249
274
  editor.addEventListener("drop", (event) => {
@@ -255,7 +280,7 @@ export function installEditor(editor) {
255
280
  const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
256
281
  if (range && editor.contains(range.startContainer)) { selection.removeAllRanges(); selection.addRange(range); }
257
282
  const [start, end] = editorSelectionOffsets(editor);
258
- replaceEditorRange(editor, start, end, text, false);
283
+ replaceEditorRange(editor, start, end, text, html.includes("data-chatroom-mentions") && /<at>@[^<]+<\/at>/.test(text));
259
284
  editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
260
285
  });
261
286
  }
@@ -72,6 +72,9 @@ export function initEvents(app) {
72
72
  // Leaving at the bottom and returning to new messages lands on the first unread;
73
73
  // a deliberate scroll position is restored exactly.
74
74
  if ((entry?.unreadIds.size || entry?.unreadOverflow) && saved?.atBottom !== false && boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
75
+ // Left at the bottom with nothing unread: land on the live bottom, not the
76
+ // old anchor — late-loading cards can grow content below the saved row.
77
+ if (saved?.atBottom === true && !entry?.unreadIds.size && !entry?.unreadOverflow) { thread.scrollTop = thread.scrollHeight; captureReadingPosition(); return { messageId: readingPosition?.messageId, atBottom: atBottom() }; }
75
78
  if (saved?.messageId && align(saved.messageId, Number(saved.offset) || 0)) return { messageId: saved.messageId, atBottom: atBottom() };
76
79
  if (boundary && align(boundary.id, 0)) return { messageId: boundary.id, atBottom: atBottom() };
77
80
  if (!saved && !boundary) return false;
@@ -113,7 +116,8 @@ export function initEvents(app) {
113
116
  }
114
117
  syncRoomDrawer();
115
118
  window.addEventListener("resize", preserveReadingPosition);
116
- window.addEventListener("pagehide", captureReadingPosition);
119
+ window.addEventListener("pagehide", () => { captureReadingPosition(); app.flushReadOnHide?.(); });
120
+ document.addEventListener("visibilitychange", () => { if (document.hidden) { captureReadingPosition(); app.flushReadOnHide?.(); } });
117
121
  drawerTrigger.addEventListener("click", () => {
118
122
  if (roomRail.classList.contains("drawer-open")) return closeRoomDrawer();
119
123
  app.closePanels(); roomRail.inert = false; roomRail.removeAttribute("aria-hidden"); roomRail.classList.add("drawer-open");
@@ -218,7 +222,14 @@ export function initEvents(app) {
218
222
  }
219
223
  if (!event.isComposing) app.recomputeMention();
220
224
  });
221
- input.addEventListener("compositionend", () => app.recomputeMention(input));
225
+ input.addEventListener("compositionend", () => {
226
+ // An ESC-cancelled composition next to a chip can leave the caret inside the
227
+ // non-editable chip, which blocks typing; re-seat it in a real text node.
228
+ const anchor = getSelection()?.anchorNode;
229
+ const element = anchor?.nodeType === Node.ELEMENT_NODE ? anchor : anchor?.parentElement;
230
+ if (element?.closest(".editor-mention")) input.setCaret(input.selectionStart);
231
+ app.recomputeMention(input);
232
+ });
222
233
  input.addEventListener("keydown", (event) => handleMessageKey(event, app));
223
234
  input.addEventListener("keyup", (event) => {
224
235
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention();
@@ -255,6 +266,7 @@ export function initEvents(app) {
255
266
  app.queueReceiptRefresh();
256
267
  if (!adjusting) app.queueReceiptObservation();
257
268
  app.updateJump();
269
+ if (!adjusting && thread.scrollTop < 160) void app.loadOlderHistory?.();
258
270
  });
259
271
  document.addEventListener("visibilitychange", () => {
260
272
  if (!document.hidden) {
@@ -268,7 +280,7 @@ export function initEvents(app) {
268
280
  });
269
281
  $("#msgList").addEventListener("click", (event) => {
270
282
  const messageButton = event.target.closest("[data-copy-message]");
271
- if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
283
+ if (messageButton) void copyTextToClipboard(messageButton._copyText, true).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
272
284
  });
273
285
  ["#inRoomId", "#inName", "#inRoomName"].forEach((selector) => {
274
286
  $(selector).addEventListener("input", app.hideJoinError);
@@ -312,12 +324,12 @@ export function initEvents(app) {
312
324
  app.applyLocale();
313
325
  $("#inToken").value = LS.token;
314
326
  $("#inTokenChat").value = LS.token;
315
- void app.refreshRoomList();
327
+ void app.seedFromCache?.().finally(() => app.refreshRoomList());
316
328
  if (!$("#joinView").hidden) $("#inRoomId").focus();
317
329
  }
318
330
 
319
331
  async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, signal) {
320
- let beforeSeq;
332
+ let beforeSeq, reachedStart = false;
321
333
  const messages = [];
322
334
  while (!signal?.aborted) {
323
335
  const query = new URLSearchParams({ limit: "100" });
@@ -327,12 +339,15 @@ async function loadAnchorHistory(roomId, entry, messageId, app, readTs = 0, sign
327
339
  messages.push(...(result.messages || []));
328
340
  const found = messageId ? messages.some((message) => message.id === messageId)
329
341
  : messages.some((message) => message.createdAt > readTs) && messages.some((message) => message.createdAt <= readTs);
330
- if (found || !result.hasMore || !result.nextBeforeSeq || result.nextBeforeSeq === beforeSeq) break;
342
+ if (found || !result.hasMore || !result.nextBeforeSeq || result.nextBeforeSeq === beforeSeq) { reachedStart = !result.hasMore; break; }
331
343
  beforeSeq = result.nextBeforeSeq;
332
344
  }
333
345
  if (messageId ? !messages.some((message) => message.id === messageId) : !messages.some((message) => message.createdAt > readTs)) return;
334
346
  const merged = new Map([...entry.room.messages, ...messages].map((message) => [message.id, { ...message, roomId }]));
335
347
  entry.room.messages = [...merged.values()].sort((left, right) => left.createdAt - right.createdAt);
348
+ // Keep the upward-pagination cursor aligned with what the anchor load fetched.
349
+ if (typeof entry.room.messages[0]?.seq === "number") entry.historyBeforeSeq = entry.room.messages[0].seq;
350
+ if (reachedStart) entry.historyComplete = true;
336
351
  }
337
352
 
338
353
  function saveAccessToken(button, app) {
@@ -344,7 +359,6 @@ function saveAccessToken(button, app) {
344
359
  try { persistent = localStorage.getItem("chat.token") === LS.token; } catch { /* Memory fallback is tab-scoped. */ }
345
360
  app.flash(button, persistent ? "saved" : "savedMemory");
346
361
  void app.refreshRoomList();
347
- void app.verifyAdminToken?.();
348
362
  app.retryPendingAction();
349
363
  }
350
364