@alexsun-top/opencode-chat-room 0.5.0 → 0.5.1

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.
@@ -0,0 +1,182 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Database } from "bun:sqlite";
3
+ import { hasAdminCapability, isOperator } from "./admin-auth";
4
+ import { binding, digest, exec, isAgentMember, many, matchesHash, newSecret, one, queue, tx, validCurrent } from "./admin-state";
5
+ import type { Binding } from "./admin-state";
6
+
7
+ const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
8
+ const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
9
+ const statuses = ["pending", "working", "blocked", "completed", "cancelled"] as const;
10
+ type TaskStatus = typeof statuses[number];
11
+ const auth = (request: Request, b: Binding) => isOperator(request) || hasAdminCapability(request, b);
12
+ type TaskRow = { id: string; admin_room_id: string; admin_generation: number; target_room_id: string; target_session_id: string; target_owner_id: string; target_membership_id: string; text: string; status: string; progress: string; delivery_token_hash: string; created_at: number; updated_at: number };
13
+ type DeliveryRow = { id: string; admissionID: string; adminRoomId: string; generation: number; recipientRoomId: string; membershipID: string; kind: string; text: string; taskId: string | null; taskToken: string | null; createdAt: number };
14
+ type TaskView = { id: string; adminRoomId: string; generation: number; targetRoomId: string; targetSessionID: string; text: string; status: string; progress: string; createdAt: number; updatedAt: number };
15
+ type AckDelivery = { id: string; admin_room_id: string; generation: number; recipient_room_id: string; session_id: string; owner_id: string; membership_id: string; kind: string };
16
+ const revokeTaskDelivery = (db: Database, roomID: string, taskID: string) => {
17
+ exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='task' AND task_id=? AND acknowledged=0", roomID, taskID);
18
+ // A delivered prompt cannot be recalled; revoke its token so it cannot report progress.
19
+ exec(db, "UPDATE admin_deliveries SET task_token=NULL WHERE admin_room_id=? AND kind='task' AND task_id=?", roomID, taskID);
20
+ };
21
+
22
+ export async function adminTaskRoutes(request: Request, url: URL): Promise<Response | undefined> {
23
+ const base = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks$/);
24
+ const update = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks\/([^/]+)$/);
25
+ if (base && request.method === "GET") return tx(db => {
26
+ const b = binding(db, decodeURIComponent(base[1]!));
27
+ if (!b) return { error: "admin room not found", status: 404 };
28
+ if (!auth(request, b)) return { error: "unauthorized", status: 401 };
29
+ if (!isOperator(request) && !validCurrent(db, b)) return { error: "binding is no longer active", status: 409 };
30
+ return { tasks: many<TaskView>(db, "SELECT id,admin_room_id AS adminRoomId,admin_generation AS generation,target_room_id AS targetRoomId,target_session_id AS targetSessionID,text,status,progress,created_at AS createdAt,updated_at AS updatedAt FROM admin_tasks WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", b.room_id) };
31
+ }).then(result => "status" in result ? json({ error: result.error }, result.status) : json(result));
32
+ if (base && request.method === "POST") return createTask(request, decodeURIComponent(base[1]!));
33
+ if (update && request.method === "PATCH") return updateTask(request, decodeURIComponent(update[1]!), decodeURIComponent(update[2]!));
34
+ if (url.pathname === "/supervision/inbox" && request.method === "GET") return inbox(request, url);
35
+ if (url.pathname === "/supervision/ack" && request.method === "POST") return acknowledge(request);
36
+ const progress = url.pathname.match(/^\/supervision\/tasks\/([^/]+)\/progress$/);
37
+ if (progress && request.method === "POST") return reportProgress(request, decodeURIComponent(progress[1]!));
38
+ return undefined;
39
+ }
40
+
41
+ async function createTask(request: Request, roomID: string): Promise<Response> {
42
+ const body: unknown = await request.json();
43
+ if (!object(body) || typeof body.targetRoomId !== "string" || !body.targetRoomId || typeof body.targetSessionID !== "string" || !body.targetSessionID || typeof body.text !== "string" || !body.text.trim() || body.text.trim().length > 2000) return json({ error: "invalid task" }, 400);
44
+ const targetRoomID = body.targetRoomId, targetSessionID = body.targetSessionID, text = body.text.trim();
45
+ const result = await tx(db => {
46
+ const b = binding(db, roomID);
47
+ if (!b) return { status: 404 as const };
48
+ if (!auth(request, b)) return { status: 401 as const };
49
+ if (!validCurrent(db, b)) return { status: 409 as const };
50
+ const recipient = one<{ receiver_owner_id: string | null; membership_id: string }>(db, "SELECT receiver_owner_id,membership_id FROM registry WHERE room_id=? AND session_id=?", targetRoomID, targetSessionID);
51
+ if (!recipient || !isAgentMember(db, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id)) return { status: 409 as const };
52
+ const id = randomUUID(), now = Date.now(), taskToken = newSecret();
53
+ exec(db, "INSERT INTO admin_tasks(id,admin_room_id,admin_generation,target_room_id,target_session_id,target_owner_id,target_membership_id,text,status,progress,delivery_token_hash,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,'pending','',?,?,?)",
54
+ id, roomID, b.generation, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id, text, digest(taskToken), now, now);
55
+ queue(db, b, "task", text, id, taskToken, { roomID: targetRoomID, sessionID: targetSessionID, ownerID: recipient.receiver_owner_id ?? "", membershipID: recipient.membership_id });
56
+ return { task: { id, adminRoomId: roomID, generation: b.generation, targetRoomId: targetRoomID, targetSessionID, text, status: "pending", progress: "", createdAt: now, updatedAt: now } };
57
+ });
58
+ if ("status" in result) return json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "active agent target not found" }, result.status);
59
+ return json(result, 201);
60
+ }
61
+
62
+ async function updateTask(request: Request, roomID: string, taskID: string): Promise<Response> {
63
+ const body: unknown = await request.json();
64
+ if (!object(body) || (body.status !== undefined && !statuses.includes(body.status as typeof statuses[number])) ||
65
+ (body.progress !== undefined && (typeof body.progress !== "string" || body.progress.length > 2000))) return json({ error: "invalid task update" }, 400);
66
+ const update = body as { status?: TaskStatus; progress?: string };
67
+ const result = await tx(db => {
68
+ const b = binding(db, roomID);
69
+ if (!b) return { status: 404 as const };
70
+ if (!auth(request, b)) return { status: 401 as const };
71
+ if (!validCurrent(db, b)) return { status: 409 as const };
72
+ const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=? AND admin_room_id=?", taskID, roomID);
73
+ if (!task || task.admin_generation !== b.generation) return { status: 404 as const };
74
+ const status = update.status ?? task.status;
75
+ if (task.status === "completed" || task.status === "cancelled") return { status: 409 as const };
76
+ const progress = update.progress === undefined ? task.progress : update.progress.trim();
77
+ const updatedAt = Date.now();
78
+ const terminal = status === "completed" || status === "cancelled";
79
+ exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?", status, progress, terminal ? "" : task.delivery_token_hash, updatedAt, taskID, b.generation);
80
+ if (terminal) revokeTaskDelivery(db, roomID, taskID);
81
+ return { task: { id: taskID, adminRoomId: roomID, generation: b.generation, targetRoomId: task.target_room_id,
82
+ targetSessionID: task.target_session_id, text: task.text, status, progress, createdAt: task.created_at, updatedAt } };
83
+ });
84
+ if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "task not found" : "binding is no longer active" }, result.status);
85
+ return json(result);
86
+ }
87
+
88
+ async function reportProgress(request: Request, taskID: string): Promise<Response> {
89
+ const body: unknown = await request.json();
90
+ const sessionID = request.headers.get("x-chat-agent-session") ?? "";
91
+ const ownerID = request.headers.get("x-chat-agent-owner") ?? "";
92
+ if (!object(body) || typeof body.taskToken !== "string" || typeof body.status !== "string" ||
93
+ !statuses.includes(body.status as TaskStatus) || typeof body.progress !== "string" || body.progress.length > 2000) return json({ error: "invalid task progress" }, 400);
94
+ const update = body as { taskToken: string; status: TaskStatus; progress: string };
95
+ const result = await tx(db => {
96
+ const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=?", taskID);
97
+ if (!task) return false;
98
+ const b = binding(db, task.admin_room_id);
99
+ if (!b || task.admin_generation !== b.generation || task.status === "completed" || task.status === "cancelled" || !validCurrent(db, b) ||
100
+ sessionID !== task.target_session_id || ownerID !== task.target_owner_id ||
101
+ !isAgentMember(db, task.target_room_id, task.target_session_id, task.target_owner_id, task.target_membership_id) ||
102
+ !task.delivery_token_hash || !matchesHash(update.taskToken, task.delivery_token_hash)) return null;
103
+ const terminal = update.status === "completed" || update.status === "cancelled";
104
+ exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?",
105
+ update.status, update.progress.trim(), terminal ? "" : task.delivery_token_hash, Date.now(), taskID, b.generation);
106
+ if (terminal) revokeTaskDelivery(db, b.room_id, taskID);
107
+ return true;
108
+ });
109
+ if (result === null) return json({ error: "task progress credential rejected" }, 401);
110
+ return result ? json({ ok: true }) : json({ error: "task not found" }, 404);
111
+ }
112
+
113
+ async function inbox(request: Request, url: URL): Promise<Response> {
114
+ const sessionID = url.searchParams.get("sessionID") ?? "";
115
+ const ownerID = url.searchParams.get("receiverOwnerID") ?? "";
116
+ const adminRoomID = url.searchParams.get("adminRoomId");
117
+ if (!sessionID || sessionID.length > 128 || ownerID.length > 128) return json({ error: "invalid agent identity" }, 400);
118
+ return adminRoomID ? protectedInbox(request, sessionID, ownerID, adminRoomID) : taskInbox(sessionID, ownerID);
119
+ }
120
+
121
+ function pruneStale(db: Database, sessionID: string, ownerID: string): void {
122
+ db.query(`DELETE FROM admin_deliveries AS d WHERE d.acknowledged=0 AND d.session_id=? AND d.owner_id=? AND (
123
+ NOT EXISTS(SELECT 1 FROM admin_rooms a WHERE a.room_id=d.admin_room_id AND a.generation=d.generation AND EXISTS(
124
+ SELECT 1 FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END
125
+ WHERE g.room_id=a.target_room_id AND g.session_id=a.session_id AND g.membership_id=a.membership_id AND coalesce(g.receiver_owner_id,'')=a.receiver_owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))
126
+ OR NOT EXISTS(SELECT 1 FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END
127
+ WHERE g.room_id=d.recipient_room_id AND g.session_id=d.session_id AND g.membership_id=d.membership_id AND coalesce(g.receiver_owner_id,'')=d.owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))`)
128
+ .run(sessionID, ownerID);
129
+ }
130
+
131
+ async function taskInbox(sessionID: string, ownerID: string): Promise<Response> {
132
+ const result = await tx(db => {
133
+ pruneStale(db, sessionID, ownerID);
134
+ const deliveries = many<DeliveryRow>(db, `SELECT d.id,d.admission_id AS admissionID,d.admin_room_id AS adminRoomId,d.generation,
135
+ d.recipient_room_id AS recipientRoomId,d.membership_id AS membershipID,d.kind,d.text,d.task_id AS taskId,d.task_token AS taskToken,d.created_at AS createdAt
136
+ FROM admin_deliveries d JOIN admin_tasks t ON t.id=d.task_id AND t.admin_room_id=d.admin_room_id AND t.admin_generation=d.generation
137
+ AND t.target_room_id=d.recipient_room_id AND t.target_session_id=d.session_id AND t.target_owner_id=d.owner_id AND t.target_membership_id=d.membership_id
138
+ WHERE d.session_id=? AND d.owner_id=? AND d.kind='task' AND d.acknowledged=0 ORDER BY d.created_at LIMIT 100`, sessionID, ownerID)
139
+ .map(({ taskToken, recipientRoomId, membershipID, ...delivery }) => ({ ...delivery, targetRoomId: recipientRoomId, ...(taskToken ? { taskToken } : {}) }));
140
+ const supervisionRoomIds = many<{ admin_room_id: string }>(db, `SELECT DISTINCT d.admin_room_id FROM admin_deliveries d JOIN admin_rooms a ON a.room_id=d.admin_room_id
141
+ WHERE d.session_id=a.session_id AND d.owner_id=a.receiver_owner_id AND d.membership_id=a.membership_id AND d.recipient_room_id=a.target_room_id
142
+ AND d.generation=a.generation AND d.session_id=? AND d.owner_id=? AND d.kind='supervision' AND d.acknowledged=0 ORDER BY d.admin_room_id LIMIT 100`, sessionID, ownerID).map(row => row.admin_room_id);
143
+ return { deliveries, supervisionRoomIds };
144
+ });
145
+ return json(result);
146
+ }
147
+
148
+ async function protectedInbox(request: Request, sessionID: string, ownerID: string, roomID: string): Promise<Response> {
149
+ const result = await tx(db => {
150
+ const b = binding(db, roomID);
151
+ if (!b) return { status: 404 as const };
152
+ const operator = isOperator(request);
153
+ if (!operator && (sessionID !== b.session_id || ownerID !== b.receiver_owner_id || !hasAdminCapability(request, b))) return { status: 401 as const };
154
+ if (!validCurrent(db, b)) return { status: 409 as const };
155
+ pruneStale(db, b.session_id, b.receiver_owner_id);
156
+ return { deliveries: many<DeliveryRow>(db, `SELECT id,admission_id AS admissionID,admin_room_id AS adminRoomId,generation,
157
+ recipient_room_id AS recipientRoomId,membership_id AS membershipID,kind,text,task_id AS taskId,task_token AS taskToken,created_at AS createdAt
158
+ FROM admin_deliveries WHERE admin_room_id=? AND generation=? AND recipient_room_id=? AND session_id=? AND owner_id=? AND membership_id=? AND kind='supervision' AND acknowledged=0 ORDER BY created_at LIMIT 100`,
159
+ roomID, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id).map(({ taskToken, membershipID, recipientRoomId, ...delivery }) => delivery) };
160
+ });
161
+ if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "admin room not found" : "binding is no longer active" }, result.status);
162
+ return json(result);
163
+ }
164
+
165
+ async function acknowledge(request: Request): Promise<Response> {
166
+ const body: unknown = await request.json();
167
+ if (!object(body) || typeof body.id !== "string" || typeof body.sessionID !== "string" || typeof body.receiverOwnerID !== "string") return json({ error: "invalid acknowledgement" }, 400);
168
+ const ack = body as { id: string; sessionID: string; receiverOwnerID: string };
169
+ const ok = await tx(db => {
170
+ const delivery = one<AckDelivery>(db, "SELECT * FROM admin_deliveries WHERE id=? AND acknowledged=0", ack.id);
171
+ if (!delivery || delivery.session_id !== ack.sessionID || delivery.owner_id !== ack.receiverOwnerID) return false;
172
+ const b = binding(db, delivery.admin_room_id);
173
+ if (!b || b.generation !== delivery.generation || !validCurrent(db, b) ||
174
+ !isAgentMember(db, delivery.recipient_room_id, delivery.session_id, delivery.owner_id, delivery.membership_id)) return false;
175
+ if (delivery.kind === "supervision" && (delivery.recipient_room_id !== b.target_room_id ||
176
+ delivery.session_id !== b.session_id || delivery.owner_id !== b.receiver_owner_id || delivery.membership_id !== b.membership_id ||
177
+ (!isOperator(request) && !hasAdminCapability(request, b)))) return false;
178
+ if (delivery.kind !== "task" && delivery.kind !== "supervision") return false;
179
+ return exec(db, "UPDATE admin_deliveries SET acknowledged=1 WHERE id=? AND acknowledged=0", ack.id).changes === 1;
180
+ });
181
+ return json({ ok });
182
+ }
@@ -3,40 +3,41 @@
3
3
  [hidden] { display: none !important; }
4
4
 
5
5
  :root {
6
- --font-sans: system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Noto Sans SC","Noto Sans CJK SC","Source Han Sans SC","Microsoft YaHei",sans-serif;
6
+ --font-sans: "Avenir Next", "Segoe UI Variable", system-ui, -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Noto Sans SC", "Microsoft YaHei", sans-serif;
7
+ --font-display: "Iowan Old Style", "Baskerville", "Songti SC", Georgia, serif;
7
8
  --font-mono: ui-monospace,"SF Mono","Cascadia Mono","JetBrains Mono",Consolas,monospace;
8
- --bg: #f2f4f6;
9
- --surface: #ffffff;
10
- --surface-2: #f3f5f7;
11
- --ink: #1c2631;
12
- --ink-2: #465462;
13
- --ink-3: #566574;
14
- --line: #d5dce3;
15
- --accent: #286783;
16
- --accent-ink: #ffffff;
17
- --accent-soft: #e2f0f5;
18
- --danger: #b23a2e;
19
- --danger-soft: #f9e7e2;
20
- --mention-blue: #2e6cc4;
21
- --shadow: 0 1px 2px rgb(48 38 25 / .05), 0 12px 32px rgb(48 38 25 / .08);
9
+ --bg: #f3f1ea;
10
+ --surface: #fffefa;
11
+ --surface-2: #f2f0e8;
12
+ --ink: #1e2c29;
13
+ --ink-2: #455651;
14
+ --ink-3: #63716b;
15
+ --line: #dcded4;
16
+ --accent: #22695c;
17
+ --accent-ink: #fffdf6;
18
+ --accent-soft: #e1eee6;
19
+ --danger: #a84437;
20
+ --danger-soft: #f7e8e1;
21
+ --mention-blue: #266c72;
22
+ --shadow: 0 2px 5px rgb(34 53 47 / .05), 0 18px 44px rgb(34 53 47 / .09);
22
23
  }
23
24
 
24
25
  @media (prefers-color-scheme: dark) {
25
26
  :root {
26
- --bg: #151a20;
27
- --surface: #1e252d;
28
- --surface-2: #28313a;
29
- --ink: #edf2f7;
30
- --ink-2: #cad3dc;
31
- --ink-3: #b3bfca;
32
- --line: #3a4652;
33
- --accent: #75b6cc;
34
- --accent-ink: #10242c;
35
- --accent-soft: #263f49;
36
- --danger: #e27a6c;
37
- --danger-soft: #3a201b;
38
- --mention-blue: #86a9ee;
39
- --shadow: 0 1px 2px rgb(0 0 0 / .4), 0 14px 36px rgb(0 0 0 / .45);
27
+ --bg: #111b19;
28
+ --surface: #182522;
29
+ --surface-2: #202f2b;
30
+ --ink: #edf2e9;
31
+ --ink-2: #c6d1c9;
32
+ --ink-3: #a6b3aa;
33
+ --line: #344640;
34
+ --accent: #8ac9aa;
35
+ --accent-ink: #14251e;
36
+ --accent-soft: #263d34;
37
+ --danger: #ef9580;
38
+ --danger-soft: #3a2924;
39
+ --mention-blue: #8bc8c2;
40
+ --shadow: 0 2px 6px rgb(0 0 0 / .22), 0 18px 44px rgb(0 0 0 / .32);
40
41
  }
41
42
  }
42
43
 
@@ -48,7 +49,8 @@
48
49
  line-height: 1.65;
49
50
  color: var(--ink);
50
51
  background:
51
- radial-gradient(1100px 520px at 50% -8%, color-mix(in srgb, var(--accent) 7%, transparent), transparent 65%),
52
+ radial-gradient(900px 540px at 6% 0%, color-mix(in srgb, var(--accent) 10%, transparent), transparent 68%),
53
+ radial-gradient(760px 420px at 100% 100%, color-mix(in srgb, #c6a775 7%, transparent), transparent 72%),
52
54
  var(--bg);
53
55
  -webkit-tap-highlight-color: transparent;
54
56
  }
@@ -87,10 +89,10 @@
87
89
  width: 100%;
88
90
  max-width: 424px;
89
91
  margin: auto;
90
- padding: 36px 32px 30px;
91
- background: var(--surface);
92
- border: 1px solid var(--line);
93
- border-radius: 18px;
92
+ padding: 38px 34px 32px;
93
+ background: linear-gradient(155deg, color-mix(in srgb, var(--accent-soft) 32%, var(--surface)), var(--surface) 42%);
94
+ border: 1px solid color-mix(in srgb, var(--accent) 18%, var(--line));
95
+ border-radius: 22px;
94
96
  box-shadow: var(--shadow);
95
97
  }
96
98
  .locale-control { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 20px; color: var(--ink-2); font-size: 12.5px; }
@@ -99,8 +101,8 @@
99
101
  .chat-head-actions .locale-control { margin: 0; }
100
102
  .wordmark {
101
103
  margin: 0;
102
- font-family: var(--font-sans);
103
- font-size: 30px;
104
+ font-family: var(--font-display);
105
+ font-size: 34px;
104
106
  font-weight: 700;
105
107
  letter-spacing: -.03em;
106
108
  color: var(--ink);
@@ -124,9 +126,9 @@
124
126
  color: var(--ink);
125
127
  background: var(--surface);
126
128
  border: 1px solid var(--line);
127
- border-radius: 10px;
129
+ border-radius: 12px;
128
130
  padding: 11px 13px;
129
- transition: border-color .15s, box-shadow .15s;
131
+ transition: border-color .16s, box-shadow .16s, background-color .16s;
130
132
  }
131
133
  .input::placeholder { color: var(--ink-3); }
132
134
  .input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 20%, transparent); }
@@ -144,10 +146,10 @@
144
146
  }
145
147
  .btn:active { transform: translateY(1px); }
146
148
  .btn:disabled { opacity: .5; cursor: default; }
147
- .btn.primary { background: var(--accent); color: var(--accent-ink); }
148
- .btn.primary:not(:disabled):hover { filter: brightness(1.07); }
149
- .btn.ghost { background: transparent; color: var(--ink-2); border: 1px solid var(--line); }
150
- .btn.ghost:not(:disabled):hover { color: var(--ink); border-color: var(--ink-3); }
149
+ .btn.primary { background: linear-gradient(135deg, color-mix(in srgb, var(--accent) 86%, #152d28), var(--accent)); color: var(--accent-ink); box-shadow: 0 3px 8px color-mix(in srgb, var(--accent) 18%, transparent); }
150
+ .btn.primary:not(:disabled):hover { filter: brightness(1.07); box-shadow: 0 5px 14px color-mix(in srgb, var(--accent) 22%, transparent); }
151
+ .btn.ghost { background: color-mix(in srgb, var(--surface) 78%, transparent); color: var(--ink-2); border: 1px solid var(--line); }
152
+ .btn.ghost:not(:disabled):hover { color: var(--ink); border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); background: var(--accent-soft); }
151
153
  .btn.small { padding: 8px 14px; font-size: 13.5px; }
152
154
  .btn:focus-visible, .chip:focus-visible, .room-row:focus-visible, .input:focus-visible,
153
155
  .jump:focus-visible, .copy-id:focus-visible, .locale-select:focus-visible {
@@ -163,7 +165,7 @@
163
165
  .alert {
164
166
  margin-top: 16px;
165
167
  padding: 10px 13px;
166
- border-radius: 10px;
168
+ border-radius: 12px;
167
169
  background: var(--danger-soft);
168
170
  color: var(--danger);
169
171
  font-size: 13.5px;
@@ -0,0 +1,196 @@
1
+ import { LS } from "./state.js";
2
+
3
+ export function initAdmin(app) {
4
+ const $ = app.$, dialog = $("#adminDialog");
5
+ let rooms = [], bindings = [], agents = [], taskAgents = [], viewGeneration = 0, designationGeneration = 0, taskGeneration = 0, tokenGeneration = 0;
6
+ const status = (text, error = false) => { $("#adminStatus").textContent = text; $("#adminStatus").classList.toggle("danger-text", error); };
7
+ const json = (body) => JSON.stringify(body);
8
+ const select = (node, values, label, id = (item) => item.id) => {
9
+ node.replaceChildren(new Option(label, ""), ...values.map((item) => new Option(item.name, id(item))));
10
+ };
11
+ function renderAdminRooms() {
12
+ $("#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
+ }
14
+ const clearEnrollment = () => { $("#adminEnrollment").replaceChildren(); $("#adminEnrollment").hidden = true; };
15
+ async function verifyToken() {
16
+ const generation = ++tokenGeneration, token = LS.adminToken, error = $("#adminAccessError"), button = $("#btnOpenAdmin");
17
+ error.hidden = true; button.hidden = true;
18
+ if (!token) return;
19
+ try { await app.adminApi("/admin/rooms"); if (generation === tokenGeneration && token === LS.adminToken) button.hidden = false; }
20
+ catch (failure) { if (generation === tokenGeneration) { error.textContent = failure.message; error.hidden = false; } }
21
+ }
22
+ async function open() {
23
+ const generation = ++viewGeneration;
24
+ clearEnrollment(); $("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
25
+ dialog.showModal(); status(app.t("adminLoading"));
26
+ $("#adminRoomSelect").disabled = $("#adminTargetRoom").disabled = $("#adminTargetAgent").disabled = true;
27
+ $("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = true;
28
+ $("#btnRevokeAdmin").hidden = $("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
29
+ try {
30
+ const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
31
+ if (generation !== viewGeneration || !dialog.open) return;
32
+ bindings = adminResult.rooms || []; rooms = roomResult || [];
33
+ renderAdminRooms();
34
+ $("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
35
+ select($("#adminTargetRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
36
+ select($("#adminTaskRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
37
+ if (rooms.length) $("#adminTargetRoom").value = rooms[0].id;
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; } }
43
+ }
44
+ 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) : [];
46
+ }
47
+ async function loadDesignationAgents() {
48
+ const generation = ++designationGeneration, roomId = $("#adminTargetRoom").value;
49
+ agents = []; $("#adminTargetAgent").disabled = true; select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
50
+ try {
51
+ const found = await registryAgents(roomId);
52
+ if (generation !== designationGeneration || roomId !== $("#adminTargetRoom").value) return;
53
+ agents = found; select($("#adminTargetAgent"), agents.map((agent) => ({ ...agent, name: `${agent.name} · ${agent.sessionID.slice(0, 8)}` })), app.t("chooseAgent"), (agent) => agent.sessionID); $("#adminTargetAgent").disabled = false;
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); }
64
+ }
65
+ async function loadBinding(generation = ++viewGeneration) {
66
+ const id = $("#adminRoomSelect").value;
67
+ const binding = bindings.find((item) => item.roomId === id);
68
+ $("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
69
+ $("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
70
+ $("#btnRevokeAdmin").hidden = !binding;
71
+ if (!id || !binding) return renderData({}, id);
72
+ $("#adminTargetRoom").value = binding.targetRoomId;
73
+ const targetRoomId = binding.targetRoomId;
74
+ await loadDesignationAgents();
75
+ if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || targetRoomId !== $("#adminTargetRoom").value || !dialog.open) return;
76
+ $("#adminTargetAgent").value = binding.sessionID;
77
+ try {
78
+ const base = `/admin/rooms/${encodeURIComponent(id)}`;
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
+ }
123
+ }
124
+ async function changePlan(roomId, planId, update, button) {
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(); });
131
+ $("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
132
+ $("#btnRefreshAdmin").addEventListener("click", async () => {
133
+ const id = $("#adminRoomSelect").value;
134
+ 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); }
137
+ });
138
+ $("#btnCloseAdmin").addEventListener("click", () => dialog.close());
139
+ dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); });
140
+ dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
141
+ $("#adminRoomSelect").addEventListener("change", () => { clearEnrollment(); void loadBinding(); });
142
+ $("#adminTargetRoom").addEventListener("change", () => { clearEnrollment(); void loadDesignationAgents(); });
143
+ $("#adminTargetAgent").addEventListener("change", clearEnrollment);
144
+ $("#adminTaskRoom").addEventListener("change", () => void loadTaskAgents());
145
+ $("#btnDesignateAgent").addEventListener("click", async () => {
146
+ const roomId = $("#adminRoomSelect").value, agent = agents.find((item) => item.sessionID === $("#adminTargetAgent").value);
147
+ if (!roomId || !agent || !agent.membershipID) return status(app.t("selectAdminAgent"), true);
148
+ const body = { targetRoomId: $("#adminTargetRoom").value, sessionID: agent.sessionID, receiverOwnerID: agent.receiverOwnerID || "", membershipID: agent.membershipID };
149
+ const generation = viewGeneration, button = $("#btnDesignateAgent"); button.disabled = true;
150
+ try {
151
+ const existing = bindings.some((item) => item.roomId === roomId);
152
+ 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 || body.targetRoomId !== $("#adminTargetRoom").value || agent.sessionID !== $("#adminTargetAgent").value) return;
154
+ if (!existing) bindings.push(result.adminRoom); else bindings = bindings.map((item) => item.roomId === roomId ? result.adminRoom : item);
155
+ renderAdminRooms(); $("#adminRoomSelect").value = roomId;
156
+ await loadBinding(generation);
157
+ if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value || body.targetRoomId !== $("#adminTargetRoom").value) return;
158
+ const box = $("#adminEnrollment"), instruction = document.createElement("code"), copy = document.createElement("button"), warning = document.createElement("p");
159
+ instruction.textContent = `admin(action='admin_claim',roomId='${roomId}',enrollmentKey='${result.enrollmentKey}')`;
160
+ warning.textContent = app.t("privateEnrollment", { expires: new Date(result.expiresAt).toLocaleString() });
161
+ copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
162
+ copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(instruction.textContent); status(app.t("enrollmentCopied")); } catch (error) { status(error.message, true); } });
163
+ box.replaceChildren(warning, instruction, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
164
+ } catch (error) { if (generation === viewGeneration) status(error.message, true); }
165
+ finally { button.disabled = false; }
166
+ });
167
+ $("#btnRevokeAdmin").addEventListener("click", async () => {
168
+ const id = $("#adminRoomSelect").value;
169
+ if (!id || !confirm(app.t("revokeConfirm"))) return;
170
+ 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); }
191
+ catch (error) { if (generation === viewGeneration) status(error.message, true); }
192
+ finally { button.disabled = false; }
193
+ });
194
+ $("#inAdminToken").value = LS.adminToken;
195
+ void verifyToken();
196
+ }