@alexsun-top/opencode-chat-room 0.5.1 → 0.5.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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.2 — 2026-11-10
4
+
5
+ - Add replies with linked message quotes, navigation to the original, and an automatic author mention. Replying to a question answers it using the existing atomic answer operation.
6
+ - Render pending questions as Markdown, enlarge the question panel, and provide a copy action. Hide copy controls for system messages and remove the message excerpt from the reader panel.
7
+ - Show mentions as atomic tokens while editing and preserve the existing message format when sending.
8
+ - Fix own messages being counted as unread by the background room watcher and refresh the jump button after a confirmed read.
9
+ - Include a bounded excerpt of the original question in answer notifications without changing the stored message.
10
+ - Show administrator-room indicators to authorized operators and clarify that a designated administrator manages all rooms.
11
+ - Add the `read_resource` room action to stream attachments into private temporary files for an Agent to inspect using its own tools.
12
+ - Raise the default server upload limit to 500 MiB per file; operators can still configure a different limit.
13
+ - Add persistent room reminders for one-time and CRON schedules, with member management and message templates.
14
+
3
15
  ## 0.5.1 — 2026-11-09
4
16
 
5
17
  - Refine the web chat visual system with a warmer light/dark palette, clearer typography, and more consistent message, composer, sidebar, attachment, and admin surfaces.
package/README.md CHANGED
@@ -80,17 +80,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
80
80
 
81
81
  ```bash
82
82
  # Show CLI options:
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --help
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --help
84
84
 
85
85
  # Start the local central server (choose any one runner):
86
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
- pnpx --package=@alexsun-top/opencode-chat-room@0.4.0 opencode-chat-room --host 0.0.0.0 --port 4399
88
- bunx @alexsun-top/opencode-chat-room@0.4.0 --host 0.0.0.0 --port 4399 --token secret
86
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
+ pnpx --package=@alexsun-top/opencode-chat-room@0.5.2 opencode-chat-room --host 0.0.0.0 --port 4399
88
+ bunx @alexsun-top/opencode-chat-room@0.5.2 --host 0.0.0.0 --port 4399 --token secret
89
89
 
90
90
  # Environment variables also work; CLI options take precedence:
91
91
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
92
92
  CHAT_ROOM_SERVER_TOKEN=secret \
93
- bunx @alexsun-top/opencode-chat-room@0.4.0
93
+ bunx @alexsun-top/opencode-chat-room@0.5.2
94
94
 
95
95
  # Local checkout:
96
96
  bun install
@@ -113,10 +113,16 @@ The central server uses a trusted shared-token model, not per-user authorization
113
113
 
114
114
  ### Question messages (0.4.0)
115
115
 
116
- Use `room` with `action: "send"`, `roomId`, `text`, and `isQuestion: true` to send a question. In web chat, enable **Question** before sending. Open the room's **Questions** panel to answer pending questions one at a time. Ordinary chat replies do not dismiss questions. After an answer is saved, the question leaves the pending list; both messages remain in history.
116
+ Use `room` with `action: "send"`, `roomId`, `text`, and `isQuestion: true` to send a question. In web chat, enable **Question** before sending. Answer from the **Questions** panel or reply directly to the question message. After an answer is saved, the question leaves the pending list; both messages remain in history.
117
117
 
118
118
  `GET /rooms/:roomId/questions` returns `{ questions }`, oldest first, including pending questions outside the visible history window. `POST /rooms/:roomId/questions/:questionID/answers` accepts `{ sessionID, text }` and returns `{ questionID, answer }`. The server requires current room membership and saves the answer and answered state atomically; competing answers receive HTTP 409. Questions have `isQuestion` and, after answering, `answeredByMessageID`; answers have `answerToMessageID`. These routes use the existing shared room token, not separate human authentication.
119
119
 
120
+ ### Room reminders
121
+
122
+ `GET /rooms/:roomId/reminders?sessionID=...`, `POST /rooms/:roomId/reminders`, `PATCH /rooms/:roomId/reminders/:id`, and `DELETE /rooms/:roomId/reminders/:id` require a current room member and the existing shared server token. Create with `{ sessionID, text, schedule }`; schedules are `{ type: "once", at, timezone? }` or `{ type: "cron", expression, timezone? }`. Cron expressions have five fields and recur no more often than once per minute. An omitted timezone uses the server's IANA timezone. Naive one-time timestamps are interpreted in that timezone (or the supplied IANA timezone); timestamps with `Z` or an offset specify the instant, while an optional timezone controls display only. Ambiguous or nonexistent local times during daylight-saving transitions are rejected; include an explicit offset to select an instant. `{time}` is rendered with the effective timezone and offset. The final rendered message must fit within 2,000 characters. Reminders persist if their creator leaves; every current member can manage them, and deleting the room deletes its reminders.
123
+
124
+ Agents use the `room` tool's `reminder_create`, `reminder_list`, `reminder_update`, and `reminder_delete` actions. Web members can manage reminders from the room header. Templates support `{time}`, `{initiator}`, and `{room}`. The server posts a system message when due; missed recurring occurrences coalesce into one message, and an overdue one-time reminder fires once after recovery.
125
+
120
126
  Version 0.4.0 requires an explicit non-empty `name` for `room`'s `join` action. Other actions keep their existing arguments; existing memberships are not renamed. Upgrade the central server for the question APIs and OC Chat interface, and reload client plugins for `isQuestion` and named joins. Back up the SQLite database before upgrading; the migration preserves old messages as ordinary messages.
121
127
 
122
128
  ### Room announcements
@@ -139,7 +145,9 @@ Unsent attachments are held in the current page and are cleared on reload. If se
139
145
 
140
146
  In central mode, an Agent can call `room` with `action: "upload_resource"`, `roomId`, and `filePath`. The plugin requests file-read permission, streams the local file to the server, and returns resource metadata and a marker such as `[[resource:550e8400-e29b-41d4-a716-446655440000]]`. Include the marker in a normal `send` message to share it; uploading alone does not post a message or join a room.
141
147
 
142
- The server-wide single-file limit defaults to 100 MiB (104,857,600 bytes). Configure `CHAT_ROOM_MAX_FILE_SIZE_MB` on the server to change it. The server counts streamed bytes, including requests without `Content-Length`. Uploads require room membership. Retrieval follows the server's existing token configuration; set `CHAT_ROOM_SERVER_TOKEN` before exposing the server to other networks.
148
+ To retrieve a room attachment, call `room` with `action: "read_resource"`, `roomId`, and the marker UUID as `resourceId`. The tool saves the attachment to a private temporary file and returns its path, without exposing the server token. The Agent can then decide whether to read it. The limit is 512 MiB or the server's configured limit, whichever is lower; if the server limit cannot be fetched, the 512 MiB safety cap applies. Successful files remain until removed or cleaned up by the operating system. Resource access uses the server's existing shared-token permissions.
149
+
150
+ The server-wide single-file limit defaults to 500 MiB (524,288,000 bytes). Configure `CHAT_ROOM_MAX_FILE_SIZE_MB` on the server to change it. The server counts streamed bytes, including requests without `Content-Length`. Uploads require room membership. Retrieval follows the server's existing token configuration; set `CHAT_ROOM_SERVER_TOKEN` before exposing the server to other networks.
143
151
 
144
152
  The browser offers downloads and on-demand previews for recognized raster images, audio, and video. Other formats, including SVG and HTML, are download-only. Playback depends on browser codec support. Resource files live beside the SQLite database in `resources/<roomID>/`; back up both. Room deletion removes its resources. Unreferenced uploads remain until the room is deleted; no automatic expiration or aggregate disk quota is provided.
145
153
 
package/README.zh-CN.md CHANGED
@@ -80,17 +80,17 @@ OpenCode 2.2.1 会在默认 60 分钟无活动后卸载闲置项目的服务。W
80
80
 
81
81
  ```bash
82
82
  # 查看 CLI 选项:
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --help
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --help
84
84
 
85
85
  # 启动本地中心服务器(三选一):
86
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
- pnpx --package=@alexsun-top/opencode-chat-room@0.4.0 opencode-chat-room --host 0.0.0.0 --port 4399
88
- bunx @alexsun-top/opencode-chat-room@0.4.0 --host 0.0.0.0 --port 4399 --token secret
86
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
+ pnpx --package=@alexsun-top/opencode-chat-room@0.5.2 opencode-chat-room --host 0.0.0.0 --port 4399
88
+ bunx @alexsun-top/opencode-chat-room@0.5.2 --host 0.0.0.0 --port 4399 --token secret
89
89
 
90
90
  # 也可以使用环境变量;CLI 参数优先:
91
91
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
92
92
  CHAT_ROOM_SERVER_TOKEN=secret \
93
- bunx @alexsun-top/opencode-chat-room@0.4.0
93
+ bunx @alexsun-top/opencode-chat-room@0.5.2
94
94
 
95
95
  # 本地 checkout:
96
96
  bun install
@@ -113,10 +113,16 @@ bun run server
113
113
 
114
114
  ### 问题消息(0.4.0)
115
115
 
116
- Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQuestion: true` 发送问题。网页发送前勾选“问题”,在当前房间的“问题”面板逐条回答。普通聊天回复不会自动消除问题;回答保存成功后,问题移出待回答列表,问题和回答仍保留在历史记录中。
116
+ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQuestion: true` 发送问题。网页发送前勾选“问题”;可以在“问题”面板回答,也可以直接回复问题消息。回答保存成功后,问题移出待回答列表,问题和回答仍保留在历史记录中。
117
117
 
118
118
  `GET /rooms/:roomId/questions` 返回 `{ questions }`,按时间从旧到新排列,包含可视历史窗口以外的未回答问题。`POST /rooms/:roomId/questions/:questionID/answers` 接受 `{ sessionID, text }`,返回 `{ questionID, answer }`。服务端要求当前房间成员身份,并原子保存回答和已回答状态;并发重复回答返回 HTTP 409。问题包含 `isQuestion`,回答后增加 `answeredByMessageID`;回答包含 `answerToMessageID`。接口沿用共享令牌,不提供独立的人类身份认证。
119
119
 
120
+ ### 房间提醒
121
+
122
+ 房间成员可在网页房间头部管理提醒;Agent 可通过 `room` 的 `reminder_create`、`reminder_list`、`reminder_update` 和 `reminder_delete` 操作管理。提醒支持一次性时间或五字段 CRON 表达式,模板可使用 `{time}`、`{initiator}` 和 `{room}`。到期时服务器向房间发送系统消息;错过的周期合并为一条,一次性提醒在服务器恢复后补发一次。创建者离房后提醒继续,删除房间时提醒一并删除。
123
+
124
+ 时区默认使用服务器时区,也可指定 IANA 时区。未带偏移的一次性时间按指定或服务器时区解释;带 `Z` 或偏移的时间表示明确时刻,指定的时区用于显示。夏令时中不存在或有歧义的本地时间会被拒绝,可用明确偏移指定时刻。提醒管理沿用共享令牌及房间成员权限。
125
+
120
126
  0.4.0 中,`room` 的 `join` 操作必须显式传入非空 `name`;其他操作参数不变,已有成员不会被改名。问题接口和 OC Chat 界面需升级中心服务器,`isQuestion` 和具名加入需重新加载客户端插件。升级前请备份 SQLite 数据库;迁移将旧消息保留为普通消息。
121
127
 
122
128
  ### 公告栏
@@ -139,7 +145,9 @@ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQues
139
145
 
140
146
  中心模式下,Agent 调用 `room`,传入 `action: "upload_resource"`、`roomId` 和本地 `filePath`。插件先申请文件读取权限,再流式上传,返回资源信息和 `[[resource:资源UUID]]` 标记。将标记放入普通 `send` 消息即可分享;上传本身不会发送消息或自动加入房间。
141
147
 
142
- 服务器默认单文件上限为 100 MiB(104857600 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
148
+ 获取房间附件时,调用 `room` 并传入 `action: "read_resource"`、`roomId` 和标记中的 UUID(`resourceId`)。工具将附件保存到私有临时文件并返回路径,不暴露服务器令牌;Agent 可自行决定是否读取该文件。单个附件上限为 512 MiB 和服务器配置上限中的较小值;无法获取服务器上限时使用 512 MiB 安全上限。成功下载的文件会保留到手动删除或操作系统清理临时目录。资源访问仍使用服务器现有的共享令牌权限。
149
+
150
+ 服务器默认单文件上限为 500 MiB(524288000 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
143
151
 
144
152
  网页支持识别到的栅格图片、音频和视频的按需预览,其他文件提供下载;SVG、HTML 不内嵌执行。播放能力取决于浏览器支持的编码。资源存放在 SQLite 数据库旁的 `resources/<roomID>/`,备份时须同时保留。删除房间会清理其资源;未引用的上传文件保留到房间删除,暂不提供自动过期或总磁盘配额。
145
153
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,6 +38,7 @@
38
38
  "server/admin-task-routes.ts",
39
39
  "server/admin-plan-routes.ts",
40
40
  "server/admin-scheduler.ts",
41
+ "server/room-reminders.ts",
41
42
  "server/wake.ts",
42
43
  "server/chat.html",
43
44
  "server/assets",
@@ -52,7 +53,7 @@
52
53
  },
53
54
  "scripts": {
54
55
  "server": "bun run server/chat-server.ts",
55
- "test": "bun test",
56
+ "test": "for file in src/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done",
56
57
  "typecheck": "tsc --noEmit"
57
58
  },
58
59
  "devDependencies": {
@@ -66,6 +67,7 @@
66
67
  "dependencies": {
67
68
  "@opencode-ai/plugin": "^1.18.29",
68
69
  "@opencode/client": "2.0.32",
70
+ "croner": "11.0.0",
69
71
  "zod": "4.1.8"
70
72
  }
71
73
  }
package/plugin.ts CHANGED
@@ -30,7 +30,9 @@ import { createV2Setup, type V2Runtime } from "./src/v2-plugin";
30
30
  import { createV1Server } from "./src/v1-plugin";
31
31
  import { runAnnouncementTool } from "./src/announcement-tool";
32
32
  import { uploadAgentResource } from "./src/resource-upload";
33
+ import { readAgentResource, resourceReadFailure } from "./src/resource-read";
33
34
  import { adminTool, adminToolDescription, adminToolSchema } from "./src/admin-client";
35
+ import { runReminderTool } from "./src/reminder-client";
34
36
  // ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
35
37
  // central server); unset = standalone local-file mode
36
38
  const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
@@ -243,15 +245,19 @@ export async function pollKnownSessions(
243
245
 
244
246
  const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "announcement_list", "announcement_read"]);
245
247
 
246
- const roomArgs = z.object({
247
- action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
248
+ export const roomArgs = z.object({
249
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
248
250
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
249
251
  roomId: z.string().optional(),
252
+ resourceId: z.string().optional(),
250
253
  filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
251
254
  text: z.string().max(2000).optional(),
252
255
  isQuestion: z.boolean().optional(),
253
256
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
254
257
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
258
+ reminderId: z.string().optional(),
259
+ schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
260
+ paused: z.boolean().optional(),
255
261
  }).superRefine((args, ctx) => {
256
262
  if (args.action === "join" && !args.name?.trim()) {
257
263
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
@@ -261,11 +267,20 @@ type RoomArguments = z.infer<typeof roomArgs>;
261
267
 
262
268
  const roomExecute = async (
263
269
  args: RoomArguments,
264
- context: V1ToolContext,
270
+ context: V1ToolContext & { signal?: AbortSignal },
265
271
  ) => {
266
272
  if (args.action === "join" && !args.name?.trim()) return "error: name is required to join a room";
267
273
  const runtime = currentRuntime();
274
+ if (args.action === "reminder_list" || args.action === "reminder_create" || args.action === "reminder_update" || args.action === "reminder_delete") {
275
+ return await runReminderTool(runtime.center, args, context.sessionID);
276
+ }
268
277
  if (args.action === "upload_resource") return uploadAgentResource(runtime.center, args.roomId ?? "", args.filePath ?? "", context.sessionID, context);
278
+ if (args.action === "read_resource") {
279
+ try {
280
+ if (!context.ask) return "error: host webfetch permission is unavailable";
281
+ return await readAgentResource(runtime.center, args.roomId ?? "", args.resourceId ?? "", context, context.abort ?? context.signal);
282
+ } catch (error) { return `error: ${resourceReadFailure(error)}`; }
283
+ }
269
284
  try {
270
285
  const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
271
286
  const receiverOwnerID = explicitV2Join && runtime.transport.verifySession
@@ -454,7 +469,7 @@ const roomExecute = async (
454
469
  }
455
470
  };
456
471
  const room = tool({
457
- description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
472
+ description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
458
473
  args: roomArgs.shape,
459
474
  execute: roomExecute,
460
475
  });
@@ -189,6 +189,16 @@
189
189
  .danger-text { color: var(--danger) !important; }
190
190
  .announcement-content { white-space: pre-wrap; overflow-wrap: anywhere; }
191
191
 
192
+ .panel.reminder-panel { width: min(410px, calc(100vw - 32px)); max-height: min(72dvh, 640px); overflow: auto; }
193
+ .reminder-form { border-top: 1px solid var(--line); padding-top: 10px; }
194
+ .reminder-form .field { margin: 0 0 9px; }
195
+ .reminder-form textarea { resize: vertical; }
196
+ .reminder-list { list-style: none; padding: 0; margin: 10px 0; display: grid; gap: 8px; }
197
+ .reminder-list li { padding: 9px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); }
198
+ .reminder-list p { margin: 0 0 6px; overflow-wrap: anywhere; }
199
+ .reminder-list .hint { margin: 2px 0 7px; }
200
+ .reminder-list .btn { margin: 0 6px 0 0; }
201
+
192
202
  .token-box { margin-top: 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
193
203
  .token-box summary {
194
204
  cursor: pointer;
@@ -8,6 +8,28 @@ export function initAdmin(app) {
8
8
  const select = (node, values, label, id = (item) => item.id) => {
9
9
  node.replaceChildren(new Option(label, ""), ...values.map((item) => new Option(item.name, id(item))));
10
10
  };
11
+ app.state.adminRoomIds = new Set();
12
+ const renderRoomOptions = app.renderRoomOptions;
13
+ app.renderRoomOptions = (list, available) => {
14
+ renderRoomOptions(list, available);
15
+ for (const button of list?.querySelectorAll(".room-row[data-room-id]") || []) {
16
+ if (!app.state.adminRoomIds.has(button.dataset.roomId)) continue;
17
+ const badge = document.createElement("span"); badge.className = "room-admin-badge"; badge.textContent = app.t("adminRoomBadge");
18
+ button.querySelector(".r-name")?.after(badge);
19
+ }
20
+ };
21
+ const renderHead = app.renderHead;
22
+ app.renderHead = () => {
23
+ renderHead();
24
+ const badge = $("#activeAdminBadge");
25
+ if (badge) badge.hidden = !app.state.adminRoomIds.has(app.state.room?.id);
26
+ };
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
+ }
11
33
  function renderAdminRooms() {
12
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)));
13
35
  }
@@ -15,9 +37,14 @@ export function initAdmin(app) {
15
37
  async function verifyToken() {
16
38
  const generation = ++tokenGeneration, token = LS.adminToken, error = $("#adminAccessError"), button = $("#btnOpenAdmin");
17
39
  error.hidden = true; button.hidden = true;
18
- if (!token) return;
19
- try { await app.adminApi("/admin/rooms"); if (generation === tokenGeneration && token === LS.adminToken) button.hidden = false; }
20
- catch (failure) { if (generation === tokenGeneration) { error.textContent = failure.message; error.hidden = false; } }
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
+ }
21
48
  }
22
49
  async function open() {
23
50
  const generation = ++viewGeneration;
@@ -29,7 +56,7 @@ export function initAdmin(app) {
29
56
  try {
30
57
  const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
31
58
  if (generation !== viewGeneration || !dialog.open) return;
32
- bindings = adminResult.rooms || []; rooms = roomResult || [];
59
+ bindings = adminResult.rooms || []; setAdminRooms(bindings); rooms = roomResult || [];
33
60
  renderAdminRooms();
34
61
  $("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
35
62
  select($("#adminTargetRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
@@ -38,7 +65,7 @@ export function initAdmin(app) {
38
65
  if (rooms.length) $("#adminTaskRoom").value = rooms[0].id;
39
66
  status(rooms.length ? "" : app.t("createAdminRoomFirst"));
40
67
  await Promise.all([loadDesignationAgents(), loadTaskAgents()]); await loadBinding(generation);
41
- } catch (error) { if (generation === viewGeneration) status(error.message, true); }
68
+ } catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
42
69
  finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#adminTargetRoom").disabled = $("#adminTargetAgent").disabled = false; $("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = false; } }
43
70
  }
44
71
  async function registryAgents(roomId) {
@@ -127,13 +154,13 @@ export function initAdmin(app) {
127
154
  catch (error) { if (generation === viewGeneration) status(error.message, true); }
128
155
  finally { button.disabled = false; }
129
156
  }
130
- $("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
157
+ $("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
131
158
  $("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
132
159
  $("#btnRefreshAdmin").addEventListener("click", async () => {
133
160
  const id = $("#adminRoomSelect").value;
134
161
  const generation = ++viewGeneration;
135
- try { const result = await app.adminApi("/admin/rooms"); if (generation !== viewGeneration || !dialog.open) return; bindings = result.rooms || []; renderAdminRooms(); $("#adminRoomSelect").value = id; await loadBinding(generation); }
136
- catch (error) { if (generation === viewGeneration) status(error.message, true); }
162
+ try { const result = await app.adminApi("/admin/rooms"); if (generation !== viewGeneration || !dialog.open) return; bindings = result.rooms || []; setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = id; await loadBinding(generation); }
163
+ catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
137
164
  });
138
165
  $("#btnCloseAdmin").addEventListener("click", () => dialog.close());
139
166
  dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); });
@@ -152,7 +179,7 @@ export function initAdmin(app) {
152
179
  const result = await app.adminApi(existing ? `/admin/rooms/${encodeURIComponent(roomId)}` : "/admin/rooms", { method: existing ? "PUT" : "POST", body: json(existing ? body : { roomId, ...body }) });
153
180
  if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value || body.targetRoomId !== $("#adminTargetRoom").value || agent.sessionID !== $("#adminTargetAgent").value) return;
154
181
  if (!existing) bindings.push(result.adminRoom); else bindings = bindings.map((item) => item.roomId === roomId ? result.adminRoom : item);
155
- renderAdminRooms(); $("#adminRoomSelect").value = roomId;
182
+ setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
156
183
  await loadBinding(generation);
157
184
  if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value || body.targetRoomId !== $("#adminTargetRoom").value) return;
158
185
  const box = $("#adminEnrollment"), instruction = document.createElement("code"), copy = document.createElement("button"), warning = document.createElement("p");
@@ -168,7 +195,7 @@ export function initAdmin(app) {
168
195
  const id = $("#adminRoomSelect").value;
169
196
  if (!id || !confirm(app.t("revokeConfirm"))) return;
170
197
  const generation = viewGeneration, button = $("#btnRevokeAdmin"); button.disabled = true;
171
- 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); renderAdminRooms(); $("#adminRoomSelect").value = id; clearEnrollment(); await loadBinding(generation); }
198
+ 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); }
172
199
  catch (error) { if (generation === viewGeneration) status(error.message, true); }
173
200
  finally { button.disabled = false; }
174
201
  });
@@ -173,7 +173,7 @@ export function initAttachments(app) {
173
173
  xhr.setRequestHeader("X-Session-ID", LS.sessionID);
174
174
  xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
175
175
  if (LS.token) xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
176
- xhr.timeout = 300000;
176
+ xhr.timeout = 1800000;
177
177
  xhr.upload.onprogress = (event) => {
178
178
  item.loaded = event.loaded; item.percent = Math.min(100, event.lengthComputable ? Math.floor(event.loaded / event.total * 100) : item.file.size ? Math.floor(event.loaded / item.file.size * 100) : 100);
179
179
  if (roomId() === id) {
@@ -0,0 +1,211 @@
1
+ import { createRandomId } from "./state.js";
2
+
3
+ const trustedChipNames = new Map();
4
+ function mentionName(node) {
5
+ const name = trustedChipNames.get(node.dataset?.chatChip);
6
+ return name !== undefined && node.dataset.mention === name && node.textContent === `@${name}` ? name : null;
7
+ }
8
+
9
+ export function editorText(editor, draft = false) {
10
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "BR") return "";
11
+ if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR") return "";
12
+ let value = "";
13
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
14
+ const walk = (node) => {
15
+ if (node.nodeType === Node.TEXT_NODE) value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
16
+ else if (node.nodeType === Node.ELEMENT_NODE) {
17
+ const mention = mentionName(node);
18
+ if (mention !== null) value += `<at>@${mention}</at>`;
19
+ else if (node.tagName === "BR") value += "\n";
20
+ else node.childNodes.forEach((child, index, all) => {
21
+ if (index && (block(child) || block(all[index - 1]))) value += "\n";
22
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) walk(child);
23
+ });
24
+ }
25
+ };
26
+ editor.childNodes.forEach((node, index, all) => {
27
+ if (index && (block(node) || block(all[index - 1]))) value += "\n";
28
+ if (!(block(node) && node.childNodes.length === 1 && node.firstChild.nodeName === "BR")) walk(node);
29
+ });
30
+ return value;
31
+ }
32
+
33
+ export const editorDraftText = (editor) => editorText(editor, true);
34
+ const literalMention = /<at>@([^<]+)<\/at>/g;
35
+ function encodeDraftText(text) { return String(text).replace(/\uE000/g, "\uE000\uE000").replace(literalMention, "\uE000$&"); }
36
+
37
+ export function setEditorText(editor, value, draft = false) {
38
+ editor.replaceChildren();
39
+ const pattern = draft ? /\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
40
+ let offset = 0, match;
41
+ while ((match = pattern.exec(String(value))) !== null) {
42
+ editor.append(document.createTextNode(String(value).slice(offset, match.index)));
43
+ if (draft && match[0] === "\uE000\uE000") { editor.append(document.createTextNode("\uE000")); offset = pattern.lastIndex; continue; }
44
+ if (draft && match[0].startsWith("\uE000")) { editor.append(document.createTextNode(match[0].slice(1))); offset = pattern.lastIndex; continue; }
45
+ const chip = document.createElement("span");
46
+ const name = match[draft ? 2 : 1];
47
+ chip.className = "editor-mention"; chip.dataset.mention = name;
48
+ chip.dataset.chatChip = createRandomId(); trustedChipNames.set(chip.dataset.chatChip, name);
49
+ chip.contentEditable = "false"; chip.setAttribute("role", "img");
50
+ chip.setAttribute("aria-label", `Mention ${name}`); chip.textContent = `@${name}`;
51
+ editor.append(chip); offset = pattern.lastIndex;
52
+ }
53
+ editor.append(document.createTextNode(String(value).slice(offset)));
54
+ pruneTrustedChipNames();
55
+ }
56
+
57
+ export function editorSelectionOffsets(editor) {
58
+ const selection = getSelection();
59
+ if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return [editorText(editor).length, editorText(editor).length];
60
+ const selected = selection.getRangeAt(0);
61
+ const offset = (node, position) => lengthBefore(editor, node, position);
62
+ return [offset(selected.startContainer, selected.startOffset), offset(selected.endContainer, selected.endOffset)];
63
+ }
64
+
65
+ function lengthBefore(root, target, position) {
66
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
67
+ const length = (node) => node.nodeType === Node.TEXT_NODE ? node.length
68
+ : mentionName(node) !== null ? `<at>@${mentionName(node)}</at>`.length
69
+ : node.tagName === "BR" ? 1 : childrenLength(node);
70
+ const childrenLength = (parent, until = parent.childNodes.length) => {
71
+ let sum = 0;
72
+ for (let index = 0; index < until; index++) {
73
+ const child = parent.childNodes[index];
74
+ if (index && (block(child) || block(parent.childNodes[index - 1]))) sum++;
75
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) sum += length(child);
76
+ }
77
+ return sum;
78
+ };
79
+ const visit = (node) => {
80
+ if (node === target) return node.nodeType === Node.TEXT_NODE ? Math.min(position, node.length)
81
+ : childrenLength(node, position);
82
+ let total = 0;
83
+ for (let index = 0; index < node.childNodes.length; index++) {
84
+ const child = node.childNodes[index];
85
+ if (index && (block(child) || block(node.childNodes[index - 1]))) total++;
86
+ if (child === target || child.contains(target)) return total + visit(child);
87
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) total += length(child);
88
+ }
89
+ return total;
90
+ };
91
+ return visit(root);
92
+ }
93
+
94
+ export function setCaret(editor, offset) {
95
+ const selection = getSelection(), range = document.createRange(), point = editorPoint(editor, offset);
96
+ range.setStart(point[0], point[1]); range.collapse(true);
97
+ selection.removeAllRanges(); selection.addRange(range);
98
+ }
99
+
100
+ export function setEditorSelection(editor, start, end = start) {
101
+ const range = document.createRange(), selection = getSelection();
102
+ const first = editorPoint(editor, start), last = editorPoint(editor, end);
103
+ range.setStart(first[0], first[1]); range.setEnd(last[0], last[1]);
104
+ selection.removeAllRanges(); selection.addRange(range);
105
+ }
106
+
107
+ function editorPoint(editor, offset) {
108
+ const last = editor.lastElementChild;
109
+ if (offset === editorText(editor).length && editor.lastChild === last && last?.tagName === "DIV" && last.firstChild?.nodeName === "BR") {
110
+ const text = last.appendChild(document.createTextNode("")); return [text, 0];
111
+ }
112
+ if (offset === editorText(editor).length && editor.lastChild?.nodeName === "BR") {
113
+ const text = editor.appendChild(document.createTextNode("")); return [text, 0];
114
+ }
115
+ const block = (node) => node.nodeType === Node.ELEMENT_NODE && node.tagName === "DIV";
116
+ let left = offset, point = null;
117
+ const visit = (node) => {
118
+ if (point) return;
119
+ if (node.nodeType === Node.TEXT_NODE) {
120
+ if (left <= node.length) point = [node, left]; else left -= node.length;
121
+ } else if (node.nodeType === Node.ELEMENT_NODE && mentionName(node) !== null) {
122
+ const index = [...node.parentNode.childNodes].indexOf(node), length = `<at>@${mentionName(node)}</at>`.length;
123
+ if (left <= length) point = [node.parentNode, index + (left ? 1 : 0)]; else left -= length;
124
+ } else if (node.tagName === "BR") {
125
+ const index = [...node.parentNode.childNodes].indexOf(node);
126
+ if (left <= 1) point = [node.parentNode, index + (left ? 1 : 0)]; else left--;
127
+ } else node.childNodes.forEach((child, index, all) => {
128
+ if (index && (block(child) || block(all[index - 1]))) {
129
+ if (left === 0) { point = [node, index]; return; }
130
+ left--;
131
+ }
132
+ if (!(block(child) && child.childNodes.length === 1 && child.firstChild.nodeName === "BR")) visit(child);
133
+ });
134
+ };
135
+ visit(editor);
136
+ if (point) return point;
137
+ const node = editor.appendChild(document.createTextNode("")); return [node, 0];
138
+ }
139
+
140
+ export function replaceEditorRange(editor, start, end, value, parseMentions = true) {
141
+ setEditorSelection(editor, start, end);
142
+ if (!parseMentions && document.execCommand("insertText", false, String(value))) return;
143
+ const marker = `chat-insert-${createRandomId()}`;
144
+ const source = String(value), token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
145
+ let html = "", cursor = 0, match;
146
+ while (token && (match = token.exec(source))) {
147
+ html += textHTML(source.slice(cursor, match.index));
148
+ const name = escapeHTML(match[1]);
149
+ const chipID = createRandomId(); trustedChipNames.set(chipID, match[1]);
150
+ html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${name}">@${name}</span>`;
151
+ cursor = token.lastIndex;
152
+ }
153
+ html += textHTML(source.slice(cursor));
154
+ if (document.execCommand("insertHTML", false, html)) {
155
+ editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
156
+ setCaret(editor, start + source.length);
157
+ pruneTrustedChipNames();
158
+ } else {
159
+ const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
160
+ if (parseMentions) setEditorText(editor, next); else editor.replaceChildren(document.createTextNode(next));
161
+ setCaret(editor, start + value.length);
162
+ pruneTrustedChipNames();
163
+ }
164
+ }
165
+
166
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]); }
167
+ function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
168
+
169
+ function pruneTrustedChipNames() {
170
+ const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
171
+ const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
172
+ // shortcut: retain 2,048 detached IDs for undo history; raise if longer histories are required.
173
+ stale.slice(0, Math.max(0, stale.length - 2048)).forEach((id) => trustedChipNames.delete(id));
174
+ }
175
+
176
+ export function installEditor(editor) {
177
+ Object.defineProperty(editor, "value", {
178
+ get: () => editorText(editor), set: (value) => setEditorText(editor, value),
179
+ });
180
+ Object.defineProperty(editor, "draftValue", {
181
+ get: () => editorDraftText(editor), set: (value) => setEditorText(editor, value, true),
182
+ });
183
+ Object.defineProperties(editor, {
184
+ selectionStart: { get: () => editorSelectionOffsets(editor)[0] },
185
+ selectionEnd: { get: () => editorSelectionOffsets(editor)[1] },
186
+ });
187
+ editor.getSelectionOffsets = () => editorSelectionOffsets(editor);
188
+ editor.setCaret = (offset) => setCaret(editor, offset);
189
+ editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
190
+ editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
191
+ editor.addEventListener("input", pruneTrustedChipNames);
192
+ editor.addEventListener("paste", (event) => {
193
+ if (event.defaultPrevented || event.clipboardData?.files.length) return;
194
+ event.preventDefault();
195
+ const [start, end] = editorSelectionOffsets(editor);
196
+ replaceEditorRange(editor, start, end, event.clipboardData?.getData("text/plain") || "", false);
197
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));
198
+ });
199
+ editor.addEventListener("drop", (event) => {
200
+ if (event.defaultPrevented || event.dataTransfer?.files.length) return;
201
+ const html = event.dataTransfer?.getData("text/html") || "";
202
+ const text = event.dataTransfer?.getData("text/plain") || new DOMParser().parseFromString(html, "text/html").body.textContent || "";
203
+ if (!text) return;
204
+ event.preventDefault();
205
+ const range = document.caretRangeFromPoint?.(event.clientX, event.clientY), selection = getSelection();
206
+ if (range && editor.contains(range.startContainer)) { selection.removeAllRanges(); selection.addRange(range); }
207
+ const [start, end] = editorSelectionOffsets(editor);
208
+ replaceEditorRange(editor, start, end, text, false);
209
+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromDrop" }));
210
+ });
211
+ }
@@ -193,17 +193,18 @@ export function initEvents(app) {
193
193
  if (failedAction === "retry") void app.retryFailedMessage(failedRoom, failedId);
194
194
  else app.discardFailedMessage(failedRoom, failedId);
195
195
  });
196
- input.addEventListener("input", () => {
196
+ input.addEventListener("input", (event) => {
197
197
  app.autoGrow(input);
198
198
  app.updateSendState();
199
199
  app.updateDraftCount();
200
200
  if (app.state.room) {
201
201
  const id = app.state.room.id;
202
202
  app.state.draftRevision.set(id, (app.state.draftRevision.get(id) || 0) + 1);
203
- app.saveDraft(id, input.value);
203
+ app.saveDraft(id, input.draftValue);
204
204
  }
205
- app.recomputeMention();
205
+ if (!event.isComposing) app.recomputeMention();
206
206
  });
207
+ input.addEventListener("compositionend", () => app.recomputeMention(input));
207
208
  input.addEventListener("keydown", (event) => handleMessageKey(event, app));
208
209
  input.addEventListener("keyup", (event) => {
209
210
  if (app.mentionActive && /^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) app.recomputeMention();
@@ -330,7 +331,8 @@ function saveAccessToken(button, app) {
330
331
  }
331
332
 
332
333
  function handleMessageKey(event, app) {
333
- if (app.mentionActive && !event.isComposing) {
334
+ if (app.handleMentionKey(event, event.currentTarget)) return;
335
+ if (app.mentionActive && !event.isComposing && event.keyCode !== 229) {
334
336
  if (event.key === "ArrowDown") { event.preventDefault(); app.moveMention(1); return; }
335
337
  if (event.key === "ArrowUp") { event.preventDefault(); app.moveMention(-1); return; }
336
338
  if (event.key === "Escape") { event.preventDefault(); app.closeMention(); return; }
@@ -344,7 +346,7 @@ function handleMessageKey(event, app) {
344
346
  if (event.key === "Tab") return;
345
347
  }
346
348
  }
347
- if (event.key === "Enter" && !event.isComposing && (event.ctrlKey || !event.shiftKey)) {
349
+ if (event.key === "Enter" && !event.isComposing && event.keyCode !== 229 && (event.ctrlKey || !event.shiftKey)) {
348
350
  event.preventDefault();
349
351
  void app.send();
350
352
  }
@@ -9,6 +9,8 @@ import { initReceipts } from "./receipts.js";
9
9
  import { initAnnouncements } from "./announcements.js";
10
10
  import { initAdmin } from "./admin.js";
11
11
  import { initAttachments } from "./attachments.js";
12
+ import { initReplies } from "./replies.js";
13
+ import { initReminders } from "./reminders.js";
12
14
 
13
15
  initMentions(app);
14
16
  initMessages(app);
@@ -17,6 +19,8 @@ initReceipts(app);
17
19
  initMembers(app);
18
20
  initRooms(app);
19
21
  initQuestions(app);
22
+ initReplies(app);
20
23
  initEvents(app);
21
24
  initAnnouncements(app);
25
+ initReminders(app);
22
26
  initAdmin(app);