@alexsun-top/opencode-chat-room 0.3.3 → 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.
- package/CHANGELOG.md +12 -0
- package/README.md +14 -6
- package/README.zh-CN.md +14 -6
- package/package.json +1 -1
- package/plugin.ts +8 -1
- package/server/assets/base.css +28 -27
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/messages.js +5 -61
- package/server/assets/chat/questions.js +204 -0
- package/server/assets/chat/receipts.js +112 -0
- package/server/assets/chat/state.js +17 -5
- package/server/assets/conversation.css +39 -13
- package/server/assets/responsive.css +17 -3
- package/server/chat-server.ts +33 -5
- package/server/chat.html +25 -3
- package/src/center-client.ts +6 -2
- package/src/room-service.ts +5 -0
- package/src/sqlite-state.ts +42 -13
- package/src/store.ts +3 -1
- package/src/v2-plugin.ts +5 -0
package/src/sqlite-state.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|