@alexsun-top/opencode-chat-room 0.5.1 → 0.5.3
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 +22 -0
- package/README.md +28 -207
- package/README.zh-CN.md +27 -201
- package/docs/administrator-rooms.md +6 -22
- package/package.json +4 -5
- package/plugin.ts +19 -4
- package/server/admin-routes.ts +2 -11
- package/server/admin-state.ts +15 -4
- package/server/assets/base.css +10 -0
- package/server/assets/chat/admin.js +67 -128
- package/server/assets/chat/attachments.js +1 -1
- package/server/assets/chat/editor.js +248 -0
- package/server/assets/chat/events.js +13 -11
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/mentions.js +38 -28
- package/server/assets/chat/message-window.js +18 -0
- package/server/assets/chat/messages.js +49 -57
- package/server/assets/chat/questions.js +115 -43
- package/server/assets/chat/receipts.js +0 -1
- package/server/assets/chat/reminders.js +102 -0
- package/server/assets/chat/replies.js +150 -0
- package/server/assets/chat/room-watcher.js +37 -0
- package/server/assets/chat/rooms.js +59 -70
- package/server/assets/chat/state.js +29 -9
- package/server/assets/conversation.css +33 -9
- package/server/assets/responsive.css +15 -16
- package/server/chat-server.ts +21 -2
- package/server/chat.html +23 -13
- package/server/inbox.ts +5 -1
- package/server/room-reminders.ts +222 -0
- package/server/wake.ts +6 -3
- package/skills/chatroom/SKILL.md +11 -7
- package/src/admin-client.ts +6 -43
- package/src/admin-credentials.ts +0 -19
- package/src/agent-receipts.ts +13 -18
- package/src/mentions.ts +2 -1
- package/src/plugin-notifications.ts +4 -0
- package/src/queue.ts +7 -2
- package/src/reminder-client.ts +50 -0
- package/src/resource-read.ts +118 -0
- package/src/resource-upload.ts +1 -1
- package/src/resources.ts +1 -1
- package/src/sqlite-state.ts +43 -3
- package/src/store.ts +22 -8
- package/src/supervision-inbox.ts +6 -18
- package/src/v2-plugin.ts +11 -5
- package/server/admin-plan-routes.ts +0 -79
- package/server/admin-scheduler.ts +0 -42
- package/server/admin-task-routes.ts +0 -182
|
@@ -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.3",
|
|
4
4
|
"description": "A chat-room plugin and central server for OpenCode.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,9 +35,7 @@
|
|
|
35
35
|
"server/admin-routes.ts",
|
|
36
36
|
"server/admin-state.ts",
|
|
37
37
|
"server/admin-auth.ts",
|
|
38
|
-
"server/
|
|
39
|
-
"server/admin-plan-routes.ts",
|
|
40
|
-
"server/admin-scheduler.ts",
|
|
38
|
+
"server/room-reminders.ts",
|
|
41
39
|
"server/wake.ts",
|
|
42
40
|
"server/chat.html",
|
|
43
41
|
"server/assets",
|
|
@@ -52,7 +50,7 @@
|
|
|
52
50
|
},
|
|
53
51
|
"scripts": {
|
|
54
52
|
"server": "bun run server/chat-server.ts",
|
|
55
|
-
"test": "bun test",
|
|
53
|
+
"test": "for file in src/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done",
|
|
56
54
|
"typecheck": "tsc --noEmit"
|
|
57
55
|
},
|
|
58
56
|
"devDependencies": {
|
|
@@ -66,6 +64,7 @@
|
|
|
66
64
|
"dependencies": {
|
|
67
65
|
"@opencode-ai/plugin": "^1.18.29",
|
|
68
66
|
"@opencode/client": "2.0.32",
|
|
67
|
+
"croner": "11.0.0",
|
|
69
68
|
"zod": "4.1.8"
|
|
70
69
|
}
|
|
71
70
|
}
|
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;
|
|
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.",
|
|
458
473
|
args: roomArgs.shape,
|
|
459
474
|
execute: roomExecute,
|
|
460
475
|
});
|
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
|
@@ -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;
|
|
@@ -2,12 +2,34 @@ 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) => {
|
|
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,152 +37,88 @@ 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 {
|
|
20
|
-
|
|
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;
|
|
24
|
-
clearEnrollment();
|
|
51
|
+
clearEnrollment();
|
|
25
52
|
dialog.showModal(); status(app.t("adminLoading"));
|
|
26
|
-
$("#adminRoomSelect").disabled = $("#
|
|
27
|
-
$("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = true;
|
|
28
|
-
$("#btnRevokeAdmin").hidden = $("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
53
|
+
$("#adminRoomSelect").disabled = $("#adminTargetAgent").disabled = $("#btnDesignateAgent").disabled = true; $("#btnRevokeAdmin").hidden = true;
|
|
29
54
|
try {
|
|
30
55
|
const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
|
|
31
56
|
if (generation !== viewGeneration || !dialog.open) return;
|
|
32
|
-
bindings = adminResult.rooms || []; rooms = roomResult || [];
|
|
57
|
+
bindings = adminResult.rooms || []; setAdminRooms(bindings); rooms = roomResult || [];
|
|
33
58
|
renderAdminRooms();
|
|
34
59
|
$("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (rooms.length) $("#adminTaskRoom").value = rooms[0].id;
|
|
39
|
-
status(rooms.length ? "" : app.t("createAdminRoomFirst"));
|
|
40
|
-
await Promise.all([loadDesignationAgents(), loadTaskAgents()]); await loadBinding(generation);
|
|
41
|
-
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
42
|
-
finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#adminTargetRoom").disabled = $("#adminTargetAgent").disabled = false; $("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = false; } }
|
|
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; } }
|
|
43
63
|
}
|
|
44
64
|
async function registryAgents(roomId) {
|
|
45
|
-
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)) : [];
|
|
46
66
|
}
|
|
47
67
|
async function loadDesignationAgents() {
|
|
48
|
-
const generation = ++designationGeneration, roomId = $("#
|
|
49
|
-
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);
|
|
50
70
|
try {
|
|
51
71
|
const found = await registryAgents(roomId);
|
|
52
|
-
if (generation !== designationGeneration || roomId !== $("#
|
|
53
|
-
agents = found; select($("#adminTargetAgent"), agents
|
|
54
|
-
} catch (error) { if (generation === designationGeneration) status(error.message, true); }
|
|
55
|
-
}
|
|
56
|
-
async function loadTaskAgents() {
|
|
57
|
-
const generation = ++taskGeneration, roomId = $("#adminTaskRoom").value;
|
|
58
|
-
taskAgents = []; $("#adminTaskAgent").disabled = true; select($("#adminTaskAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
59
|
-
try {
|
|
60
|
-
const found = await registryAgents(roomId);
|
|
61
|
-
if (generation !== taskGeneration || roomId !== $("#adminTaskRoom").value) return;
|
|
62
|
-
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;
|
|
63
|
-
} 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; } }
|
|
64
75
|
}
|
|
65
76
|
async function loadBinding(generation = ++viewGeneration) {
|
|
66
77
|
const id = $("#adminRoomSelect").value;
|
|
67
78
|
const binding = bindings.find((item) => item.roomId === id);
|
|
68
|
-
$("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
|
|
69
|
-
$("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
70
79
|
$("#btnRevokeAdmin").hidden = !binding;
|
|
71
|
-
if (!id
|
|
72
|
-
$("#adminTargetRoom").value = binding.targetRoomId;
|
|
73
|
-
const targetRoomId = binding.targetRoomId;
|
|
80
|
+
if (!id) { agents = []; $("#btnDesignateAgent").disabled = true; status(app.t("createAdminRoomFirst")); select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID); return; }
|
|
74
81
|
await loadDesignationAgents();
|
|
75
|
-
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value ||
|
|
76
|
-
$("#adminTargetAgent").value = binding.sessionID;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const [overview, tasks, plans] = await Promise.all([app.adminApi(`${base}/overview`), app.adminApi(`${base}/tasks`), app.adminApi(`${base}/plans`)]);
|
|
80
|
-
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || !dialog.open) return;
|
|
81
|
-
renderData({ overview, tasks: tasks.tasks, plans: plans.plans }, id);
|
|
82
|
-
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
83
|
-
}
|
|
84
|
-
function renderData(data, id) {
|
|
85
|
-
const overview = $("#adminOverview"); overview.replaceChildren();
|
|
86
|
-
for (const room of data.overview?.rooms || []) {
|
|
87
|
-
const item = document.createElement("p");
|
|
88
|
-
item.textContent = `${room.name}: ${(room.members || []).map((member) => `${member.name} (${member.workState || "unknown"})`).join(", ") || app.t("noAgents")}`;
|
|
89
|
-
overview.append(item);
|
|
90
|
-
}
|
|
91
|
-
const binding = bindings.find((item) => item.roomId === id);
|
|
92
|
-
$("#adminTaskForm").hidden = !binding; $("#adminPlanForm").hidden = !binding;
|
|
93
|
-
renderTasks(data.tasks || [], id); renderPlans(data.plans || [], id);
|
|
94
|
-
}
|
|
95
|
-
function renderTasks(tasks, roomId) {
|
|
96
|
-
const list = $("#adminTaskList"); list.replaceChildren();
|
|
97
|
-
for (const task of tasks) {
|
|
98
|
-
const row = document.createElement("li"), title = document.createElement("p"), state = document.createElement("select"), progress = document.createElement("textarea"), save = document.createElement("button");
|
|
99
|
-
title.textContent = task.text; state.className = "admin-select";
|
|
100
|
-
for (const value of ["pending", "working", "blocked", "completed", "cancelled"]) state.add(new Option(app.t(`task_${value}`), value));
|
|
101
|
-
state.value = task.status; progress.className = "input"; progress.rows = 2; progress.value = task.progress || "";
|
|
102
|
-
save.className = "btn ghost small"; save.type = "button"; save.textContent = app.t("updateTask");
|
|
103
|
-
save.addEventListener("click", async () => {
|
|
104
|
-
const generation = viewGeneration, nextStatus = state.value, nextProgress = progress.value; save.disabled = true;
|
|
105
|
-
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(); }
|
|
106
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
107
|
-
finally { save.disabled = false; }
|
|
108
|
-
});
|
|
109
|
-
row.append(title, state, progress, save); list.append(row);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
function renderPlans(plans, roomId) {
|
|
113
|
-
const list = $("#adminPlanList"); list.replaceChildren();
|
|
114
|
-
for (const plan of plans) {
|
|
115
|
-
const row = document.createElement("li"), text = document.createElement("p"), toggle = document.createElement("button"), remove = document.createElement("button");
|
|
116
|
-
text.textContent = `${plan.name} · ${app.t(plan.paused ? "paused" : "nextRun", { time: new Date(plan.nextRunAt).toLocaleString(), minutes: Math.round(plan.intervalSeconds / 60) })}`;
|
|
117
|
-
toggle.className = remove.className = "btn ghost small"; toggle.type = remove.type = "button";
|
|
118
|
-
toggle.textContent = app.t(plan.paused ? "resumeTimer" : "pauseTimer"); remove.textContent = app.t("deleteTimer");
|
|
119
|
-
toggle.addEventListener("click", () => changePlan(roomId, plan.id, { paused: !plan.paused }, toggle));
|
|
120
|
-
remove.addEventListener("click", async () => { if (confirm(app.t("deleteTimerConfirm", { name: plan.name }))) await changePlan(roomId, plan.id, null, remove); });
|
|
121
|
-
row.append(text, toggle, remove); list.append(row);
|
|
122
|
-
}
|
|
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("");
|
|
123
86
|
}
|
|
124
|
-
async
|
|
125
|
-
const generation = viewGeneration; button.disabled = true;
|
|
126
|
-
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(); }
|
|
127
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
128
|
-
finally { button.disabled = false; }
|
|
129
|
-
}
|
|
130
|
-
$("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); 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(); });
|
|
131
88
|
$("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
|
|
132
89
|
$("#btnRefreshAdmin").addEventListener("click", async () => {
|
|
133
90
|
const id = $("#adminRoomSelect").value;
|
|
134
91
|
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); }
|
|
92
|
+
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); }
|
|
93
|
+
catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
|
|
137
94
|
});
|
|
138
95
|
$("#btnCloseAdmin").addEventListener("click", () => dialog.close());
|
|
139
|
-
dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration;
|
|
96
|
+
dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; clearEnrollment(); });
|
|
140
97
|
dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
|
|
141
98
|
$("#adminRoomSelect").addEventListener("change", () => { clearEnrollment(); void loadBinding(); });
|
|
142
|
-
$("#
|
|
143
|
-
$("#adminTargetAgent").addEventListener("change", clearEnrollment);
|
|
144
|
-
$("#adminTaskRoom").addEventListener("change", () => void loadTaskAgents());
|
|
99
|
+
$("#adminTargetAgent").addEventListener("change", () => { clearEnrollment(); $("#btnDesignateAgent").disabled = !agents.some((agent) => agent.sessionID === $("#adminTargetAgent").value); });
|
|
145
100
|
$("#btnDesignateAgent").addEventListener("click", async () => {
|
|
146
101
|
const roomId = $("#adminRoomSelect").value, agent = agents.find((item) => item.sessionID === $("#adminTargetAgent").value);
|
|
147
102
|
if (!roomId || !agent || !agent.membershipID) return status(app.t("selectAdminAgent"), true);
|
|
148
|
-
const body = { targetRoomId:
|
|
103
|
+
const body = { targetRoomId: roomId, sessionID: agent.sessionID, receiverOwnerID: agent.receiverOwnerID || "", membershipID: agent.membershipID };
|
|
149
104
|
const generation = viewGeneration, button = $("#btnDesignateAgent"); button.disabled = true;
|
|
150
105
|
try {
|
|
151
106
|
const existing = bindings.some((item) => item.roomId === roomId);
|
|
152
107
|
const result = await app.adminApi(existing ? `/admin/rooms/${encodeURIComponent(roomId)}` : "/admin/rooms", { method: existing ? "PUT" : "POST", body: json(existing ? body : { roomId, ...body }) });
|
|
153
|
-
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value ||
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
instruction.textContent = `admin(action='admin_claim',roomId='${roomId}',enrollmentKey='${result.enrollmentKey}')`;
|
|
108
|
+
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value || agent.sessionID !== $("#adminTargetAgent").value) return;
|
|
109
|
+
if (!existing) bindings.push(result.adminRoom); else bindings = bindings.map((item) => item.roomId === roomId ? result.adminRoom : item);
|
|
110
|
+
setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
|
|
111
|
+
await loadBinding(generation);
|
|
112
|
+
if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value) return;
|
|
113
|
+
const box = $("#adminEnrollment"), instruction = `admin(action='admin_claim',roomId='${roomId}',enrollmentKey='${result.enrollmentKey}')`, copy = document.createElement("button"), warning = document.createElement("p"), fallback = document.createElement("textarea");
|
|
160
114
|
warning.textContent = app.t("privateEnrollment", { expires: new Date(result.expiresAt).toLocaleString() });
|
|
115
|
+
warning.id = "adminEnrollmentHelp"; fallback.className = "input"; fallback.readOnly = true; fallback.rows = 3; fallback.setAttribute("aria-label", app.t("copyEnrollment")); fallback.setAttribute("aria-describedby", warning.id);
|
|
161
116
|
copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
|
|
162
|
-
|
|
163
|
-
|
|
117
|
+
copy.addEventListener("click", async () => {
|
|
118
|
+
try { if (!navigator.clipboard?.writeText) throw new Error(); await navigator.clipboard.writeText(instruction); status(app.t("enrollmentCopied")); }
|
|
119
|
+
catch { fallback.value = instruction; box.replaceChildren(warning, fallback, copy); fallback.focus(); fallback.select(); status(warning.textContent || ""); }
|
|
120
|
+
});
|
|
121
|
+
box.replaceChildren(warning, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
|
|
164
122
|
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
165
123
|
finally { button.disabled = false; }
|
|
166
124
|
});
|
|
@@ -168,26 +126,7 @@ export function initAdmin(app) {
|
|
|
168
126
|
const id = $("#adminRoomSelect").value;
|
|
169
127
|
if (!id || !confirm(app.t("revokeConfirm"))) return;
|
|
170
128
|
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); }
|
|
172
|
-
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
173
|
-
finally { button.disabled = false; }
|
|
174
|
-
});
|
|
175
|
-
$("#adminTaskForm").addEventListener("submit", async (event) => {
|
|
176
|
-
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]");
|
|
177
|
-
if (!binding) return status(app.t("selectAdminAgent"), true);
|
|
178
|
-
if (!target || !text.trim()) return status(app.t("chooseAgent"), true);
|
|
179
|
-
const generation = viewGeneration; button.disabled = true;
|
|
180
|
-
try {
|
|
181
|
-
await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/tasks`, { method: "POST", body: json({ targetRoomId, targetSessionID, text }) });
|
|
182
|
-
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value) return;
|
|
183
|
-
if (input.value === text && targetRoomId === $("#adminTaskRoom").value && targetSessionID === $("#adminTaskAgent").value) input.value = "";
|
|
184
|
-
await loadBinding(generation);
|
|
185
|
-
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
186
|
-
finally { button.disabled = false; }
|
|
187
|
-
});
|
|
188
|
-
$("#adminPlanForm").addEventListener("submit", async (event) => {
|
|
189
|
-
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;
|
|
190
|
-
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); }
|
|
129
|
+
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); }
|
|
191
130
|
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
192
131
|
finally { button.disabled = false; }
|
|
193
132
|
});
|
|
@@ -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 =
|
|
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) {
|