@alexsun-top/opencode-chat-room 0.5.5 → 0.6.0

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.
@@ -17,6 +17,7 @@ import { readInbox } from "./inbox";
17
17
  import { isReceiverOwnerID } from "../src/receiver-owner";
18
18
  import { claimWake, touchActive, wakeMentionedSessions } from "./wake";
19
19
  import { historyRoute } from "./history-route";
20
+ import { roomPayload } from "./room-payload";
20
21
  import { jsonObject } from "./json-body";
21
22
  import { roomManagement } from "./newrooms";
22
23
  import { memberRoutes } from "./member-routes";
@@ -61,17 +62,6 @@ const json = (body: unknown, status = 200) =>
61
62
  headers: { "Content-Type": "application/json" },
62
63
  });
63
64
 
64
- const serializeRoom = (r: Room) => ({
65
- id: r.id,
66
- name: r.name,
67
- ownerId: r.ownerId,
68
- createdAt: r.createdAt,
69
- participants: [...r.participants.values()],
70
- messages: r.messages,
71
- kind: r.kind ?? "group",
72
- ...(r.directSessionIDs ? { directSessionIDs: r.directSessionIDs } : {}),
73
- });
74
-
75
65
  function mutate<T>(fn: (svc: RoomService, registry: Registry) => T): Promise<T> {
76
66
  return writeState(fn);
77
67
  }
@@ -160,13 +150,14 @@ async function handle(req: Request): Promise<Response> {
160
150
  }
161
151
  if (req.method === "GET" && p === "/rooms") {
162
152
  const caller = url.searchParams.get("sessionID");
163
- const rooms = await readState((svc, registry) => svc.listRooms()
153
+ const rows = await readState((svc, registry) => svc.listRooms()
164
154
  .filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller))
165
- .map((room) => {
166
- const entry = caller ? registry[room.id]?.[caller] : undefined;
167
- // The browser keeps its watermark per tab; a new tab starts from this one.
168
- return { ...serializeRoom(room), joined: Boolean(entry), ...(entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {}) };
169
- }));
155
+ .map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
156
+ const rooms = [];
157
+ for (const { room, entry } of rows) {
158
+ // The browser keeps its watermark per tab; a new tab starts from this one.
159
+ rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...(entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {}) });
160
+ }
170
161
  return json(rooms);
171
162
  }
172
163
  const members = await memberRoutes(req, url);
@@ -214,7 +205,7 @@ async function handle(req: Request): Promise<Response> {
214
205
  }
215
206
  return created;
216
207
  });
217
- return json(serializeRoom(room), 201);
208
+ return json(await roomPayload(room), 201);
218
209
  }
219
210
  if (req.method === "GET" && p === "/inbox") {
220
211
  const sessionID = url.searchParams.get("sessionID") ?? "";
@@ -364,7 +355,7 @@ async function handle(req: Request): Promise<Response> {
364
355
  return svc.getRoom(roomId);
365
356
  });
366
357
  touchActive(sessionID); // join = active
367
- return json(serializeRoom(room), 201);
358
+ return json(await roomPayload(room), 201);
368
359
  }
369
360
  if (req.method === "POST" && m[2] === "leave") {
370
361
  await mutate((svc, reg) => {
@@ -412,7 +403,7 @@ async function handle(req: Request): Promise<Response> {
412
403
  touchActive(sessionID);
413
404
  const room = await read((svc) => svc.getRoom(roomId));
414
405
  void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
415
- return json(serializeRoom(room), 201);
406
+ return json(await roomPayload(room), 201);
416
407
  }
417
408
  const result = await appendRoomMessage(roomId, sessionID, text, isQuestion === true);
418
409
  if (result.status !== "ok") {
@@ -423,7 +414,7 @@ async function handle(req: Request): Promise<Response> {
423
414
  const room = await read((svc) => svc.getRoom(roomId));
424
415
  // ponytail: 即时唤起——仅 @ 点名成员时(核心需求)
425
416
  void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
426
- return json(serializeRoom(room), 201);
417
+ return json(await roomPayload(room), 201);
427
418
  }
428
419
  }
429
420
  const questions = p.match(/^\/rooms\/([^/]+)\/questions$/);
@@ -457,7 +448,7 @@ async function handle(req: Request): Promise<Response> {
457
448
  const room = await read((svc) =>
458
449
  svc.getRoom(decodeURIComponent(g[1]!)),
459
450
  );
460
- return json(serializeRoom(room));
451
+ return json(await roomPayload(room));
461
452
  }
462
453
  const r = p.match(/^\/rooms\/([^/]+)\/registry$/);
463
454
  if (r && req.method === "GET") {
package/server/chat.html CHANGED
@@ -99,25 +99,20 @@
99
99
  <button class="btn ghost small" type="button" data-token-save="inTokenChat" data-i18n="save">Save</button>
100
100
  <p id="tokenHint" class="hint" data-i18n="tokenRequired" hidden>The server requires an access token (401).</p>
101
101
  <p class="hint" data-i18n="privacyNote">Anyone with the shared token can read direct messages and manage rooms; the server can read them too.</p>
102
- <details class="admin-access" aria-labelledby="adminAccessHeading">
103
- <summary id="adminAccessHeading" data-i18n="adminAccess">Administration</summary>
104
- <label class="field"><span class="field-label" data-i18n="adminToken">Administration token</span><input id="inAdminToken" class="input" type="password" autocomplete="off" spellcheck="false"></label>
105
- <button id="btnSaveAdminToken" class="btn ghost small" type="button" data-i18n="save">Save</button>
106
- <p id="adminAccessError" class="hint danger-text" role="alert" hidden></p>
107
- <button id="btnOpenAdmin" class="btn ghost small" type="button" data-i18n="openAdministration" hidden>Open administration</button>
108
- </details>
109
102
  </div>
110
103
  </div>
111
104
  </div>
112
105
  </aside>
113
- <dialog id="adminDialog" class="admin-dialog" aria-labelledby="adminHeading">
114
- <header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><div class="admin-dialog-actions"><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></div></header>
115
- <p id="adminStatus" class="hint" role="status" aria-live="polite"></p>
116
- <div class="admin-guide"><p class="hint admin-scope-note" data-i18n="adminBindingGuide">Choose a room, then select a registered member. They must privately accept the invitation to finish setup.</p><label class="field"><span class="field-label" data-i18n="adminRoomLabel">Room to administer</span><select id="adminRoomSelect" class="admin-select"></select></label>
117
- <label class="field"><span class="field-label" data-i18n="targetAgent">Registered agent</span><select id="adminTargetAgent" class="admin-select"></select></label>
118
- <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="adminDesignateAgent">Designate agent</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
119
- <button id="btnRevokeAdmin" class="btn ghost small danger-text" type="button" data-i18n="revokeDesignation">Revoke designation</button>
120
- </div>
106
+ <dialog id="editRoomDialog" class="admin-dialog" aria-labelledby="editRoomHeading">
107
+ <header class="admin-dialog-head"><h2 id="editRoomHeading" data-i18n="editRoom">Edit room</h2><div class="admin-dialog-actions"><button id="btnCloseEditRoom" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></div></header>
108
+ <p id="editRoomStatus" class="hint" role="status" aria-live="polite"></p>
109
+ <form id="editRoomForm" class="admin-guide">
110
+ <label class="field"><span class="field-label" data-i18n="roomNameLabel">Room name</span><input id="editRoomName" class="input" maxlength="64" autocomplete="off" required></label>
111
+ <label class="field"><span class="field-label" data-i18n="roomDescriptionLabel">Description</span><textarea id="editRoomDescription" class="input" rows="3" maxlength="2000"></textarea></label>
112
+ <label class="field"><span class="field-label" data-i18n="adminAgentLabel">Administrator agent</span><select id="editRoomAdmin" class="admin-select"></select></label>
113
+ <p class="hint" data-i18n="adminAgentHint">The designated agent can inspect all rooms and their history with the admin tool. Leave empty for none.</p>
114
+ <button class="btn primary small" type="submit" data-i18n="save">Save</button>
115
+ </form>
121
116
  </dialog>
122
117
  <button id="roomDrawerBackdrop" class="room-drawer-backdrop" type="button" aria-label="Close room list" data-i18n-aria-label="closeRoomList" hidden></button>
123
118
  <header class="chat-head">
@@ -128,6 +123,7 @@
128
123
  <span class="mono" id="roomIdShort"></span><span class="copy-ok" data-i18n="copied">Copied</span>
129
124
  </button>
130
125
  </p>
126
+ <p id="roomDescription" class="room-description" hidden></p>
131
127
  </div>
132
128
  <div class="chat-head-actions">
133
129
  <div class="anchor questions-anchor">
@@ -184,6 +180,7 @@
184
180
  <div class="anchor room-options-anchor">
185
181
  <button class="chip" type="button" id="btnRoomOptions" aria-haspopup="true" aria-expanded="false" aria-controls="roomOptions"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></svg><span class="action-label" data-i18n="roomOptions">Options</span></button>
186
182
  <div class="panel room-options-panel" id="roomOptions" hidden>
183
+ <button class="menu-action" type="button" id="btnEditRoom" data-i18n="editRoom" hidden>Edit room</button>
187
184
  <button class="menu-action" type="button" id="btnLeave" data-i18n="leave">Leave room</button>
188
185
  <button class="menu-action danger-text" type="button" id="btnDeleteRoom" data-i18n="deleteRoom">Delete room</button>
189
186
  </div>
@@ -1,13 +1,12 @@
1
1
  import RoomService, { RoomError, type Room } from "../src/room-service";
2
2
  import { databasePath, writeState } from "../src/store";
3
3
  import { writeSqliteStateWithDatabase } from "../src/sqlite-state";
4
- import { isOperator } from "./admin-auth";
4
+ import { binding, enroll, exec } from "./admin-state";
5
+ import { roomPayload } from "./room-payload";
5
6
  import { clearPendingAdmission } from "../src/queue";
6
7
  import { removeRoomResources } from "../src/resources";
7
8
 
8
9
  const json = (body: unknown, status = 200) => Response.json(body, { status });
9
- class ProtectedRoomDeletion extends Error {}
10
- const serializeRoom = (room: Room) => ({ ...room, participants: [...room.participants.values()], messages: room.messages, kind: room.kind ?? "group" });
11
10
  const mutate = <T>(fn: (service: RoomService, registry: import("../src/store").Registry) => T) => writeState(fn);
12
11
  async function objectBody(req: Request): Promise<Record<string, unknown> | undefined> {
13
12
  const value: unknown = await req.json();
@@ -43,7 +42,7 @@ export async function roomManagement(req: Request, url: URL): Promise<Response |
43
42
  }
44
43
  return { room: direct, created: !existing };
45
44
  });
46
- return json(serializeRoom(result.room), result.created ? 201 : 200);
45
+ return json(await roomPayload(result.room), result.created ? 201 : 200);
47
46
  }
48
47
  const kick = p.match(/^\/rooms\/([^/]+)\/kick$/);
49
48
  if (kick && req.method === "POST") {
@@ -68,35 +67,62 @@ export async function roomManagement(req: Request, url: URL): Promise<Response |
68
67
  clearPendingAdmission(result.target, roomId, Number.MAX_SAFE_INTEGER);
69
68
  return json({ ok: true, createdAt: result.message.createdAt });
70
69
  }
70
+ const edit = p.match(/^\/rooms\/([^/]+)$/);
71
+ if (edit && req.method === "PATCH") {
72
+ const roomId = decodeURIComponent(edit[1]!);
73
+ const body = await objectBody(req);
74
+ if (!body) return json({ error: "JSON object body is required" }, 400);
75
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
76
+ if (!sessionID || sessionID.length > 128) return json({ error: "sessionID is required" }, 400);
77
+ if (body.name !== undefined && (typeof body.name !== "string" || !body.name.trim() || body.name.trim().length > 64)) return json({ error: "name must be 1-64 characters" }, 400);
78
+ if (body.description !== undefined && (typeof body.description !== "string" || body.description.length > 2000)) return json({ error: "description too long (max 2000)" }, 400);
79
+ if (body.adminSessionID !== undefined && body.adminSessionID !== null && (typeof body.adminSessionID !== "string" || body.adminSessionID.length > 128)) return json({ error: "invalid adminSessionID" }, 400);
80
+ const name = typeof body.name === "string" ? body.name.trim() : undefined;
81
+ const description = typeof body.description === "string" ? body.description.trim() : undefined;
82
+ const adminSessionID = typeof body.adminSessionID === "string" ? body.adminSessionID : body.adminSessionID === null ? null : undefined;
83
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
84
+ const room = svc.getRoom(roomId);
85
+ const actor = registry[roomId]?.[sessionID];
86
+ if (!actor) return { status: 409 as const, error: "actor is not a room member" };
87
+ if (actor.name !== room.ownerId) return { status: 403 as const, error: "only the room owner can edit the room" };
88
+ const changes: string[] = [];
89
+ if (name !== undefined && name !== room.name) { changes.push(`${actor.name} renamed the room from "${room.name}" to "${name}"`); room.name = name; }
90
+ if (description !== undefined && description !== (room.description ?? "")) { room.description = description || undefined; changes.push(`${actor.name} updated the room description`); }
91
+ if (adminSessionID !== undefined) {
92
+ if (!adminSessionID) {
93
+ if (binding(db, roomId)) { exec(db, "DELETE FROM admin_rooms WHERE room_id=?", roomId); changes.push(`${actor.name} revoked the administrator designation`); }
94
+ } else {
95
+ const agent = registry[roomId]?.[adminSessionID];
96
+ if (!agent?.membershipID || !(agent.protocol === "v1" || agent.protocol === "v2" || agent.receiverOwnerID || agent.host)) return { status: 409 as const, error: "administrator must be a registered agent member" };
97
+ const previous = binding(db, roomId);
98
+ if (previous?.session_id !== adminSessionID) {
99
+ if (!enroll(db, roomId, roomId, adminSessionID, agent.receiverOwnerID ?? "", agent.membershipID, (previous?.generation ?? 0) + 1)) return { status: 409 as const, error: "this room cannot be designated as an admin room" };
100
+ changes.push(`${actor.name} designated ${agent.name} as administrator`);
101
+ }
102
+ }
103
+ }
104
+ if (changes.length) svc.addEvent(roomId, changes.join("; "));
105
+ return { room };
106
+ });
107
+ if ("error" in result) return json({ error: result.error }, result.status);
108
+ return json(await roomPayload(result.room));
109
+ }
71
110
  const remove = p.match(/^\/rooms\/([^/]+)$/);
72
111
  if (remove && req.method === "DELETE") {
73
112
  const roomId = decodeURIComponent(remove[1]!);
74
113
  const body = await objectBody(req);
75
114
  if (!body) return json({ error: "JSON object body is required" }, 400);
76
115
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
77
- if (body.sessionID !== undefined && (typeof body.sessionID !== "string" || sessionID.length > 128)) return json({ error: "invalid sessionID" }, 400);
78
- if (!sessionID && !isOperator(req)) return json({ error: "sessionID is required" }, 400);
79
- let sessions: string[];
80
- try {
81
- sessions = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
82
- svc.getRoom(roomId);
83
- const hasAdminSchema = db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='admin_rooms'").get();
84
- const protectedRoom = Boolean(hasAdminSchema && db.query("SELECT 1 FROM admin_rooms WHERE room_id=? OR target_room_id=? LIMIT 1").get(roomId, roomId));
85
- const operator = isOperator(req);
86
- if (protectedRoom && !operator) throw new ProtectedRoomDeletion();
87
- // Only an operator may bypass membership when deleting an admin room or its target.
88
- if (!protectedRoom || !operator) {
89
- if (!registry[roomId]?.[sessionID]) throw new RoomError("NOT_JOINED", "actor is not a room member");
90
- }
91
- const removed = Object.keys(registry[roomId] ?? {});
92
- svc.deleteRoom(roomId);
93
- delete registry[roomId];
94
- return removed;
95
- });
96
- } catch (error) {
97
- if (error instanceof ProtectedRoomDeletion) return json({ error: "operator token required to delete a designated admin or target room" }, 403);
98
- throw error;
99
- }
116
+ if (!sessionID || sessionID.length > 128) return json({ error: "sessionID is required" }, 400);
117
+ // Admin bindings cascade with the room (foreign keys), so members may delete.
118
+ const sessions = await mutate((svc, registry) => {
119
+ svc.getRoom(roomId);
120
+ if (!registry[roomId]?.[sessionID]) throw new RoomError("NOT_JOINED", "actor is not a room member");
121
+ const removed = Object.keys(registry[roomId] ?? {});
122
+ svc.deleteRoom(roomId);
123
+ delete registry[roomId];
124
+ return removed;
125
+ });
100
126
  await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
101
127
  for (const sid of sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
102
128
  return json({ ok: true });
@@ -0,0 +1,29 @@
1
+ import { countOpenQuestions, readHistory } from "../src/store";
2
+ import type { Room } from "../src/room-service";
3
+ import { binding, tx } from "./admin-state";
4
+
5
+ // Initial page of history sent when a room is opened; older pages load on scroll.
6
+ export const ROOM_WINDOW = 100;
7
+
8
+ // Room meta + participants from memory, messages as a bounded newest-first page
9
+ // from SQLite so opening a room never downloads the whole history.
10
+ export async function roomPayload(room: Room, limit = ROOM_WINDOW) {
11
+ const page = await readHistory(room.id, undefined, limit);
12
+ const admin = await tx(db => binding(db, room.id));
13
+ const openQuestions = await countOpenQuestions(room.id);
14
+ return {
15
+ id: room.id,
16
+ name: room.name,
17
+ description: room.description ?? "",
18
+ ownerId: room.ownerId,
19
+ createdAt: room.createdAt,
20
+ participants: [...room.participants.values()],
21
+ messages: page.messages,
22
+ kind: room.kind ?? "group",
23
+ ...(room.directSessionIDs ? { directSessionIDs: room.directSessionIDs } : {}),
24
+ hasMore: page.hasMore,
25
+ nextBeforeSeq: page.nextBeforeSeq,
26
+ adminSessionID: admin?.session_id ?? null,
27
+ openQuestions,
28
+ };
29
+ }
@@ -98,9 +98,9 @@ To retrieve an attachment from a room message, call `room` with `action: "read_r
98
98
 
99
99
  ## Administrator supervision
100
100
 
101
- The separate `admin` tool supports operator-designated administrator rooms in central mode. A normal room token, a mention, or room membership does not grant administrator privileges. Do not attempt to appoint yourself or another Agent.
101
+ The separate `admin` tool supports owner-designated administrator rooms in central mode. A normal room token, a mention, or room membership does not grant administrator privileges. Do not attempt to appoint yourself or another Agent.
102
102
 
103
- Designation happens in the operator's administration panel and applies immediately; it stays in effect until the operator revokes it. There is no enrollment code to redeem. If the tool reports that the session is not designated, the operator must designate it first.
103
+ The room owner designates the administrator from the room's Options → Edit room dialog; it applies immediately and stays in effect until the owner revokes it. There is no enrollment code to redeem. If the tool reports that the session is not designated, the room owner must designate it first.
104
104
 
105
105
  For a designated supervisor, `admin_overview` lists rooms and members; `admin_history` reads bounded target-room history. To assign work, send a room message to the intended Agent. For scheduled work, create a room reminder containing the task and an @ mention.
106
106
 
@@ -21,6 +21,7 @@ export type Message = {
21
21
  export type Room = {
22
22
  id: string;
23
23
  name: string;
24
+ description?: string;
24
25
  ownerId: string;
25
26
  participants: Map<string, Participant>;
26
27
  messages: Message[];
@@ -147,6 +147,7 @@ async function ensureRoomColumns(db: Database): Promise<void> {
147
147
  if (!columns.some((column) => column.name === "kind")) db.exec("ALTER TABLE rooms ADD COLUMN kind TEXT NOT NULL DEFAULT 'group'");
148
148
  if (!columns.some((column) => column.name === "direct_sessions")) db.exec("ALTER TABLE rooms ADD COLUMN direct_sessions TEXT");
149
149
  if (!columns.some((column) => column.name === "direct_pair")) db.exec("ALTER TABLE rooms ADD COLUMN direct_pair TEXT");
150
+ if (!columns.some((column) => column.name === "description")) db.exec("ALTER TABLE rooms ADD COLUMN description TEXT");
150
151
  const registry = db.query("PRAGMA table_info(registry)").all() as Array<{ name: string }>;
151
152
  if (!registry.some((column) => column.name === "membership_id")) db.exec("ALTER TABLE registry ADD COLUMN membership_id TEXT");
152
153
  if (!registry.some((column) => column.name === "work_state")) db.exec("ALTER TABLE registry ADD COLUMN work_state TEXT");
@@ -261,7 +262,7 @@ function validateRegistry(value: unknown): Registry {
261
262
  }
262
263
 
263
264
  function insertRoom(db: Database, room: Room): void {
264
- db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair) VALUES(?,?,?,?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null);
265
+ db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description) VALUES(?,?,?,?,?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null);
265
266
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
266
267
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
267
268
  const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by) VALUES(?,?,?,?,?,?,?,?,?)");
@@ -280,7 +281,7 @@ function replaceRegistry(db: Database, registry: Registry): void {
280
281
  }
281
282
 
282
283
  function persistState(db: Database, rooms: Room[], registry: Registry): void {
283
- const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at,kind=excluded.kind,direct_sessions=excluded.direct_sessions,direct_pair=excluded.direct_pair");
284
+ const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at,kind=excluded.kind,direct_sessions=excluded.direct_sessions,direct_pair=excluded.direct_pair,description=excluded.description");
284
285
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
285
286
  const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by) VALUES(?,?,?,?,?,?,?,?,?)");
286
287
  const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
@@ -289,7 +290,7 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
289
290
  const deleteRoom = db.query("DELETE FROM rooms WHERE id=?");
290
291
  for (const row of existing) if (!keep.has(row.id)) deleteRoom.run(row.id);
291
292
  for (const room of rooms) {
292
- roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null);
293
+ roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null);
293
294
  removeParticipants.run(room.id);
294
295
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
295
296
  for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt, m.isQuestion ? 1 : 0, m.answerToMessageID ?? null, m.answeredByMessageID ?? null);
@@ -298,14 +299,14 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
298
299
  }
299
300
 
300
301
  function readState(db: Database): State {
301
- const roomRows = db.query("SELECT id,name,owner_id,created_at,kind,direct_sessions,direct_pair FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number | null>>;
302
+ const roomRows = db.query("SELECT id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number | null>>;
302
303
  const rooms = roomRows.map((r): Room => {
303
304
  const participants = new Map<string, Participant>();
304
305
  for (const p of db.query("SELECT id,name,joined_at FROM participants WHERE room_id=?").all(String(r.id)) as Array<Record<string, string | number>>) {
305
306
  participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
306
307
  }
307
308
  const messages = db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 500").all(String(r.id)) as Array<Record<string, string | number | null>>;
308
- return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), kind: r.kind === "direct" ? "direct" : "group", ...(r.direct_sessions ? { directSessionIDs: JSON.parse(String(r.direct_sessions)) as string[] } : {}), ...(r.direct_pair ? { directPair: String(r.direct_pair) } : {}), participants,
309
+ return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), kind: r.kind === "direct" ? "direct" : "group", ...(r.description ? { description: String(r.description) } : {}), ...(r.direct_sessions ? { directSessionIDs: JSON.parse(String(r.direct_sessions)) as string[] } : {}), ...(r.direct_pair ? { directPair: String(r.direct_pair) } : {}), participants,
309
310
  messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
310
311
  text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}), ...(m.is_question ? { isQuestion: true } : {}), ...(m.answer_to ? { answerToMessageID: String(m.answer_to) } : {}), ...(m.answered_by ? { answeredByMessageID: String(m.answered_by) } : {}) })) };
311
312
  });
@@ -353,6 +354,12 @@ export async function readQuestions(file: string, roomID: string): Promise<Messa
353
354
  return (db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL ORDER BY seq").all(roomID) as Array<Record<string, string | number | null>>).map(rowMessage);
354
355
  }
355
356
 
357
+ export async function countOpenQuestions(file: string, roomID: string): Promise<number> {
358
+ const db = await openStateDatabase(file);
359
+ const row = db.query("SELECT COUNT(*) AS count FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL").get(roomID) as { count: number };
360
+ return Number(row.count);
361
+ }
362
+
356
363
  export async function answerQuestion(file: string, roomID: string, questionID: string, sessionID: string, text: string): Promise<{ status: "ok"; answer: Message } | { status: "missing" | "member" | "question" | "answered" }> {
357
364
  const db = await openStateDatabase(file);
358
365
  return immediate(db, () => {
@@ -367,6 +374,7 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
367
374
  db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to) VALUES(?,?,?,?,?,?,0,?)").run(answer.id, roomID, answer.senderId, sessionID, text, answer.createdAt, questionID);
368
375
  const update = db.query("UPDATE messages SET answered_by=? WHERE room_id=? AND id=? AND is_question=1 AND answered_by IS NULL").run(answer.id, roomID, questionID);
369
376
  if (update.changes !== 1) throw new Error("question answer race");
377
+ noteMessageInsert(db, roomID);
370
378
  return { status: "ok", answer };
371
379
  });
372
380
  }
@@ -385,6 +393,7 @@ export async function appendRoomMessage(file: string, roomID: string, sessionID:
385
393
  };
386
394
  db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)")
387
395
  .run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0);
396
+ noteMessageInsert(db, roomID);
388
397
  return { status: "ok", message };
389
398
  });
390
399
  }
@@ -401,10 +410,27 @@ export async function sendReply(file: string, roomID: string, targetID: string,
401
410
  const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
402
411
  const message: Message = { id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name, senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1), answerToMessageID: targetID };
403
412
  db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to) VALUES(?,?,?,?,?,?,0,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, targetID);
413
+ noteMessageInsert(db, roomID);
404
414
  return { status: "ok", message };
405
415
  });
406
416
  }
407
417
 
418
+ // Per-room retention bound. Trimming runs lazily (every 1024 inserts) so the
419
+ // hot insert path stays a single statement.
420
+ export const MAX_RETAINED_MESSAGES = 1_000_000;
421
+ const retentionCounters = new Map<string, number>();
422
+
423
+ export function enforceRetention(db: Database, roomID: string, limit = MAX_RETAINED_MESSAGES): void {
424
+ db.query("DELETE FROM messages WHERE room_id=? AND seq <= (SELECT seq FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1 OFFSET ?)").run(roomID, roomID, limit);
425
+ }
426
+
427
+ function noteMessageInsert(db: Database, roomID: string): void {
428
+ const count = (retentionCounters.get(roomID) ?? 0) + 1;
429
+ if (count < 1024) { retentionCounters.set(roomID, count); return; }
430
+ retentionCounters.set(roomID, 0);
431
+ enforceRetention(db, roomID);
432
+ }
433
+
408
434
  function questionExcerpt(text: string): string {
409
435
  const chars = Array.from(text);
410
436
  return chars.length <= 200 ? text : `${chars.slice(0, 100).join("")}…${chars.slice(-100).join("")}`;
package/src/store.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import path from "node:path";
5
5
  import os from "node:os";
6
6
  import RoomService, { type Message, type Room } from "./room-service";
7
- import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
7
+ import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, countOpenQuestions as sqliteCountOpenQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
8
8
 
9
9
  export function statePath(): string {
10
10
  // JSON path remains the migration source; SQLite lives beside it.
@@ -35,6 +35,7 @@ export async function readHistory(roomID: string, beforeSeq?: number, limit = 10
35
35
  return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
36
36
  }
37
37
  export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
38
+ export async function countOpenQuestions(roomID: string): Promise<number> { return sqliteCountOpenQuestions(databasePath(), roomID); }
38
39
  export function acknowledgeRead(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeRead(databasePath(), roomID, sessionID, ts); }
39
40
  export function acknowledgeQueued(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeQueued(databasePath(), roomID, sessionID, ts); }
40
41
  export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }