@alexsun-top/opencode-chat-room 0.3.2 → 0.4.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.
@@ -8,7 +8,7 @@ import RoomService, {
8
8
  type Message,
9
9
  type Room,
10
10
  } from "../src/room-service";
11
- import { readState, writeState, type Registry, type RegistryEntry } from "../src/store";
11
+ import { answerQuestion, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/store";
12
12
  import {
13
13
  admissionMatches,
14
14
  clearPendingAdmission,
@@ -273,15 +273,15 @@ async function handle(req: Request): Promise<Response> {
273
273
  if (m) {
274
274
  const roomId = decodeURIComponent(m[1]!);
275
275
  const body = (await req.json()) as Record<string, string>;
276
- const sessionID = body.sessionID ?? "";
276
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
277
277
  if (req.method === "POST" && m[2] === "join") {
278
278
  if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
279
279
  return json({ error: "invalid receiver ownership" }, 400);
280
280
  }
281
281
  // ponytail: F4/F5 — names must be non-empty, and re-joining under a
282
282
  // new name must retire the old participant (no ghost members)
283
- const id = (body.participantId ?? "").trim();
284
- const name = (body.participantName ?? "").trim();
283
+ const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
284
+ const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
285
285
  if (!id || !name || !sessionID) {
286
286
  return json(
287
287
  { error: "participantId/participantName/sessionID are required" },
@@ -371,6 +371,8 @@ async function handle(req: Request): Promise<Response> {
371
371
  return json({ ok: true });
372
372
  }
373
373
  if (req.method === "POST" && m[2] === "messages") {
374
+ const isQuestion = (body as Record<string, unknown>).isQuestion;
375
+ if (isQuestion !== undefined && typeof isQuestion !== "boolean") return json({ error: "isQuestion must be a boolean" }, 400);
374
376
  // ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
375
377
  const text = (body.text ?? "").trim();
376
378
  if (!text) {
@@ -383,7 +385,7 @@ async function handle(req: Request): Promise<Response> {
383
385
  const senderEntry = reg[roomId]?.[sessionID];
384
386
  if (!senderEntry) throw new RoomError("NOT_JOINED", "session is not a room member");
385
387
  const sender = svc.getRoom(roomId).kind === "direct" ? sessionID : senderEntry.name;
386
- svc.sendMessage(roomId, sender, text, sessionID);
388
+ svc.sendMessage(roomId, sender, text, sessionID, isQuestion === true);
387
389
  return svc.getRoom(roomId);
388
390
  });
389
391
  touchActive(sessionID); // 发送者活跃
@@ -402,6 +404,32 @@ async function handle(req: Request): Promise<Response> {
402
404
  return json(serializeRoom(room), 201);
403
405
  }
404
406
  }
407
+ const questions = p.match(/^\/rooms\/([^/]+)\/questions$/);
408
+ if (req.method === "GET" && questions) {
409
+ const roomId = decodeURIComponent(questions[1]!);
410
+ const exists = await read((svc) => svc.listRooms().some((room) => room.id === roomId));
411
+ if (!exists) return json({ error: "room not found" }, 404);
412
+ return json({ questions: await readQuestions(roomId) });
413
+ }
414
+ const answer = p.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
415
+ if (req.method === "POST" && answer) {
416
+ const roomId = decodeURIComponent(answer[1]!);
417
+ const questionID = decodeURIComponent(answer[2]!);
418
+ const body: unknown = await req.json();
419
+ if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "sessionID and non-empty text (max 2000) are required" }, 400);
420
+ const input = body as Record<string, unknown>;
421
+ if (typeof input.sessionID !== "string" || !input.sessionID || typeof input.text !== "string" || !input.text.trim() || input.text.trim().length > 2000) return json({ error: "sessionID and non-empty text (max 2000) are required" }, 400);
422
+ const result = await answerQuestion(roomId, questionID, input.sessionID, input.text.trim());
423
+ if (result.status === "missing") return json({ error: "room not found" }, 404);
424
+ if (result.status === "question") return json({ error: "question not found" }, 404);
425
+ if (result.status === "member") return json({ error: "session is not a room member" }, 409);
426
+ if (result.status === "answered") return json({ error: "question already answered" }, 409);
427
+ if (result.status !== "ok") return json({ error: "question not found" }, 404);
428
+ touchActive(input.sessionID);
429
+ const room = await read((svc) => svc.getRoom(roomId));
430
+ void wakeMentionedSessions(serveWakeUrl, roomId, room.name, result.answer.text, input.sessionID, result.answer);
431
+ return json({ questionID, answer: result.answer }, 201);
432
+ }
405
433
  const g = p.match(/^\/rooms\/([^/]+)$/);
406
434
  if (g && req.method === "GET") {
407
435
  const room = await read((svc) =>
package/server/chat.html CHANGED
@@ -4,7 +4,7 @@
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
6
  <meta name="color-scheme" content="light dark">
7
- <title data-i18n="documentTitle">Casual Chat · Lightweight Chatroom</title>
7
+ <title data-i18n="documentTitle">OC Chat</title>
8
8
  <link rel="stylesheet" href="/assets/base.css">
9
9
  <link rel="stylesheet" href="/assets/conversation.css">
10
10
  <link rel="stylesheet" href="/assets/responsive.css">
@@ -23,7 +23,7 @@
23
23
  <option value="zh-CN">中文</option>
24
24
  </select>
25
25
  </div>
26
- <p class="wordmark" data-i18n="brand">Casual Chat</p>
26
+ <p class="wordmark" data-i18n="brand">OC Chat</p>
27
27
  <p class="tagline" data-i18n="tagline">A lightweight chat room. Enter a room ID to join, or create a new one.</p>
28
28
 
29
29
  <form id="joinForm" novalidate>
@@ -73,7 +73,7 @@
73
73
  <!-- Shared room workspace. -->
74
74
  <section id="chatView" class="view" hidden>
75
75
  <aside class="room-rail" aria-label="Rooms" data-i18n-aria-label="roomsLabel">
76
- <div class="rail-brand"><span class="brand-mark">C</span><span data-i18n="brand">Casual Chat</span></div>
76
+ <div class="rail-brand"><span class="brand-mark">OC</span><span data-i18n="brand">OC Chat</span></div>
77
77
  <div class="rail-label"><span data-i18n="existingRooms">Rooms</span><span class="rail-tools"><button id="btnNewRoom" class="icon-btn" type="button" aria-label="Create a room" data-i18n-aria-label="newRoom">+</button><button id="btnRefreshRooms" class="icon-btn" type="button" aria-label="Refresh rooms" data-i18n-aria-label="refreshRooms">↻</button></span></div>
78
78
  <form id="railRoomForm" class="rail-composer" hidden>
79
79
  <label class="field"><span class="field-label" data-i18n="newRoomNameLabel">New room name</span><input id="inRoomNameChat" class="input" maxlength="40" data-i18n-placeholder="newRoomNamePlaceholder" placeholder="e.g. Weekend movie night"></label>
@@ -100,6 +100,18 @@
100
100
  <option value="zh-CN">中文</option>
101
101
  </select>
102
102
  </div>
103
+ <div class="anchor questions-anchor">
104
+ <button class="chip questions-trigger" type="button" id="btnQuestions" aria-haspopup="true" aria-expanded="false" aria-controls="questionPanel">
105
+ <span data-i18n="questions">Questions</span><span id="questionBadge" class="question-badge" hidden></span>
106
+ </button>
107
+ <section class="panel question-panel" id="questionPanel" aria-labelledby="questionHeading" hidden>
108
+ <div class="question-panel-head"><h3 id="questionHeading" tabindex="-1" data-i18n="pendingQuestions">Pending questions</h3>
109
+ <button class="question-refresh" type="button" id="btnRefreshQuestions" data-i18n="refreshQuestions">Refresh</button></div>
110
+ <p id="questionStatus" class="hint" role="status" aria-live="polite" data-i18n="questionsLoading">Loading questions…</p>
111
+ <ul id="questionList" class="question-list" aria-label="Pending questions" data-i18n-aria-label="pendingQuestions"></ul>
112
+ <div id="questionReply" class="question-reply" hidden></div>
113
+ </section>
114
+ </div>
103
115
  <div class="anchor">
104
116
  <button class="chip" type="button" id="btnMembers" aria-label="Members" data-i18n-aria-label="members" aria-haspopup="true" aria-expanded="false" data-i18n="members">Members</button>
105
117
  <div class="panel" id="memberPanel" hidden>
@@ -142,6 +154,15 @@
142
154
  </button>
143
155
  </div>
144
156
 
157
+ <aside id="readerPanel" class="reader-panel" aria-labelledby="readerHeading" hidden>
158
+ <div class="reader-panel-head">
159
+ <div><p id="readerCount" class="hint"></p><h2 id="readerHeading" tabindex="-1" data-i18n="readerPanelTitle">Message readers</h2></div>
160
+ <button type="button" id="btnCloseReaders" class="reader-close" data-i18n-aria-label="close" aria-label="Close">×</button>
161
+ </div>
162
+ <blockquote id="readerExcerpt" class="reader-excerpt"></blockquote>
163
+ <ul id="readerList" class="receipt-reader-list" aria-label="Message readers" data-i18n-aria-label="readerPanelTitle"></ul>
164
+ </aside>
165
+
145
166
  <footer class="composer">
146
167
  <p id="sendError" class="send-error" role="alert" hidden></p>
147
168
  <div id="mentionPicker" class="mention-picker" role="listbox" aria-label="Choose a member to mention" data-i18n-aria-label="mentionMembers" hidden></div>
@@ -149,6 +170,7 @@
149
170
  <textarea id="msgInput" class="input" rows="1" maxlength="2000" placeholder="Type a message, Enter to send, Shift+Enter for a new line" data-i18n-placeholder="messagePlaceholder" autocomplete="off" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" disabled></textarea>
150
171
  <button class="btn primary" type="button" id="btnSend" data-i18n="send" disabled>Send</button>
151
172
  </div>
173
+ <label class="question-toggle"><input id="questionToggle" type="checkbox"><span data-i18n="sendAsQuestion">Send as a question</span></label>
152
174
  <p id="draftCount" class="draft-count">0 / 2000</p>
153
175
  </footer>
154
176
  </section>
@@ -1,16 +1,21 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
- import { databasePath, recordMessageReceipts } from "./store";
3
+ import { databasePath, formatNotificationLines, NOTIFY_INSTRUCTION, recordMessageReceipts, timeOf } from "./store";
4
4
  import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "./receiver-state";
5
5
 
6
6
  // shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
7
7
  const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
8
- type Item = { id?: string; text: string };
8
+ type Item = { id?: string; text: string; senderId?: string; createdAt?: number };
9
+ type CappedItem = Item & { senderId: string; createdAt: number };
9
10
  export type ReceiptCandidate = {
10
11
  admissionID: string; sessionID: string; roomID: string; membershipID: string;
11
12
  receiverOwnerID: string; destination: string; messageIDs: string[]; textHash: string; createdAt: number;
12
13
  };
13
14
  const hash = (text: string) => createHash("sha256").update(text).digest("hex");
15
+ function hasCappedMetadata(item: Item): item is CappedItem {
16
+ return typeof item.senderId === "string" && typeof item.createdAt === "number" && Number.isSafeInteger(item.createdAt) &&
17
+ !/[\r\n]/.test(item.senderId) && !/[\r\n]/.test(item.text);
18
+ }
14
19
 
15
20
  export function receiptDestination(center: string): string {
16
21
  if (!center) return path.resolve(databasePath());
@@ -23,13 +28,41 @@ export function prepareReceiptCandidate(input: {
23
28
  admissionID: string; sessionID: string; roomID: string; membershipID?: string;
24
29
  receiverOwnerID?: string; destination: string; items: Item[]; prompt: string; capped: boolean;
25
30
  }): ReceiptCandidate | undefined {
26
- if (input.capped || !input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
31
+ if (!input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
27
32
  !input.sessionID || input.sessionID.length > 128 || !input.roomID || input.roomID.length > 128 ||
28
33
  !input.items.length || input.items.length > 500 || input.items.some((item) => typeof item.id !== "string" || !item.id || item.id.length > 128 || typeof item.text !== "string")) return undefined;
34
+ // shortcut: capped multiline notifications fail closed; use structured rendered-line metadata if partial proofs become necessary.
35
+ let evidenceItems = input.items;
36
+ if (input.capped) {
37
+ const cappedItems = input.items.filter(hasCappedMetadata);
38
+ if (cappedItems.length !== input.items.length) return undefined;
39
+ const instruction = input.prompt.lastIndexOf(`\n${NOTIFY_INSTRUCTION}\n</notification>`);
40
+ if (instruction < 0) return undefined;
41
+ const renderedCounts = new Map<string, number>();
42
+ for (const item of cappedItems) {
43
+ const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
44
+ const key = `${prefix}${item.text}`;
45
+ renderedCounts.set(key, (renderedCounts.get(key) ?? 0) + 1);
46
+ }
47
+ let tail = input.prompt.slice(0, instruction);
48
+ evidenceItems = [];
49
+ for (let index = cappedItems.length - 1; index >= 0; index--) {
50
+ const item = cappedItems[index]!;
51
+ const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
52
+ const line = tail.lastIndexOf(prefix);
53
+ if (line < 0) break;
54
+ const displayedText = tail.slice(line + prefix.length);
55
+ if (displayedText.includes("\n")) break;
56
+ if (displayedText === item.text && renderedCounts.get(`${prefix}${item.text}`) === 1 && !formatNotificationLines([item]).capped) evidenceItems.push(item);
57
+ tail = tail.slice(0, line);
58
+ }
59
+ evidenceItems.reverse();
60
+ }
61
+ if (!evidenceItems.length) return undefined;
29
62
  const candidate: ReceiptCandidate = {
30
63
  admissionID: input.admissionID, sessionID: input.sessionID, roomID: input.roomID,
31
64
  membershipID: input.membershipID, receiverOwnerID: input.receiverOwnerID,
32
- destination: input.destination, messageIDs: input.items.map((item) => item.id!),
65
+ destination: input.destination, messageIDs: evidenceItems.map((item) => item.id!),
33
66
  textHash: hash(input.prompt), createdAt: Date.now(),
34
67
  };
35
68
  const key = hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
@@ -61,25 +94,37 @@ export function observeReceiptContext(sessionID: string, messages: readonly unkn
61
94
  }
62
95
 
63
96
  const receiptFlushes = new Map<string, Promise<void>>();
97
+ // shortcut: cursor resets on process restart; persist it if restart storms delay backlog progress.
98
+ const receiptFlushCursors = new Map<string, string>();
99
+ const RECEIPT_FLUSH_LIMIT = 8;
100
+ const RECEIPT_FLUSH_LEASE_MS = 30_000;
64
101
  export function flushReceiptCandidates(input: {
65
102
  destination: string; receiverOwnerID?: string; center?: string; token?: string;
66
103
  }): Promise<void> {
67
104
  const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
68
105
  const running = receiptFlushes.get(key);
69
106
  if (running) return running;
70
- const task = flushOneReceiptCandidate(input).finally(() => receiptFlushes.delete(key));
107
+ const task = flushOneReceiptCandidate(input, key).finally(() => receiptFlushes.delete(key));
71
108
  receiptFlushes.set(key, task);
72
109
  return task;
73
110
  }
74
111
 
75
- async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }): Promise<void> {
76
- const leaseKey = `receipt-flush:${hash(JSON.stringify([input.destination, input.receiverOwnerID ?? ""]))}`;
112
+ async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }, cursorKey: string): Promise<void> {
113
+ const leaseKey = `receipt-flush:${hash(cursorKey)}`;
77
114
  const holder = randomUUID(), now = Date.now();
78
- if (!acquireDeliveryLease(leaseKey, holder, now, now + 5000)) return;
115
+ if (!acquireDeliveryLease(leaseKey, holder, now, now + RECEIPT_FLUSH_LEASE_MS)) return;
79
116
  try {
80
117
  let candidates: Array<{ id: string; value: ReceiptCandidate }>;
81
- try { candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), 1); }
118
+ let cursor = receiptFlushCursors.get(cursorKey) ?? "";
119
+ try {
120
+ candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT, cursor);
121
+ if (!candidates.length && cursor) {
122
+ cursor = "";
123
+ candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT);
124
+ }
125
+ }
82
126
  catch { return; }
127
+ if (candidates.length) receiptFlushCursors.set(cursorKey, candidates.at(-1)!.id);
83
128
  for (const { id, value } of candidates) {
84
129
  try {
85
130
  if (input.center) {
@@ -97,6 +97,7 @@ export async function centerAction(
97
97
  name?: string;
98
98
  roomId?: string;
99
99
  text?: string;
100
+ isQuestion?: boolean;
100
101
  receiverOwnerID?: string;
101
102
  protocol?: "v1" | "v2";
102
103
  },
@@ -134,10 +135,13 @@ export async function centerAction(
134
135
  return formatRoom(svcOf(room), toRoom(room));
135
136
  }
136
137
  case "join": {
138
+ if (!args.name?.trim()) {
139
+ return "error: name is required to join a room";
140
+ }
137
141
  if (!args.roomId) {
138
142
  return "error: roomId is required";
139
143
  }
140
- const me = identity(args.name?.trim());
144
+ const me = identity(args.name.trim());
141
145
  const room = await request(
142
146
  opts,
143
147
  `/rooms/${encodeURIComponent(args.roomId)}/join`,
@@ -192,7 +196,7 @@ export async function centerAction(
192
196
  opts,
193
197
  `/rooms/${encodeURIComponent(args.roomId)}/messages`,
194
198
  "POST",
195
- { sessionID, text: args.text.trim() },
199
+ { sessionID, text: args.text.trim(), ...(args.isQuestion ? { isQuestion: true } : {}) },
196
200
  );
197
201
  const svc = svcOf(room);
198
202
  return `sent: ${args.text.trim()}\n${formatRoom(svc, toRoom(room))}`;
@@ -121,11 +121,13 @@ export function markReceiptCandidateReady(id: string): boolean {
121
121
  return immediate((db) => db.query("UPDATE receipt_candidates SET ready=1,expires_at=? WHERE candidate_id=? AND ready=0")
122
122
  .run(Number.MAX_SAFE_INTEGER, id).changes === 1);
123
123
  }
124
- export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number): Array<{ id: string; value: T }> {
124
+ export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number, afterID?: string): Array<{ id: string; value: T }> {
125
125
  return immediate((db) => {
126
126
  db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(now);
127
- const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" + (limit ? " LIMIT ?" : "");
128
- const rows = (limit ? db.query(query).all(destination, ownerID ?? "", limit) : db.query(query).all(destination, ownerID ?? "")) as Array<{ candidate_id: string; candidate: string }>;
127
+ const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" +
128
+ (afterID !== undefined ? " AND candidate_id>?" : "") + " ORDER BY candidate_id" + (limit ? " LIMIT ?" : "");
129
+ const args = [destination, ownerID ?? "", ...(afterID !== undefined ? [afterID] : []), ...(limit ? [limit] : [])];
130
+ const rows = db.query(query).all(...args) as Array<{ candidate_id: string; candidate: string }>;
129
131
  return rows.map((row) => ({ id: row.candidate_id, value: JSON.parse(row.candidate) as T }));
130
132
  });
131
133
  }
@@ -13,6 +13,9 @@ export type Message = {
13
13
  senderSessionID?: string;
14
14
  text: string;
15
15
  createdAt: number;
16
+ isQuestion?: boolean;
17
+ answerToMessageID?: string;
18
+ answeredByMessageID?: string;
16
19
  };
17
20
 
18
21
  export type Room = {
@@ -129,6 +132,7 @@ export default class RoomService {
129
132
  senderId: string,
130
133
  text: string,
131
134
  senderSessionID?: string,
135
+ isQuestion = false,
132
136
  ): Message {
133
137
  const room = this.getRoom(roomId);
134
138
  if (!room.participants.has(senderId)) {
@@ -145,6 +149,7 @@ export default class RoomService {
145
149
  ...(senderSessionID ? { senderSessionID } : {}),
146
150
  text: trimmed,
147
151
  createdAt: Math.max(Date.now(), (room.messages.at(-1)?.createdAt ?? 0) + 1),
152
+ ...(isQuestion ? { isQuestion: true } : {}),
148
153
  };
149
154
  room.messages.push(message);
150
155
  this.trimMessages(room);
@@ -27,16 +27,17 @@ async function initialize(file: string): Promise<Database> {
27
27
  try {
28
28
  for (let attempt = 0; ; attempt++) {
29
29
  try {
30
- db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; PRAGMA foreign_keys=ON;");
30
+ db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;");
31
31
  db.exec(`CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
32
32
  CREATE TABLE IF NOT EXISTS rooms(id TEXT PRIMARY KEY,name TEXT NOT NULL,owner_id TEXT NOT NULL,created_at INTEGER NOT NULL,kind TEXT NOT NULL DEFAULT 'group',direct_sessions TEXT,direct_pair TEXT UNIQUE);
33
33
  CREATE TABLE IF NOT EXISTS participants(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,id TEXT NOT NULL,name TEXT NOT NULL,joined_at INTEGER NOT NULL,PRIMARY KEY(room_id,id));
34
- CREATE TABLE IF NOT EXISTS messages(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,sender_id TEXT NOT NULL,sender_session_id TEXT,text TEXT NOT NULL,created_at INTEGER NOT NULL);
34
+ CREATE TABLE IF NOT EXISTS messages(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,sender_id TEXT NOT NULL,sender_session_id TEXT,text TEXT NOT NULL,created_at INTEGER NOT NULL,is_question INTEGER NOT NULL DEFAULT 0,answer_to TEXT,answered_by TEXT);
35
35
  CREATE INDEX IF NOT EXISTS messages_room_seq ON messages(room_id,seq DESC);
36
36
  CREATE INDEX IF NOT EXISTS messages_room_time ON messages(room_id,created_at,seq);
37
37
  CREATE TABLE IF NOT EXISTS registry(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,server_url TEXT NOT NULL,api_prefix TEXT NOT NULL,protocol TEXT,name TEXT NOT NULL,last_read_ts INTEGER,last_queued_ts INTEGER,directory TEXT,host TEXT,receiver_owner_id TEXT,membership_id TEXT,work_state TEXT,last_seen_at INTEGER,PRIMARY KEY(room_id,session_id));`);
38
38
  await ensureRoomColumns(db);
39
39
  await migrate(db, file);
40
+ db.exec("PRAGMA busy_timeout=50;");
40
41
  return db;
41
42
  } catch (error) {
42
43
  if (!isBusy(error) || attempt >= 7) throw error;
@@ -47,7 +48,12 @@ async function initialize(file: string): Promise<Database> {
47
48
  }
48
49
 
49
50
  async function ensureRoomColumns(db: Database): Promise<void> {
50
- await immediate(db, () => {
51
+ await immediate(db, () => {
52
+ const messageColumns = db.query("PRAGMA table_info(messages)").all() as Array<{ name: string }>;
53
+ if (!messageColumns.some((column) => column.name === "is_question")) db.exec("ALTER TABLE messages ADD COLUMN is_question INTEGER NOT NULL DEFAULT 0");
54
+ if (!messageColumns.some((column) => column.name === "answer_to")) db.exec("ALTER TABLE messages ADD COLUMN answer_to TEXT");
55
+ if (!messageColumns.some((column) => column.name === "answered_by")) db.exec("ALTER TABLE messages ADD COLUMN answered_by TEXT");
56
+ db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
51
57
  const columns = db.query("PRAGMA table_info(rooms)").all() as Array<{ name: string }>;
52
58
  if (!columns.some((column) => column.name === "kind")) db.exec("ALTER TABLE rooms ADD COLUMN kind TEXT NOT NULL DEFAULT 'group'");
53
59
  if (!columns.some((column) => column.name === "direct_sessions")) db.exec("ALTER TABLE rooms ADD COLUMN direct_sessions TEXT");
@@ -169,8 +175,8 @@ function insertRoom(db: Database, room: Room): void {
169
175
  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);
170
176
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
171
177
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
172
- const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
173
- for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
178
+ 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(?,?,?,?,?,?,?,?,?)");
179
+ 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);
174
180
  }
175
181
 
176
182
  function replaceRegistry(db: Database, registry: Registry): void {
@@ -187,7 +193,7 @@ function replaceRegistry(db: Database, registry: Registry): void {
187
193
  function persistState(db: Database, rooms: Room[], registry: Registry): void {
188
194
  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");
189
195
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
190
- const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
196
+ 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(?,?,?,?,?,?,?,?,?)");
191
197
  const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
192
198
  const keep = new Set(rooms.map((room) => room.id));
193
199
  const existing = db.query("SELECT id FROM rooms").all() as Array<{ id: string }>;
@@ -197,7 +203,7 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
197
203
  roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null);
198
204
  removeParticipants.run(room.id);
199
205
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
200
- for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
206
+ 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);
201
207
  }
202
208
  replaceRegistry(db, registry);
203
209
  }
@@ -209,10 +215,10 @@ function readState(db: Database): State {
209
215
  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>>) {
210
216
  participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
211
217
  }
212
- const messages = db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 500").all(String(r.id)) as Array<Record<string, string | number | null>>;
218
+ 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>>;
213
219
  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,
214
220
  messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
215
- text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}) })) };
221
+ 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) } : {}) })) };
216
222
  });
217
223
  const registry: Registry = Object.create(null);
218
224
  const rows = db.query("SELECT * FROM registry").all() as Array<Record<string, string | number | null>>;
@@ -249,10 +255,33 @@ export async function readSqliteState(file: string): Promise<State> {
249
255
  return db.transaction(() => readState(db)).deferred();
250
256
  }
251
257
 
258
+ export async function readQuestions(file: string, roomID: string): Promise<Message[]> {
259
+ const db = await open(file);
260
+ 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);
261
+ }
262
+
263
+ export async function answerQuestion(file: string, roomID: string, questionID: string, sessionID: string, text: string): Promise<{ status: "ok"; answer: Message } | { status: "missing" | "member" | "question" | "answered" }> {
264
+ const db = await open(file);
265
+ return immediate(db, () => {
266
+ if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
267
+ const member = db.query("SELECT g.name,r.kind 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 WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
268
+ if (!member) return { status: "member" };
269
+ const question = db.query("SELECT is_question,answered_by FROM messages WHERE room_id=? AND id=?").get(roomID, questionID) as { is_question: number; answered_by: string | null } | null;
270
+ if (!question || !question.is_question) return { status: "question" };
271
+ if (question.answered_by) return { status: "answered" };
272
+ 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;
273
+ const answer: 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: questionID };
274
+ 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);
275
+ 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);
276
+ if (update.changes !== 1) throw new Error("question answer race");
277
+ return { status: "ok", answer };
278
+ });
279
+ }
280
+
252
281
  export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
253
282
  const db = await open(file);
254
283
  const take = Math.min(200, Math.max(1, limit));
255
- const rows = db.query(`SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? AND created_at>? AND
284
+ const rows = 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 created_at>? AND
256
285
  (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
257
286
  ORDER BY created_at ${newest ? "DESC" : "ASC"},seq ${newest ? "DESC" : "ASC"} LIMIT ?`)
258
287
  .all(roomID, afterTs, sessionID ?? null, sessionID ?? null, senderName ?? "", take + 1) as Array<Record<string, string | number | null>>;
@@ -266,7 +295,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
266
295
  return db.transaction(() => {
267
296
  const take = Math.min(200, Math.max(1, limit));
268
297
  const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
269
- const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,r.name AS room_name,r.kind AS room_kind
298
+ const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,m.is_question,m.answer_to,m.answered_by,r.name AS room_name,r.kind AS room_kind
270
299
  FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
271
300
  WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
272
301
  m.created_at > coalesce(?,CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END) AND
@@ -286,7 +315,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
286
315
  export async function readHistoryPage(file: string, roomID: string, beforeSeq?: number, limit = 100, excludeSessionID?: string, excludeName = ""): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
287
316
  const db = await open(file);
288
317
  const take = Math.min(200, Math.max(1, limit));
289
- const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
318
+ const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
290
319
  (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
291
320
  ORDER BY seq DESC LIMIT ?`).all(...(beforeSeq === undefined ? [roomID] : [roomID, beforeSeq]),
292
321
  excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1) as Array<Record<string, string | number | null>>;
@@ -368,5 +397,5 @@ export async function writePresenceState(file: string, reports: PresenceReport[]
368
397
 
369
398
  function rowMessage(row: Record<string, string | number | null>): Message {
370
399
  return { id: String(row.id), roomId: String(row.room_id), senderId: String(row.sender_id), text: String(row.text),
371
- createdAt: Number(row.created_at), ...(row.sender_session_id !== null ? { senderSessionID: String(row.sender_session_id) } : {}) };
400
+ createdAt: Number(row.created_at), ...(row.sender_session_id !== null ? { senderSessionID: String(row.sender_session_id) } : {}), ...(row.is_question ? { isQuestion: true } : {}), ...(row.answer_to ? { answerToMessageID: String(row.answer_to) } : {}), ...(row.answered_by ? { answeredByMessageID: String(row.answered_by) } : {}) };
372
401
  }
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 { readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
7
+ import { answerQuestion as sqliteAnswerQuestion, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestions as sqliteReadQuestions, 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.
@@ -34,6 +34,8 @@ export async function readInboxMessages(sessionID: string, roomID: string | null
34
34
  export async function readHistory(roomID: string, beforeSeq?: number, limit = 100, exclude?: { sessionID: string; name: string }): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
35
35
  return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
36
36
  }
37
+ export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
38
+ export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
37
39
 
38
40
  export async function loadRooms(): Promise<Room[]> {
39
41
  return (await readSqliteState(databasePath())).rooms;
package/src/v2-plugin.ts CHANGED
@@ -120,6 +120,11 @@ function roomSchema() {
120
120
  name: z.string().max(64).optional(),
121
121
  roomId: z.string().optional(),
122
122
  text: z.string().max(2000).optional(),
123
+ isQuestion: z.boolean().optional(),
124
+ }).superRefine((args, ctx) => {
125
+ if (args.action === "join" && !args.name?.trim()) {
126
+ ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
127
+ }
123
128
  });
124
129
  }
125
130