@alexsun-top/opencode-chat-room 0.5.2 → 0.5.4
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 +29 -0
- package/README.md +28 -215
- package/README.zh-CN.md +27 -209
- package/docs/administrator-rooms.md +6 -22
- package/package.json +1 -4
- package/plugin.ts +1 -1
- package/server/admin-auth.ts +4 -2
- package/server/admin-routes.ts +2 -11
- package/server/admin-state.ts +15 -4
- package/server/assets/base.css +1 -1
- package/server/assets/chat/admin.js +30 -123
- package/server/assets/chat/announcements.js +17 -1
- package/server/assets/chat/attachments.js +4 -1
- package/server/assets/chat/editor.js +65 -15
- package/server/assets/chat/events.js +12 -7
- package/server/assets/chat/markdown.js +31 -11
- package/server/assets/chat/mentions.js +3 -1
- package/server/assets/chat/messages.js +55 -20
- package/server/assets/chat/questions.js +15 -4
- package/server/assets/chat/reminders.js +4 -3
- package/server/assets/chat/replies.js +2 -1
- package/server/assets/chat/room-watcher.js +45 -0
- package/server/assets/chat/rooms.js +62 -69
- package/server/assets/chat/state.js +8 -6
- package/server/assets/conversation.css +8 -5
- package/server/assets/responsive.css +5 -12
- package/server/chat-server.ts +26 -37
- package/server/chat.html +3 -10
- package/server/member-routes.ts +9 -11
- package/server/room-reminders.ts +15 -5
- package/server/wake.ts +11 -2
- package/skills/chatroom/SKILL.md +3 -7
- package/src/admin-client.ts +8 -45
- package/src/admin-credentials.ts +0 -19
- package/src/center-inbox.ts +0 -2
- package/src/mentions.ts +2 -1
- package/src/plugin-notifications.ts +4 -3
- package/src/resource-upload.ts +1 -1
- package/src/resources.ts +4 -1
- package/src/sqlite-state.ts +40 -0
- package/src/store.ts +4 -1
- package/src/v2-plugin.ts +1 -1
- package/server/admin-plan-routes.ts +0 -79
- package/server/admin-scheduler.ts +0 -42
- package/server/admin-task-routes.ts +0 -182
- package/src/supervision-inbox.ts +0 -62
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Administrator rooms
|
|
2
2
|
|
|
3
|
-
An administrator room is a normal group room with one operator-designated Agent. That Agent can inspect
|
|
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.
|
|
4
4
|
|
|
5
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.
|
|
6
6
|
|
|
@@ -17,35 +17,19 @@ The plugin binds the claim to its native session and receiver owner. It stores t
|
|
|
17
17
|
|
|
18
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.
|
|
19
19
|
|
|
20
|
-
##
|
|
20
|
+
## Inspect rooms and assign work
|
|
21
21
|
|
|
22
|
-
The `admin` tool uses `roomId` for the administrator room
|
|
22
|
+
The `admin` tool uses `roomId` for the administrator room.
|
|
23
23
|
|
|
24
24
|
| Action | Additional arguments | Purpose |
|
|
25
25
|
| --- | --- | --- |
|
|
26
|
-
| `admin_overview` | None | Inspect rooms
|
|
26
|
+
| `admin_overview` | None | Inspect rooms and members |
|
|
27
27
|
| `admin_history` | `targetRoomId`, optional `limit` | Inspect bounded target-room history |
|
|
28
|
-
| `admin_dispatch` | `targetRoomId`, `targetSessionID`, `text` | Create a task for an existing Agent |
|
|
29
|
-
| `admin_tasks` | None | List tracked tasks |
|
|
30
|
-
| `admin_task_update` | `taskId`, `status`, optional `progress` | Record task progress and blockers |
|
|
31
|
-
| `admin_plans` | None | Inspect recurring supervision plans |
|
|
32
|
-
| `admin_plan_create` | `name`, `intervalSeconds`, `text` | Schedule checks of work progress |
|
|
33
|
-
| `admin_plan_update` | `planId`, `paused` | Pause or resume a plan |
|
|
34
|
-
| `admin_plan_delete` | `planId` | Remove a plan |
|
|
35
|
-
| `task_progress` | `taskId`, `status`, `progress` | Let the assigned worker report progress without administrator privileges |
|
|
36
28
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
Workers receive the task ID and reporting instructions with their assignment. The plugin retains a task-scoped reporting token privately, before delivering the assignment to the host. Progress reports use the worker's native session and receiver owner; they do not require the administrator's capability or operator token. The token is not part of the prompt.
|
|
40
|
-
|
|
41
|
-
Worker delivery remains inside the existing shared-server-token trust domain: a client holding that token can impersonate another client's routing IDs and obtain its worker assignment. Worker status is therefore self-reported information, not independent authenticated evidence. Global supervisor reminders require the designated Agent's capability for both retrieval and acknowledgement.
|
|
42
|
-
|
|
43
|
-
Cancelling queued work prevents later delivery and revokes its progress token. Instructions already accepted by a host cannot be recalled; coordinate cancellation with the worker when execution may already have started.
|
|
44
|
-
|
|
45
|
-
The server persists schedules and pending deliveries. Reminders steer the designated supervisor; offline periods are coalesced rather than replayed as a backlog of reminders. The host must be available to execute an Agent. A timer firing, a host accepting a steer, and an Agent completing work are separate events.
|
|
29
|
+
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.
|
|
46
30
|
|
|
47
31
|
## Security and operations
|
|
48
32
|
|
|
49
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.
|
|
50
34
|
|
|
51
|
-
Back up server SQLite state to preserve designations,
|
|
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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexsun-top/opencode-chat-room",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.4",
|
|
4
4
|
"description": "A chat-room plugin and central server for OpenCode.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,9 +35,6 @@
|
|
|
35
35
|
"server/admin-routes.ts",
|
|
36
36
|
"server/admin-state.ts",
|
|
37
37
|
"server/admin-auth.ts",
|
|
38
|
-
"server/admin-task-routes.ts",
|
|
39
|
-
"server/admin-plan-routes.ts",
|
|
40
|
-
"server/admin-scheduler.ts",
|
|
41
38
|
"server/room-reminders.ts",
|
|
42
39
|
"server/wake.ts",
|
|
43
40
|
"server/chat.html",
|
package/plugin.ts
CHANGED
|
@@ -469,7 +469,7 @@ const roomExecute = async (
|
|
|
469
469
|
}
|
|
470
470
|
};
|
|
471
471
|
const room = tool({
|
|
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.",
|
|
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; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
|
|
473
473
|
args: roomArgs.shape,
|
|
474
474
|
execute: roomExecute,
|
|
475
475
|
});
|
package/server/admin-auth.ts
CHANGED
|
@@ -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
|
-
|
|
15
|
-
|
|
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
|
}
|
package/server/admin-routes.ts
CHANGED
|
@@ -1,25 +1,18 @@
|
|
|
1
1
|
import { databasePath } from "../src/store";
|
|
2
2
|
import { readHistoryPage } from "../src/sqlite-state";
|
|
3
3
|
import { adminEnabled, hasAdminCapability, isOperator } from "./admin-auth";
|
|
4
|
-
import { adminPlanRoutes } from "./admin-plan-routes";
|
|
5
|
-
import { adminTaskRoutes } from "./admin-task-routes";
|
|
6
4
|
import { binding, digest, ensureAdminSchema, exec, isAgentMember, many, matchesHash, newSecret, one, publicRoom, tx, validCurrent, enroll } from "./admin-state";
|
|
7
5
|
import type { Binding } from "./admin-state";
|
|
8
|
-
import { startAdminScheduler } from "./admin-scheduler";
|
|
9
6
|
|
|
10
7
|
const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
|
|
11
8
|
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
12
|
-
|
|
9
|
+
await ensureAdminSchema();
|
|
13
10
|
|
|
14
11
|
export async function adminRoutes(request: Request, url: URL): Promise<Response | undefined> {
|
|
15
12
|
if (!url.pathname.startsWith("/admin/") && !url.pathname.startsWith("/supervision/")) return undefined;
|
|
16
13
|
if (!adminEnabled) return json({ error: "admin API is disabled" }, 503);
|
|
17
14
|
try {
|
|
18
15
|
await ensureAdminSchema();
|
|
19
|
-
const task = await adminTaskRoutes(request, url);
|
|
20
|
-
if (task) return task;
|
|
21
|
-
const plan = await adminPlanRoutes(request, url);
|
|
22
|
-
if (plan) return plan;
|
|
23
16
|
return await rootRoutes(request, url);
|
|
24
17
|
} catch (error) {
|
|
25
18
|
if (error instanceof SyntaxError || error instanceof URIError) return json({ error: "invalid request" }, 400);
|
|
@@ -126,9 +119,7 @@ async function overview(request: Request, roomID: string): Promise<Response> {
|
|
|
126
119
|
if (!isOperator(request) && !validCurrent(db, b)) return { status: 409 as const };
|
|
127
120
|
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")
|
|
128
121
|
.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) }));
|
|
129
|
-
|
|
130
|
-
const plans = many(db, "SELECT id,admin_room_id AS adminRoomId,name,interval_seconds AS intervalSeconds,text,paused,next_run_at AS nextRunAt,created_at AS createdAt FROM admin_plans WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", roomID);
|
|
131
|
-
return { rooms, tasks, plans };
|
|
122
|
+
return { rooms };
|
|
132
123
|
});
|
|
133
124
|
return "status" in result ? json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json(result);
|
|
134
125
|
}
|
package/server/admin-state.ts
CHANGED
|
@@ -20,7 +20,21 @@ export function matchesHash(value: string, stored: string): boolean {
|
|
|
20
20
|
const left = Buffer.from(hash(value), "hex"), right = Buffer.from(stored, "hex");
|
|
21
21
|
return right.length === 32 && timingSafeEqual(left, right);
|
|
22
22
|
}
|
|
23
|
-
export async function ensureAdminSchema() {
|
|
23
|
+
export async function ensureAdminSchema() {
|
|
24
|
+
const file = databasePath();
|
|
25
|
+
const migrated = await withStateTransaction(file, db => {
|
|
26
|
+
db.exec("CREATE TABLE IF NOT EXISTS server_admin_migrations(version INTEGER PRIMARY KEY,applied_at INTEGER NOT NULL)");
|
|
27
|
+
return !!db.query("SELECT 1 FROM server_admin_migrations WHERE version=1").get();
|
|
28
|
+
});
|
|
29
|
+
if (migrated) return;
|
|
30
|
+
await initializeAdminSchema(file);
|
|
31
|
+
await withStateTransaction(file, db => {
|
|
32
|
+
if (db.query("SELECT 1 FROM server_admin_migrations WHERE version=1").get()) return;
|
|
33
|
+
// Legacy route producers used only task and supervision delivery kinds.
|
|
34
|
+
db.exec("DELETE FROM admin_deliveries WHERE kind IN ('task','supervision'); DELETE FROM admin_tasks; DELETE FROM admin_plans;");
|
|
35
|
+
db.query("INSERT INTO server_admin_migrations(version,applied_at) VALUES(1,?)").run(Date.now());
|
|
36
|
+
});
|
|
37
|
+
}
|
|
24
38
|
export async function tx<T>(fn: (db: Database) => T) { await ensureAdminSchema(); return withStateTransaction(databasePath(), fn); }
|
|
25
39
|
export function publicRoom(b: Binding): AdminRoom { return { roomId: b.room_id, targetRoomId: b.target_room_id, sessionID: b.session_id, receiverOwnerID: b.receiver_owner_id, membershipID: b.membership_id, generation: b.generation, enrolled: Boolean(b.capability_hash), createdAt: b.created_at }; }
|
|
26
40
|
export function binding(db: Database, roomID: string) { return row<Binding>(db, "SELECT * FROM admin_rooms WHERE room_id=?", roomID); }
|
|
@@ -39,9 +53,6 @@ export function enroll(db: Database, roomID: string, targetRoomID: string, sessi
|
|
|
39
53
|
run(db, `INSERT INTO admin_rooms(room_id,target_room_id,session_id,receiver_owner_id,membership_id,generation,enrollment_hash,enrollment_expires,capability_hash,created_at)
|
|
40
54
|
VALUES(?,?,?,?,?,?,?,?,NULL,?) ON CONFLICT(room_id) DO UPDATE SET target_room_id=excluded.target_room_id,session_id=excluded.session_id,receiver_owner_id=excluded.receiver_owner_id,membership_id=excluded.membership_id,generation=excluded.generation,enrollment_hash=excluded.enrollment_hash,enrollment_expires=excluded.enrollment_expires,capability_hash=NULL`,
|
|
41
55
|
roomID, targetRoomID, sessionID, ownerID, membershipID, generation, hash(nextKey), expiresAt, createdAt);
|
|
42
|
-
run(db, "UPDATE admin_tasks SET status='cancelled',delivery_token_hash='',updated_at=? WHERE admin_room_id=? AND status IN ('pending','working','blocked')", Date.now(), roomID);
|
|
43
|
-
run(db, "DELETE FROM admin_deliveries WHERE admin_room_id=?", roomID);
|
|
44
|
-
run(db, "UPDATE admin_plans SET paused=1 WHERE admin_room_id=?", roomID);
|
|
45
56
|
return { enrollmentKey: nextKey, expiresAt };
|
|
46
57
|
}
|
|
47
58
|
export function isAgentMember(db: Database, roomID: string, sessionID: string, ownerID: string, membershipID: string) {
|
package/server/assets/base.css
CHANGED
|
@@ -2,7 +2,7 @@ import { LS } from "./state.js";
|
|
|
2
2
|
|
|
3
3
|
export function initAdmin(app) {
|
|
4
4
|
const $ = app.$, dialog = $("#adminDialog");
|
|
5
|
-
let rooms = [], bindings = [], agents = [],
|
|
5
|
+
let rooms = [], bindings = [], agents = [], viewGeneration = 0, designationGeneration = 0, tokenGeneration = 0;
|
|
6
6
|
const status = (text, error = false) => { $("#adminStatus").textContent = text; $("#adminStatus").classList.toggle("danger-text", error); };
|
|
7
7
|
const json = (body) => JSON.stringify(body);
|
|
8
8
|
const select = (node, values, label, id = (item) => item.id) => {
|
|
@@ -48,146 +48,72 @@ export function initAdmin(app) {
|
|
|
48
48
|
}
|
|
49
49
|
async function open() {
|
|
50
50
|
const generation = ++viewGeneration;
|
|
51
|
-
clearEnrollment();
|
|
51
|
+
clearEnrollment();
|
|
52
52
|
dialog.showModal(); status(app.t("adminLoading"));
|
|
53
|
-
$("#adminRoomSelect").disabled = $("#
|
|
54
|
-
$("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = true;
|
|
55
|
-
$("#btnRevokeAdmin").hidden = $("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
53
|
+
$("#adminRoomSelect").disabled = $("#adminTargetAgent").disabled = $("#btnDesignateAgent").disabled = true; $("#btnRevokeAdmin").hidden = true;
|
|
56
54
|
try {
|
|
57
55
|
const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
|
|
58
56
|
if (generation !== viewGeneration || !dialog.open) return;
|
|
59
57
|
bindings = adminResult.rooms || []; setAdminRooms(bindings); rooms = roomResult || [];
|
|
60
58
|
renderAdminRooms();
|
|
61
59
|
$("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
|
|
62
|
-
|
|
63
|
-
select($("#adminTaskRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
|
|
64
|
-
if (rooms.length) $("#adminTargetRoom").value = rooms[0].id;
|
|
65
|
-
if (rooms.length) $("#adminTaskRoom").value = rooms[0].id;
|
|
66
|
-
status(rooms.length ? "" : app.t("createAdminRoomFirst"));
|
|
67
|
-
await Promise.all([loadDesignationAgents(), loadTaskAgents()]); await loadBinding(generation);
|
|
60
|
+
status(""); await loadBinding(generation);
|
|
68
61
|
} catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
|
|
69
|
-
finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#
|
|
62
|
+
finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#adminTargetAgent").disabled = false; } }
|
|
70
63
|
}
|
|
71
64
|
async function registryAgents(roomId) {
|
|
72
|
-
return roomId ? Object.entries(await app.api(`/rooms/${encodeURIComponent(roomId)}/registry`)).map(([sessionID, value]) => ({ sessionID, ...value })).filter((agent) => agent.membershipID) : [];
|
|
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)) : [];
|
|
73
66
|
}
|
|
74
67
|
async function loadDesignationAgents() {
|
|
75
|
-
const generation = ++designationGeneration, roomId = $("#
|
|
76
|
-
agents = []; $("#adminTargetAgent").disabled = true; select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
68
|
+
const generation = ++designationGeneration, roomId = $("#adminRoomSelect").value;
|
|
69
|
+
agents = []; $("#adminTargetAgent").disabled = $("#btnDesignateAgent").disabled = true; select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
77
70
|
try {
|
|
78
71
|
const found = await registryAgents(roomId);
|
|
79
|
-
if (generation !== designationGeneration || roomId !== $("#
|
|
80
|
-
agents = found; select($("#adminTargetAgent"), agents
|
|
81
|
-
} catch (error) { if (generation === designationGeneration) status(error.message, true); }
|
|
82
|
-
}
|
|
83
|
-
async function loadTaskAgents() {
|
|
84
|
-
const generation = ++taskGeneration, roomId = $("#adminTaskRoom").value;
|
|
85
|
-
taskAgents = []; $("#adminTaskAgent").disabled = true; select($("#adminTaskAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
86
|
-
try {
|
|
87
|
-
const found = await registryAgents(roomId);
|
|
88
|
-
if (generation !== taskGeneration || roomId !== $("#adminTaskRoom").value) return;
|
|
89
|
-
taskAgents = found; select($("#adminTaskAgent"), taskAgents.map((agent) => ({ ...agent, name: `${agent.name} · ${agent.sessionID.slice(0, 8)}` })), app.t("chooseAgent"), (agent) => agent.sessionID); $("#adminTaskAgent").disabled = false;
|
|
90
|
-
} catch (error) { if (generation === taskGeneration) status(error.message, true); }
|
|
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; } }
|
|
91
75
|
}
|
|
92
76
|
async function loadBinding(generation = ++viewGeneration) {
|
|
93
77
|
const id = $("#adminRoomSelect").value;
|
|
94
78
|
const binding = bindings.find((item) => item.roomId === id);
|
|
95
|
-
$("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
|
|
96
|
-
$("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
97
79
|
$("#btnRevokeAdmin").hidden = !binding;
|
|
98
|
-
if (!id
|
|
99
|
-
$("#adminTargetRoom").value = binding.targetRoomId;
|
|
100
|
-
const targetRoomId = binding.targetRoomId;
|
|
80
|
+
if (!id) { agents = []; $("#btnDesignateAgent").disabled = true; status(app.t("createAdminRoomFirst")); select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID); return; }
|
|
101
81
|
await loadDesignationAgents();
|
|
102
|
-
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value ||
|
|
103
|
-
$("#adminTargetAgent").value = binding.sessionID;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const [overview, tasks, plans] = await Promise.all([app.adminApi(`${base}/overview`), app.adminApi(`${base}/tasks`), app.adminApi(`${base}/plans`)]);
|
|
107
|
-
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || !dialog.open) return;
|
|
108
|
-
renderData({ overview, tasks: tasks.tasks, plans: plans.plans }, id);
|
|
109
|
-
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
110
|
-
}
|
|
111
|
-
function renderData(data, id) {
|
|
112
|
-
const overview = $("#adminOverview"); overview.replaceChildren();
|
|
113
|
-
for (const room of data.overview?.rooms || []) {
|
|
114
|
-
const item = document.createElement("p");
|
|
115
|
-
item.textContent = `${room.name}: ${(room.members || []).map((member) => `${member.name} (${member.workState || "unknown"})`).join(", ") || app.t("noAgents")}`;
|
|
116
|
-
overview.append(item);
|
|
117
|
-
}
|
|
118
|
-
const binding = bindings.find((item) => item.roomId === id);
|
|
119
|
-
$("#adminTaskForm").hidden = !binding; $("#adminPlanForm").hidden = !binding;
|
|
120
|
-
renderTasks(data.tasks || [], id); renderPlans(data.plans || [], id);
|
|
121
|
-
}
|
|
122
|
-
function renderTasks(tasks, roomId) {
|
|
123
|
-
const list = $("#adminTaskList"); list.replaceChildren();
|
|
124
|
-
for (const task of tasks) {
|
|
125
|
-
const row = document.createElement("li"), title = document.createElement("p"), state = document.createElement("select"), progress = document.createElement("textarea"), save = document.createElement("button");
|
|
126
|
-
title.textContent = task.text; state.className = "admin-select";
|
|
127
|
-
for (const value of ["pending", "working", "blocked", "completed", "cancelled"]) state.add(new Option(app.t(`task_${value}`), value));
|
|
128
|
-
state.value = task.status; progress.className = "input"; progress.rows = 2; progress.value = task.progress || "";
|
|
129
|
-
save.className = "btn ghost small"; save.type = "button"; save.textContent = app.t("updateTask");
|
|
130
|
-
save.addEventListener("click", async () => {
|
|
131
|
-
const generation = viewGeneration, nextStatus = state.value, nextProgress = progress.value; save.disabled = true;
|
|
132
|
-
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/tasks/${encodeURIComponent(task.id)}`, { method: "PATCH", body: json({ status: nextStatus, progress: nextProgress }) }); if (generation === viewGeneration && roomId === $("#adminRoomSelect").value && state.value === nextStatus && progress.value === nextProgress) await loadBinding(); }
|
|
133
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
134
|
-
finally { save.disabled = false; }
|
|
135
|
-
});
|
|
136
|
-
row.append(title, state, progress, save); list.append(row);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
function renderPlans(plans, roomId) {
|
|
140
|
-
const list = $("#adminPlanList"); list.replaceChildren();
|
|
141
|
-
for (const plan of plans) {
|
|
142
|
-
const row = document.createElement("li"), text = document.createElement("p"), toggle = document.createElement("button"), remove = document.createElement("button");
|
|
143
|
-
text.textContent = `${plan.name} · ${app.t(plan.paused ? "paused" : "nextRun", { time: new Date(plan.nextRunAt).toLocaleString(), minutes: Math.round(plan.intervalSeconds / 60) })}`;
|
|
144
|
-
toggle.className = remove.className = "btn ghost small"; toggle.type = remove.type = "button";
|
|
145
|
-
toggle.textContent = app.t(plan.paused ? "resumeTimer" : "pauseTimer"); remove.textContent = app.t("deleteTimer");
|
|
146
|
-
toggle.addEventListener("click", () => changePlan(roomId, plan.id, { paused: !plan.paused }, toggle));
|
|
147
|
-
remove.addEventListener("click", async () => { if (confirm(app.t("deleteTimerConfirm", { name: plan.name }))) await changePlan(roomId, plan.id, null, remove); });
|
|
148
|
-
row.append(text, toggle, remove); list.append(row);
|
|
149
|
-
}
|
|
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("");
|
|
150
86
|
}
|
|
151
|
-
async
|
|
152
|
-
|
|
153
|
-
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/plans/${encodeURIComponent(planId)}`, update ? { method: "PATCH", body: json(update) } : { method: "DELETE", body: json({}) }); if (generation === viewGeneration && roomId === $("#adminRoomSelect").value) await loadBinding(); }
|
|
154
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
155
|
-
finally { button.disabled = false; }
|
|
156
|
-
}
|
|
157
|
-
$("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
|
|
87
|
+
$("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
|
|
88
|
+
app.verifyAdminToken = verifyToken;
|
|
158
89
|
$("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
|
|
159
90
|
$("#btnRefreshAdmin").addEventListener("click", async () => {
|
|
160
91
|
const id = $("#adminRoomSelect").value;
|
|
161
92
|
const generation = ++viewGeneration;
|
|
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); }
|
|
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); }
|
|
163
94
|
catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
|
|
164
95
|
});
|
|
165
96
|
$("#btnCloseAdmin").addEventListener("click", () => dialog.close());
|
|
166
|
-
dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration;
|
|
97
|
+
dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); });
|
|
167
98
|
dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
|
|
168
99
|
$("#adminRoomSelect").addEventListener("change", () => { clearEnrollment(); void loadBinding(); });
|
|
169
|
-
$("#
|
|
170
|
-
$("#adminTargetAgent").addEventListener("change", clearEnrollment);
|
|
171
|
-
$("#adminTaskRoom").addEventListener("change", () => void loadTaskAgents());
|
|
100
|
+
$("#adminTargetAgent").addEventListener("change", () => { clearEnrollment(); $("#btnDesignateAgent").disabled = !agents.some((agent) => agent.sessionID === $("#adminTargetAgent").value); });
|
|
172
101
|
$("#btnDesignateAgent").addEventListener("click", async () => {
|
|
173
102
|
const roomId = $("#adminRoomSelect").value, agent = agents.find((item) => item.sessionID === $("#adminTargetAgent").value);
|
|
174
103
|
if (!roomId || !agent || !agent.membershipID) return status(app.t("selectAdminAgent"), true);
|
|
175
|
-
const body = { targetRoomId:
|
|
104
|
+
const body = { targetRoomId: roomId, sessionID: agent.sessionID, receiverOwnerID: agent.receiverOwnerID || "", membershipID: agent.membershipID };
|
|
176
105
|
const generation = viewGeneration, button = $("#btnDesignateAgent"); button.disabled = true;
|
|
177
106
|
try {
|
|
178
107
|
const existing = bindings.some((item) => item.roomId === roomId);
|
|
179
108
|
const result = await app.adminApi(existing ? `/admin/rooms/${encodeURIComponent(roomId)}` : "/admin/rooms", { method: existing ? "PUT" : "POST", body: json(existing ? body : { roomId, ...body }) });
|
|
180
|
-
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value ||
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
|
|
189
|
-
copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(instruction.textContent); status(app.t("enrollmentCopied")); } catch (error) { status(error.message, true); } });
|
|
190
|
-
box.replaceChildren(warning, instruction, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
|
|
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("");
|
|
191
117
|
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
192
118
|
finally { button.disabled = false; }
|
|
193
119
|
});
|
|
@@ -199,25 +125,6 @@ export function initAdmin(app) {
|
|
|
199
125
|
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
200
126
|
finally { button.disabled = false; }
|
|
201
127
|
});
|
|
202
|
-
$("#adminTaskForm").addEventListener("submit", async (event) => {
|
|
203
|
-
event.preventDefault(); const roomId = $("#adminRoomSelect").value, binding = bindings.find((item) => item.roomId === roomId), targetRoomId = $("#adminTaskRoom").value, targetSessionID = $("#adminTaskAgent").value, target = taskAgents.find((item) => item.sessionID === targetSessionID && item.membershipID), input = $("#adminTaskText"), text = input.value, button = $("#adminTaskForm button[type=submit]");
|
|
204
|
-
if (!binding) return status(app.t("selectAdminAgent"), true);
|
|
205
|
-
if (!target || !text.trim()) return status(app.t("chooseAgent"), true);
|
|
206
|
-
const generation = viewGeneration; button.disabled = true;
|
|
207
|
-
try {
|
|
208
|
-
await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/tasks`, { method: "POST", body: json({ targetRoomId, targetSessionID, text }) });
|
|
209
|
-
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value) return;
|
|
210
|
-
if (input.value === text && targetRoomId === $("#adminTaskRoom").value && targetSessionID === $("#adminTaskAgent").value) input.value = "";
|
|
211
|
-
await loadBinding(generation);
|
|
212
|
-
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
213
|
-
finally { button.disabled = false; }
|
|
214
|
-
});
|
|
215
|
-
$("#adminPlanForm").addEventListener("submit", async (event) => {
|
|
216
|
-
event.preventDefault(); const roomId = $("#adminRoomSelect").value, generation = viewGeneration, form = $("#adminPlanForm"), button = form.querySelector("button[type=submit]"), name = $("#adminPlanName").value, interval = $("#adminPlanInterval").value, text = $("#adminPlanText").value; button.disabled = true;
|
|
217
|
-
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/plans`, { method: "POST", body: json({ name, intervalSeconds: Number(interval), text }) }); if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value || !dialog.open) return; if ($("#adminPlanName").value === name && $("#adminPlanInterval").value === interval && $("#adminPlanText").value === text) { form.reset(); $("#adminPlanInterval").value = "3600"; } await loadBinding(generation); }
|
|
218
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
219
|
-
finally { button.disabled = false; }
|
|
220
|
-
});
|
|
221
128
|
$("#inAdminToken").value = LS.adminToken;
|
|
222
129
|
void verifyToken();
|
|
223
130
|
}
|
|
@@ -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)
|
|
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)
|
|
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) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createRandomId } from "./state.js";
|
|
2
2
|
|
|
3
3
|
const trustedChipNames = new Map();
|
|
4
|
+
const autoSeparator = "\uE000\uE001";
|
|
4
5
|
function mentionName(node) {
|
|
5
6
|
const name = trustedChipNames.get(node.dataset?.chatChip);
|
|
6
7
|
return name !== undefined && node.dataset.mention === name && node.textContent === `@${name}` ? name : null;
|
|
@@ -15,7 +16,9 @@ export function editorText(editor, draft = false) {
|
|
|
15
16
|
if (node.nodeType === Node.TEXT_NODE) value += draft ? encodeDraftText(node.nodeValue) : node.nodeValue;
|
|
16
17
|
else if (node.nodeType === Node.ELEMENT_NODE) {
|
|
17
18
|
const mention = mentionName(node);
|
|
18
|
-
if (
|
|
19
|
+
if (node.dataset?.chatAutoSeparator) value += draft && node.textContent.startsWith(" ")
|
|
20
|
+
? autoSeparator + encodeDraftText(node.textContent.slice(1)) : draft ? encodeDraftText(node.textContent) : node.textContent;
|
|
21
|
+
else if (mention !== null) value += `<at>@${mention}</at>`;
|
|
19
22
|
else if (node.tagName === "BR") value += "\n";
|
|
20
23
|
else node.childNodes.forEach((child, index, all) => {
|
|
21
24
|
if (index && (block(child) || block(all[index - 1]))) value += "\n";
|
|
@@ -31,24 +34,20 @@ export function editorText(editor, draft = false) {
|
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
export const editorDraftText = (editor) => editorText(editor, true);
|
|
37
|
+
export const autoMentionDraft = (name) => `<at>@${name}</at>${autoSeparator}`;
|
|
34
38
|
const literalMention = /<at>@([^<]+)<\/at>/g;
|
|
35
39
|
function encodeDraftText(text) { return String(text).replace(/\uE000/g, "\uE000\uE000").replace(literalMention, "\uE000$&"); }
|
|
36
40
|
|
|
37
41
|
export function setEditorText(editor, value, draft = false) {
|
|
38
42
|
editor.replaceChildren();
|
|
39
|
-
const pattern = draft ? /\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
|
|
43
|
+
const pattern = draft ? /\uE000\uE001|\uE000\uE000|\uE000<at>@([^<]+)<\/at>|<at>@([^<]+)<\/at>/g : /<at>@([^<]+)<\/at>/g;
|
|
40
44
|
let offset = 0, match;
|
|
41
45
|
while ((match = pattern.exec(String(value))) !== null) {
|
|
42
46
|
editor.append(document.createTextNode(String(value).slice(offset, match.index)));
|
|
47
|
+
if (draft && match[0] === autoSeparator) { editor.append(createAutoSeparator()); offset = pattern.lastIndex; continue; }
|
|
43
48
|
if (draft && match[0] === "\uE000\uE000") { editor.append(document.createTextNode("\uE000")); offset = pattern.lastIndex; continue; }
|
|
44
49
|
if (draft && match[0].startsWith("\uE000")) { editor.append(document.createTextNode(match[0].slice(1))); offset = pattern.lastIndex; continue; }
|
|
45
|
-
|
|
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;
|
|
50
|
+
editor.append(createMention(draft ? match[2] : match[1])); offset = pattern.lastIndex;
|
|
52
51
|
}
|
|
53
52
|
editor.append(document.createTextNode(String(value).slice(offset)));
|
|
54
53
|
pruneTrustedChipNames();
|
|
@@ -92,11 +91,24 @@ function lengthBefore(root, target, position) {
|
|
|
92
91
|
}
|
|
93
92
|
|
|
94
93
|
export function setCaret(editor, offset) {
|
|
95
|
-
const selection = getSelection(), range = document.createRange()
|
|
96
|
-
|
|
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);
|
|
97
99
|
selection.removeAllRanges(); selection.addRange(range);
|
|
98
100
|
}
|
|
99
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
|
+
|
|
100
112
|
export function setEditorSelection(editor, start, end = start) {
|
|
101
113
|
const range = document.createRange(), selection = getSelection();
|
|
102
114
|
const first = editorPoint(editor, start), last = editorPoint(editor, end);
|
|
@@ -141,16 +153,18 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
|
|
|
141
153
|
setEditorSelection(editor, start, end);
|
|
142
154
|
if (!parseMentions && document.execCommand("insertText", false, String(value))) return;
|
|
143
155
|
const marker = `chat-insert-${createRandomId()}`;
|
|
144
|
-
const source = String(value),
|
|
156
|
+
const source = String(value), generatedSpace = parseMentions && source.endsWith(" "), content = generatedSpace ? source.slice(0, -1) : source;
|
|
157
|
+
const token = parseMentions ? /<at>@([^<]+)<\/at>/g : null;
|
|
145
158
|
let html = "", cursor = 0, match;
|
|
146
|
-
while (token && (match = token.exec(
|
|
147
|
-
html += textHTML(
|
|
159
|
+
while (token && (match = token.exec(content))) {
|
|
160
|
+
html += textHTML(content.slice(cursor, match.index));
|
|
148
161
|
const name = escapeHTML(match[1]);
|
|
149
162
|
const chipID = createRandomId(); trustedChipNames.set(chipID, match[1]);
|
|
150
163
|
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
164
|
cursor = token.lastIndex;
|
|
152
165
|
}
|
|
153
|
-
html += textHTML(
|
|
166
|
+
html += textHTML(content.slice(cursor));
|
|
167
|
+
if (generatedSpace) html += `<span data-chat-auto-separator="true"> </span>`;
|
|
154
168
|
if (document.execCommand("insertHTML", false, html)) {
|
|
155
169
|
editor.querySelectorAll(`[data-insert-marker="${marker}"]`).forEach((chip) => chip.removeAttribute("data-insert-marker"));
|
|
156
170
|
setCaret(editor, start + source.length);
|
|
@@ -158,6 +172,7 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
|
|
|
158
172
|
} else {
|
|
159
173
|
const current = editorText(editor), next = current.slice(0, start) + value + current.slice(end);
|
|
160
174
|
if (parseMentions) setEditorText(editor, next); else editor.replaceChildren(document.createTextNode(next));
|
|
175
|
+
if (generatedSpace) wrapAutoSeparator(editor, start + source.length - 1);
|
|
161
176
|
setCaret(editor, start + value.length);
|
|
162
177
|
pruneTrustedChipNames();
|
|
163
178
|
}
|
|
@@ -166,6 +181,40 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
|
|
|
166
181
|
function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]); }
|
|
167
182
|
function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
|
|
168
183
|
|
|
184
|
+
function createMention(name) {
|
|
185
|
+
const chip = document.createElement("span");
|
|
186
|
+
chip.className = "editor-mention"; chip.dataset.mention = name;
|
|
187
|
+
chip.dataset.chatChip = createRandomId(); trustedChipNames.set(chip.dataset.chatChip, name);
|
|
188
|
+
chip.contentEditable = "false"; chip.setAttribute("role", "img");
|
|
189
|
+
chip.setAttribute("aria-label", `Mention ${name}`); chip.textContent = `@${name}`;
|
|
190
|
+
return chip;
|
|
191
|
+
}
|
|
192
|
+
function createAutoSeparator() {
|
|
193
|
+
const separator = document.createElement("span");
|
|
194
|
+
separator.dataset.chatAutoSeparator = "true"; separator.textContent = " ";
|
|
195
|
+
return separator;
|
|
196
|
+
}
|
|
197
|
+
function wrapAutoSeparator(editor, offset) {
|
|
198
|
+
const start = editorPoint(editor, offset), end = editorPoint(editor, offset + 1), range = document.createRange();
|
|
199
|
+
range.setStart(start[0], start[1]); range.setEnd(end[0], end[1]); range.deleteContents(); range.insertNode(createAutoSeparator());
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function deleteMentionAtCaret(editor, event) {
|
|
203
|
+
if (event.isComposing || event.keyCode === 229 || event.key !== "Backspace") return;
|
|
204
|
+
const [caret, end] = editorSelectionOffsets(editor);
|
|
205
|
+
if (caret !== end) return;
|
|
206
|
+
const separator = [...editor.querySelectorAll("[data-chat-auto-separator]")].find((node) => {
|
|
207
|
+
const start = lengthBefore(editor, node, 0); return node.textContent === " " && caret === start + 1;
|
|
208
|
+
});
|
|
209
|
+
const mention = separator?.previousElementSibling || [...editor.querySelectorAll(".editor-mention")].find((node) => {
|
|
210
|
+
return caret === lengthBefore(editor, node, 0) + `<at>@${mentionName(node)}</at>`.length;
|
|
211
|
+
});
|
|
212
|
+
if (!mention || (separator && separator.previousElementSibling !== mention)) return;
|
|
213
|
+
const start = lengthBefore(editor, mention, 0);
|
|
214
|
+
event.preventDefault(); mention.remove(); separator?.remove(); setCaret(editor, start);
|
|
215
|
+
editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
|
216
|
+
}
|
|
217
|
+
|
|
169
218
|
function pruneTrustedChipNames() {
|
|
170
219
|
const live = new Set([...document.querySelectorAll("[data-chat-chip]")].map((node) => node.dataset.chatChip));
|
|
171
220
|
const stale = [...trustedChipNames.keys()].filter((id) => !live.has(id));
|
|
@@ -189,6 +238,7 @@ export function installEditor(editor) {
|
|
|
189
238
|
editor.setSelectionRange = (start, end = start) => setEditorSelection(editor, start, end);
|
|
190
239
|
editor.replaceTextRange = (start, end, value) => replaceEditorRange(editor, start, end, value);
|
|
191
240
|
editor.addEventListener("input", pruneTrustedChipNames);
|
|
241
|
+
editor.addEventListener("keydown", (event) => deleteMentionAtCaret(editor, event));
|
|
192
242
|
editor.addEventListener("paste", (event) => {
|
|
193
243
|
if (event.defaultPrevented || event.clipboardData?.files.length) return;
|
|
194
244
|
event.preventDefault();
|