@alexsun-top/opencode-chat-room 0.8.7 → 0.8.8

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.
@@ -717,18 +717,17 @@
717
717
  #roomList > li > .room-row, #roomListChat > li > .room-row { flex: 1; min-width: 0; }
718
718
  .room-row[draggable="true"] { cursor: grab; }
719
719
  .room-row.dragging { opacity: .45; }
720
+ .room-row.dragging { opacity: .45; }
721
+ /* Insertion line: one clear target while dragging, no outline box. */
720
722
  .room-row.drop-before { box-shadow: inset 0 2px 0 var(--accent); }
721
723
  .room-row.drop-after { box-shadow: inset 0 -2px 0 var(--accent); }
722
- .room-move { display: none; flex-direction: column; gap: 2px; margin-left: 2px; }
723
- .room-move-btn { display: grid; place-items: center; width: 26px; height: 24px; padding: 0; border: 1px solid transparent; border-radius: 7px; color: var(--ink-3); background: transparent; cursor: pointer; }
724
- .room-move-btn:hover { color: var(--accent); border-color: var(--line); background: var(--surface); }
725
- .room-move-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
726
- .room-move-btn:disabled { opacity: .3; cursor: default; }
727
- .room-move-btn svg { width: 14px; height: 14px; }
728
- @media (hover: none), (pointer: coarse) {
729
- .room-move { display: flex; }
724
+ .room-row[draggable="true"] { cursor: grab; }
725
+ .room-grip { display: none; margin-left: 4px; padding: 0 4px; color: var(--ink-3); touch-action: none; cursor: grab; user-select: none; }
726
+ @media (pointer: coarse) {
727
+ .room-grip { display: inline-block; }
730
728
  .room-row[draggable="true"] { cursor: pointer; }
731
729
  }
730
+ }
732
731
  #roomList[aria-busy="true"], #roomListChat[aria-busy="true"] { opacity: .6; transition: opacity .15s ease; }
733
732
  #btnRefreshRooms.is-refreshing svg { animation: spin .8s linear infinite; }
734
733
  @media (prefers-reduced-motion: reduce) { #btnRefreshRooms.is-refreshing svg { animation: none; opacity: .6; } }
@@ -171,6 +171,23 @@ export function createInboundRelay(config: ChannelConfig): {
171
171
  ).run(event.eventId, route.to.room, Date.now());
172
172
  if (Number(inserted.changes) === 0) return;
173
173
  svc.addEvent(route.to.room, body);
174
+ // Remember where this room's inbound came from so a reply can return
175
+ // to the same chat without a per-chat rule.
176
+ db.exec(
177
+ `CREATE TABLE IF NOT EXISTS channel_inbound_sources (
178
+ room_id TEXT NOT NULL,
179
+ platform TEXT NOT NULL,
180
+ account TEXT NOT NULL,
181
+ chat_id TEXT NOT NULL,
182
+ last_at INTEGER NOT NULL,
183
+ PRIMARY KEY (room_id, platform, account, chat_id)
184
+ )`,
185
+ );
186
+ db.query(
187
+ `INSERT INTO channel_inbound_sources (room_id, platform, account, chat_id, last_at)
188
+ VALUES (?, ?, ?, ?, ?)
189
+ ON CONFLICT(room_id, platform, account, chat_id) DO UPDATE SET last_at = excluded.last_at`,
190
+ ).run(route.to.room, event.source.platform, event.source.accountId, route.from.room, Date.now());
174
191
  });
175
192
  }
176
193
  },
@@ -465,7 +482,7 @@ async function isRoomMember(roomId: string, sessionID: string): Promise<boolean>
465
482
  }
466
483
 
467
484
  /** Targets of rules whose source is this room's forward requests and whose account is ready. */
468
- function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[] {
485
+ async function forwardTargets(runtime: ChannelsRuntime, roomId: string): Promise<RuleTarget[]> {
469
486
  const probe: IngestEvent = {
470
487
  schemaVersion: EVENT_SCHEMA_VERSION,
471
488
  eventId: "forward-targets",
@@ -480,6 +497,7 @@ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[]
480
497
  const targets: RuleTarget[] = [];
481
498
  for (const rule of matchRules(config, probe)) {
482
499
  for (const target of rule.to) {
500
+ if (target.room === "*") continue;
483
501
  if (runtime.host.targetStatus(target.platform, target.account) !== "ready") continue;
484
502
  const key = `${target.platform}/${target.account}/${target.room}`;
485
503
  if (seen.has(key)) continue;
@@ -487,6 +505,24 @@ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[]
487
505
  targets.push(target);
488
506
  }
489
507
  }
508
+ // Dynamic targets: only rooms whose rules declare a wildcard target may send
509
+ // a reply back to a chat that wrote to them; the server records the chat.
510
+ const wildcards = matchRules(config, probe)
511
+ .flatMap((rule) => rule.to)
512
+ .filter((target) => target.room === "*");
513
+ if (wildcards.length) {
514
+ const db = await openStateDatabase(databasePath());
515
+ const rows = db.query(
516
+ "SELECT platform, account, chat_id FROM channel_inbound_sources WHERE room_id = ? ORDER BY last_at DESC LIMIT 20",
517
+ ).all(roomId) as Array<{ platform: string; account: "string"; chat_id: string }>;
518
+ for (const row of rows) {
519
+ const matched = wildcards.find((target) => target.platform === row.platform && target.account === row.account);
520
+ if (!matched || seen.has(`${row.platform}/${row.account}/${row.chat_id}`)) continue;
521
+ if (runtime.host.targetStatus(row.platform, row.account) !== "ready") continue;
522
+ seen.add(`${row.platform}/${row.account}/${row.chat_id}`);
523
+ targets.push({ platform: row.platform, account: row.account, room: row.chat_id });
524
+ }
525
+ }
490
526
  return targets;
491
527
  }
492
528
 
@@ -539,7 +575,7 @@ export async function channelRoutes(
539
575
 
540
576
  const message = await readForwardableMessage(roomId, messageId, sessionID);
541
577
  if (!message) return json({ error: "message not found" }, 404);
542
- if (!forwardTargets(runtime, roomId).some((candidate) =>
578
+ if (!(await forwardTargets(runtime, roomId)).some((candidate) =>
543
579
  candidate.platform === target.platform && candidate.account === target.account && candidate.room === target.room)) {
544
580
  return json({ error: "forward target is unavailable" }, 409);
545
581
  }
@@ -581,5 +617,5 @@ export async function channelRoutes(
581
617
  const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
582
618
  if (!sessionID || sessionID.length > MAX_SESSION) return json({ error: "sessionID is required" }, 400);
583
619
  if (!await isRoomMember(roomId, sessionID)) return json({ error: "room not found" }, 404);
584
- return json({ targets: forwardTargets(runtime, roomId) });
620
+ return json({ targets: await forwardTargets(runtime, roomId) });
585
621
  }
@@ -7,9 +7,14 @@ import { withStateTransaction } from "../src/state/sqlite-state.ts";
7
7
  import { writeSqliteStateWithDatabase } from "../src/state/sqlite-state-store.ts";
8
8
  import { databasePath } from "../src/state/store.ts";
9
9
  import { operatorAuthorized } from "./operator-auth.ts";
10
- import { getOperatorRoom, insertOperatorAudit, listOperatorAudit, listOperatorCandidates, listOperatorRooms } from "./operator-state.ts";
10
+ import { getOperatorRoom, insertOperatorAction, insertOperatorAudit, listOperatorActions, listOperatorAudit, listOperatorCandidates, listOperatorMembers, listOperatorRooms } from "./operator-state.ts";
11
11
  import { applyOwnerTransfer } from "./room-owner.ts";
12
+ import { clearPendingAdmission } from "../src/center/queue.ts";
13
+ import { removeRoomResources } from "../src/rooms/resources.ts";
14
+ import { findJoinRequest, removeJoinRequest } from "../src/state/sqlite-state.ts";
15
+ import { joinRoomMember } from "./room-join.ts";
12
16
 
17
+ type RoomId = string;
13
18
  type OperatorOptions = { here: string; token?: string };
14
19
 
15
20
  const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
@@ -24,6 +29,9 @@ const PAGE_CSP = "default-src 'none'; script-src 'self'; style-src 'self'; conne
24
29
  // worker cannot claim them. They carry no data or credentials.
25
30
  const STATIC_FILES: Record<string, { file: string; type: string }> = {
26
31
  "/system/operator.js": { file: "assets/chat/operator.js", type: "text/javascript; charset=utf-8" },
32
+ "/system/operator-api.js": { file: "assets/chat/operator-api.js", type: "text/javascript; charset=utf-8" },
33
+ "/system/operator-i18n.js": { file: "assets/chat/operator-i18n.js", type: "text/javascript; charset=utf-8" },
34
+ "/system/operator-manage.js": { file: "assets/chat/operator-manage.js", type: "text/javascript; charset=utf-8" },
27
35
  "/system/operator.css": { file: "operator.css", type: "text/css; charset=utf-8" },
28
36
  };
29
37
 
@@ -69,8 +77,35 @@ export async function operatorRoutes(req: Request, url: URL, options: OperatorOp
69
77
  }
70
78
  const detail = p.match(/^\/system\/rooms\/([^/]+)$/);
71
79
  if (detail) {
80
+ const roomId = decodeSegment(detail[1]!);
81
+ if (req.method === "GET") return await roomDetail(roomId);
82
+ if (req.method === "DELETE") return await deleteRoom(req, roomId);
83
+ return json({ error: "method not allowed" }, 405);
84
+ }
85
+ const rename = p.match(/^\/system\/rooms\/([^/]+)\/rename$/);
86
+ if (rename) {
87
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
88
+ return await renameRoom(req, decodeSegment(rename[1]!));
89
+ }
90
+ const joins = p.match(/^\/system\/rooms\/([^/]+)\/join-requests$/);
91
+ if (joins) {
72
92
  if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
73
- return await roomDetail(decodeSegment(detail[1]!));
93
+ return await listJoins(decodeSegment(joins[1]!));
94
+ }
95
+ const joinAction = p.match(/^\/system\/rooms\/([^/]+)\/join-requests\/([^/]+)\/(approve|deny)$/);
96
+ if (joinAction) {
97
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
98
+ return await reviewJoin(decodeSegment(joinAction[1]!), decodeSegment(joinAction[2]!), joinAction[3] === "approve");
99
+ }
100
+ const memberRole = p.match(/^\/system\/rooms\/([^/]+)\/members\/role$/);
101
+ if (memberRole) {
102
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
103
+ return await setMemberRole(req, decodeSegment(memberRole[1]!));
104
+ }
105
+ const memberRemove = p.match(/^\/system\/rooms\/([^/]+)\/members\/remove$/);
106
+ if (memberRemove) {
107
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
108
+ return await removeMember(req, decodeSegment(memberRemove[1]!));
74
109
  }
75
110
  const owner = p.match(/^\/system\/rooms\/([^/]+)\/owner$/);
76
111
  if (owner) {
@@ -89,7 +124,13 @@ async function roomDetail(roomId: string): Promise<Response> {
89
124
  const detail = await readOnly((db) => {
90
125
  const room = getOperatorRoom(db, roomId);
91
126
  if (!room) return undefined;
92
- return { room, candidates: listOperatorCandidates(db, roomId), audit: listOperatorAudit(db, roomId) };
127
+ const pendingJoins = Number((db.query("SELECT COUNT(*) AS n FROM room_join_requests WHERE room_id=?").get(roomId) as { n: number } | null)?.n ?? 0);
128
+ return {
129
+ room: { ...room, admins: [...(room.adminIds ?? [])], members: listOperatorMembers(db, roomId), pendingJoins },
130
+ candidates: listOperatorCandidates(db, roomId),
131
+ audit: listOperatorAudit(db, roomId),
132
+ actions: listOperatorActions(db, roomId),
133
+ };
93
134
  });
94
135
  return detail ? json(detail) : json({ error: "not found" }, 404);
95
136
  }
@@ -148,3 +189,154 @@ async function transferOwner(req: Request, roomId: string): Promise<Response> {
148
189
  }
149
190
  return json({ changed: result.changed });
150
191
  }
192
+
193
+
194
+ async function readJson(req: Request): Promise<Record<string, unknown> | undefined> {
195
+ try {
196
+ const value: unknown = await req.json();
197
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
198
+ } catch { return undefined; }
199
+ }
200
+
201
+ async function renameRoom(req: Request, roomId: string): Promise<Response> {
202
+ const body = await readJson(req);
203
+ if (!body) return json({ error: "invalid request" }, 400);
204
+ const name = typeof body.name === "string" ? body.name.trim() : "";
205
+ if (!name || name.length > 64) return json({ error: "name must be 1-64 characters" }, 400);
206
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
207
+ let room: Room;
208
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
209
+ if ((room.kind ?? "group") !== "group") return { status: 404 as const };
210
+ const previous = room.name;
211
+ if (previous === name) return { changed: false };
212
+ room.name = name;
213
+ svcAddEvent(svc, roomId, `System operator renamed the room from "${previous}" to "${name}"`);
214
+ insertOperatorAction(db, roomId, "rename", name, previous);
215
+ return { changed: true };
216
+ });
217
+ return "status" in result ? json({ error: "not found" }, 404) : json({ changed: result.changed });
218
+ }
219
+
220
+ function svcAddEvent(svc: { addEvent(roomId: string, text: string): unknown }, roomId: string, text: string): void {
221
+ svc.addEvent(roomId, text);
222
+ }
223
+
224
+ async function deleteRoom(req: Request, roomId: string): Promise<Response> {
225
+ const body = await readJson(req);
226
+ if (!body) return json({ error: "invalid request" }, 400);
227
+ const confirmName = typeof body.name === "string" ? body.name.trim() : "";
228
+ if (!confirmName || confirmName.length > 64) return json({ error: "type the room name to confirm" }, 400);
229
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
230
+ let room: Room;
231
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
232
+ if ((room.kind ?? "group") !== "group") return { status: 404 as const };
233
+ if (room.name !== confirmName) return { status: 409 as const, error: "room name does not match" };
234
+ const sessions = Object.entries(registry[roomId] ?? {}).map(([sid]) => sid);
235
+ svc.deleteRoom(roomId);
236
+ delete registry[roomId];
237
+ insertOperatorAction(db, roomId, "delete", room.name, `${sessions.length} members`);
238
+ return { sessions };
239
+ });
240
+ if ("status" in result) return result.status === 404 ? json({ error: "not found" }, 404) : json({ error: result.error }, 409);
241
+ await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
242
+ for (const sid of result.sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
243
+ return json({ ok: true });
244
+ }
245
+
246
+ async function setMemberRole(req: Request, roomId: RoomId): Promise<Response> {
247
+ const body = await readJson(req);
248
+ if (!body) return json({ error: "invalid request" }, 400);
249
+ const name = typeof body.name === "string" ? body.name.trim() : "";
250
+ const role = body.role === "admin" || body.role === "member" ? body.role : undefined;
251
+ if (!name || name.length > 64 || !role) return json({ error: "name and role are required" }, 400);
252
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
253
+ let room: Room;
254
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
255
+ const entry = Object.values(registry[roomId] ?? {}).find((candidate) => candidate.name === name && isUser(candidate));
256
+ if (!entry) return { status: 409 as const, error: "target is not a joined human member" };
257
+ if (name === room.ownerId) return { status: 409 as const, error: "the owner is already an administrator" };
258
+ const admins = new Set(room.adminIds ?? []);
259
+ if (role === "admin") admins.add(name); else admins.delete(name);
260
+ room.adminIds = [...adminsCheck(admins)];
261
+ const ids = new Set(room.adminMembershipIDs ?? []);
262
+ if (role === "admin" && entry.membershipID) ids.add(entry.membershipID);
263
+ if (role === "member" && entry.membershipID) ids.delete(entry.membershipID);
264
+ if (ids.size) room.adminMembershipIDs = [...ids]; else delete room.adminMembershipIDs;
265
+ insertOperatorAction(db, roomId, role === "admin" ? "grant-admin" : "revoke-admin", name, "");
266
+ return { changed: true };
267
+ });
268
+ return "status" in result ? json({ error: result.error }, result.status) : json({ changed: result.changed });
269
+ }
270
+
271
+ function adminsCheck(names: Set<string>): Set<string> { return names; }
272
+
273
+ async function removeMember(req: Request, roomId: string): Promise<Response> {
274
+ const body = await readJson(req);
275
+ if (!body) return json({ error: "invalid request" }, 400);
276
+ const name = typeof body.name === "string" ? body.name.trim() : "";
277
+ if (!name || name.length > 64) return json({ error: "name is required" }, 400);
278
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
279
+ let room: Room;
280
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
281
+ if (name === room.ownerId) return { status: 409 as const, error: "the owner cannot be removed; transfer the room first" };
282
+ const sessions = Object.entries(registry[roomId] ?? {}).filter(([, entry]) => entry.name === name).map(([sid]) => sid);
283
+ if (!sessions.length) return { status: 404 as const };
284
+ for (const sid of sessions) delete registry[roomId]![sid];
285
+ for (const [id, participant] of [...room.participants]) if (participant.name === name) svc.leaveRoom(roomId, id);
286
+ if (room.adminIds) { room.adminIds = room.adminIds.filter((admin) => admin !== name); if (!room.adminIds.length) delete room.adminIds; }
287
+ insertOperatorAction(db, roomId, "remove-member", name, `${sessions.length} sessions`);
288
+ return { sessions };
289
+ });
290
+ if ("status" in result) return result.status === 404 ? json({ error: "not found" }, 404) : json({ error: result.error }, 409);
291
+ for (const sid of result.sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
292
+ return json({ ok: true });
293
+ }
294
+
295
+
296
+ async function listJoins(roomId: string): Promise<Response> {
297
+ if (!roomId || roomId.length > 128) return json({ error: "not found" }, 404);
298
+ const rows = await readOnly((db) => db.query(
299
+ "SELECT session_id AS sessionID,participant_id AS participantId,name,is_agent AS isAgent,created_at AS createdAt FROM room_join_requests WHERE room_id=? ORDER BY created_at"
300
+ ).all(roomId) as Array<{ sessionID: string; participantId: string; name: string; isAgent: number; createdAt: number }>);
301
+ return json({ requests: rows.map((row) => ({
302
+ sessionID: String(row.sessionID), participantId: String(row.participantId), name: String(row.name),
303
+ isAgent: Number(row.isAgent) === 1, createdAt: Number(row.createdAt),
304
+ })) });
305
+ }
306
+
307
+ async function reviewJoin(roomId: string, requestSessionID: string, approve: boolean): Promise<Response> {
308
+ if (!roomId || roomId.length > 128 || !requestSessionID || requestSessionID.length > 128) return json({ error: "not found" }, 404);
309
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
310
+ let room: Room;
311
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
312
+ const request = findJoinRequest(db, roomId, requestSessionID);
313
+ if (!request) return { status: 404 as const, error: "join request not found" };
314
+ if (!approve) {
315
+ removeJoinRequest(db, roomId, requestSessionID);
316
+ insertOperatorAction(db, roomId, "deny-join", request.name, "");
317
+ return { ok: true as const };
318
+ }
319
+ if (registry[roomId]?.[request.sessionID]) {
320
+ removeJoinRequest(db, roomId, requestSessionID);
321
+ return { status: 409 as const, error: "requester already joined the room" };
322
+ }
323
+ if (svc.containsParticipant(roomId, request.participantId)) {
324
+ removeJoinRequest(db, roomId, requestSessionID);
325
+ return { status: 409 as const, error: "participant name is already in use in this room" };
326
+ }
327
+ removeJoinRequest(db, roomId, requestSessionID);
328
+ joinRoomMember(svc, registry, roomId, {
329
+ sessionID: request.sessionID,
330
+ participantId: request.participantId,
331
+ name: request.name,
332
+ ...(request.protocol ? { protocol: request.protocol } : {}),
333
+ ...(request.receiverOwnerID ? { receiverOwnerID: request.receiverOwnerID } : {}),
334
+ ...(request.directory ? { directory: request.directory } : {}),
335
+ ...(request.host ? { host: request.host } : {}),
336
+ notify: true,
337
+ });
338
+ insertOperatorAction(db, roomId, "approve-join", request.name, "");
339
+ return { ok: true as const };
340
+ });
341
+ return "ok" in result ? json({ ok: true }) : json({ error: result.error }, result.status);
342
+ }
@@ -2,10 +2,21 @@ import { randomUUID } from "node:crypto";
2
2
  import { isUser } from "../src/state/roles.ts";
3
3
  import type { StateDatabase } from "../src/state/sqlite.ts";
4
4
 
5
- export type OperatorRoom = { id: string; name: string; ownerId: string };
6
- export type OperatorRoomDetail = OperatorRoom & { ownerMembershipID: string | null };
5
+ export type OperatorRoom = {
6
+ id: string; name: string; ownerId: string; kind: "group";
7
+ memberCount: number; agentCount: number; lastActiveAt: number | null;
8
+ };
9
+ export type OperatorRoomDetail = OperatorRoom & {
10
+ ownerMembershipID: string | null;
11
+ adminIds: string[];
12
+ admins: string[];
13
+ members: OperatorMember[];
14
+ pendingJoins: number;
15
+ };
16
+ export type OperatorMember = { name: string; role: "owner" | "admin" | "member"; isAgent: boolean; lastSeenAt: number | null };
7
17
  export type OperatorCandidate = { name: string; membershipID: string };
8
18
  export type OperatorAudit = { createdAt: number; previousOwner: string; targetName: string; reason: string };
19
+ export type OperatorAction = { createdAt: number; action: string; target: string; detail: string };
9
20
  export type OperatorAuditInput = {
10
21
  roomId: string;
11
22
  previousOwner: string;
@@ -17,18 +28,71 @@ export type OperatorAuditInput = {
17
28
  };
18
29
 
19
30
  export function listOperatorRooms(db: StateDatabase): OperatorRoom[] {
20
- const rows = db.query("SELECT id,name,owner_id AS ownerId FROM rooms WHERE COALESCE(kind,'group')='group' ORDER BY created_at,id").all() as Array<{ id: string; name: string; ownerId: string }>;
21
- return rows.map((row) => ({ id: String(row.id), name: String(row.name), ownerId: String(row.ownerId) }));
31
+ const rows = db.query(`SELECT r.id,r.name,r.owner_id AS ownerId,
32
+ (SELECT COUNT(*) FROM participants p WHERE p.room_id=r.id) AS memberCount,
33
+ (SELECT COUNT(*) FROM registry g WHERE g.room_id=r.id AND g.protocol IS NOT NULL) AS agentCount,
34
+ (SELECT MAX(m.created_at) FROM messages m WHERE m.room_id=r.id) AS lastActiveAt
35
+ FROM rooms r WHERE COALESCE(r.kind,'group')='group' ORDER BY r.created_at,r.id`).all() as Array<{
36
+ id: string; name: string; ownerId: string; memberCount: number; agentCount: number; lastActiveAt: number | null;
37
+ }>;
38
+ return rows.map((row) => ({
39
+ id: String(row.id), name: String(row.name), ownerId: String(row.ownerId), kind: "group" as const,
40
+ memberCount: Number(row.memberCount), agentCount: Number(row.agentCount),
41
+ lastActiveAt: row.lastActiveAt === null ? null : Number(row.lastActiveAt),
42
+ }));
43
+ }
44
+
45
+ export function listOperatorMembers(db: StateDatabase, roomId: string): OperatorMember[] {
46
+ const room = db.query("SELECT owner_id AS ownerId,admin_names AS adminNames FROM rooms WHERE id=?").get(roomId) as
47
+ { ownerId: string; admin_names?: string; adminNames: string | null } | null;
48
+ if (!room) return [];
49
+ const admins = new Set<string>(room.adminNames ? JSON.parse(String(room.adminNames)) as string[] : []);
50
+ const rows = db.query(`SELECT p.name AS name, g.protocol AS protocol, g.last_seen_at AS lastSeenAt
51
+ FROM participants p LEFT JOIN registry g ON g.room_id=p.room_id AND (g.name=p.name OR g.name=p.id)
52
+ WHERE p.room_id=? ORDER BY p.joined_at, p.name`).all(roomId) as Array<{
53
+ name: string; protocol: string | null; lastSeenAt: number | null;
54
+ }>;
55
+ return rows.map((row) => {
56
+ const name = String(row.name);
57
+ return {
58
+ name,
59
+ role: name === String(room.ownerId) ? "owner" as const : admins.has(name) ? "admin" as const : "member" as const,
60
+ isAgent: row.protocol !== null,
61
+ lastSeenAt: row.lastSeenAt === null ? null : Number(row.lastSeenAt),
62
+ };
63
+ });
64
+ }
65
+
66
+ export function listOperatorActions(db: StateDatabase, roomId: string): OperatorAction[] {
67
+ const rows = db.query("SELECT created_at AS createdAt,action,target,detail FROM system_operator_actions WHERE room_id=? ORDER BY created_at DESC,id DESC LIMIT 50").all(roomId) as Array<{
68
+ createdAt: number; action: string; target: string; detail: string;
69
+ }>;
70
+ return rows.map((row) => ({
71
+ createdAt: Number(row.createdAt), action: String(row.action), target: String(row.target), detail: String(row.detail),
72
+ }));
73
+ }
74
+
75
+ export function insertOperatorAction(db: StateDatabase, roomId: string, action: string, target: string, detail: string): void {
76
+ db.query("INSERT INTO system_operator_actions(id,room_id,actor,action,target,detail,created_at) VALUES(?,?,?,?,?,?,?)")
77
+ .run(randomUUID(), roomId, "operator", action, target.slice(0, 200), detail.slice(0, 500), Date.now());
22
78
  }
23
79
 
24
- export function getOperatorRoom(db: StateDatabase, roomId: string): OperatorRoomDetail | undefined {
25
- const row = db.query("SELECT id,name,owner_id AS ownerId,owner_membership_id AS ownerMembershipID,kind FROM rooms WHERE id=?").get(roomId) as {
80
+ export function getOperatorRoom(db: StateDatabase, roomId: string): Omit<OperatorRoomDetail, "members" | "admins" | "pendingJoins"> | undefined {
81
+ const row = db.query(`SELECT r.id,r.name,r.owner_id AS ownerId,r.owner_membership_id AS ownerMembershipID,r.kind,r.admin_names AS adminNames,
82
+ (SELECT COUNT(*) FROM participants p WHERE p.room_id=r.id) AS memberCount,
83
+ (SELECT COUNT(*) FROM registry g WHERE g.room_id=r.id AND g.protocol IS NOT NULL) AS agentCount,
84
+ (SELECT MAX(m.created_at) FROM messages m WHERE m.room_id=r.id) AS lastActiveAt
85
+ FROM rooms r WHERE r.id=?`).get(roomId) as {
26
86
  id: string; name: string; ownerId: string; ownerMembershipID: string | null; kind: string | null;
87
+ adminNames: string | null; memberCount: number; agentCount: number; lastActiveAt: number | null;
27
88
  } | null;
28
89
  if (!row || (row.kind ?? "group") !== "group") return undefined;
29
90
  return {
30
- id: String(row.id), name: String(row.name), ownerId: String(row.ownerId),
31
- ownerMembershipID: row.ownerMembershipID ? String(row.ownerMembershipID) : null,
91
+ id: String(row.id), name: String(row.name), ownerMembershipID: row.ownerMembershipID ? String(row.ownerMembershipID) : null,
92
+ ownerId: String(row.ownerId), kind: "group" as const,
93
+ memberCount: Number(row.memberCount), agentCount: Number(row.agentCount),
94
+ lastActiveAt: row.lastActiveAt === null ? null : Number(row.lastActiveAt),
95
+ adminIds: row.adminNames ? JSON.parse(String(row.adminNames)) : [],
32
96
  };
33
97
  }
34
98
 
@@ -137,3 +137,32 @@ dialog p { margin: 0 0 8px; }
137
137
  *, *::before, *::after { animation: none !important; transition: none !important; }
138
138
  .status-slot[data-busy]::after { display: none; }
139
139
  }
140
+
141
+ /* Room list, members, joins, and administrator actions. */
142
+ .operator-tools { display: flex; justify-content: flex-end; gap: 8px; flex: none; }
143
+ .room-tools { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }
144
+ .room-tools .input { flex: 1; }
145
+ .room-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
146
+ .room-meta { grid-column: 1 / -1; color: var(--ink-3); font-size: 12.5px; overflow-wrap: anywhere; }
147
+ .member-list, .join-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
148
+ .member-row, .join-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
149
+ .member-head, .join-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; min-width: 0; }
150
+ .member-name, .join-name { font-weight: 650; overflow-wrap: anywhere; }
151
+ .member-badges { display: inline-flex; flex-wrap: wrap; gap: 6px; }
152
+ .badge { display: inline-flex; align-items: center; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--ink-2); font-size: 11.5px; font-weight: 650; }
153
+ .badge.role-owner { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); color: var(--accent); }
154
+ .badge.role-admin { background: color-mix(in srgb, var(--warning) 16%, var(--surface)); color: var(--warning); }
155
+ .badge.agent { background: var(--accent-soft); color: var(--accent); }
156
+ .member-seen, .join-time { color: var(--ink-3); font-size: 12.5px; }
157
+ .member-controls, .join-controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; }
158
+ .card form, .card .btn { margin-top: 12px; }
159
+ .card .btn { margin-top: 12px; }
160
+ .danger-card { border-color: color-mix(in srgb, var(--danger) 40%, var(--line)); }
161
+ .btn.danger { background: var(--danger); color: #fffdf6; }
162
+ .btn.danger:hover { filter: brightness(1.06); }
163
+ [dir="rtl"] .member-controls, [dir="rtl"] .join-controls { justify-content: flex-start; }
164
+ @media (max-width: 560px) {
165
+ .member-row, .join-row { grid-template-columns: 1fr; }
166
+ .member-controls, .join-controls { justify-content: flex-start; }
167
+ .room-tools { flex-wrap: wrap; }
168
+ }