@alexsun-top/opencode-chat-room 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/cli.js +815 -192
  5. package/package.json +3 -2
  6. package/plugin.ts +15 -3
  7. package/server/assets/base.css +0 -2
  8. package/server/assets/chat/announcements.js +5 -2
  9. package/server/assets/chat/clipboard.js +30 -0
  10. package/server/assets/chat/copy-action.js +48 -0
  11. package/server/assets/chat/diagram-viewer.js +253 -0
  12. package/server/assets/chat/doc-preview.js +160 -13
  13. package/server/assets/chat/editor.js +10 -7
  14. package/server/assets/chat/events.js +26 -5
  15. package/server/assets/chat/files.js +26 -5
  16. package/server/assets/chat/history-loader.js +3 -1
  17. package/server/assets/chat/index.js +11 -1
  18. package/server/assets/chat/join-requests.js +6 -3
  19. package/server/assets/chat/locales/de.js +20 -2
  20. package/server/assets/chat/locales/es.js +20 -2
  21. package/server/assets/chat/locales/fr.js +20 -2
  22. package/server/assets/chat/locales/it.js +20 -2
  23. package/server/assets/chat/locales/ja.js +20 -2
  24. package/server/assets/chat/locales/ko.js +20 -2
  25. package/server/assets/chat/markdown.js +75 -86
  26. package/server/assets/chat/messages.js +7 -3
  27. package/server/assets/chat/palette.js +40 -18
  28. package/server/assets/chat/pwa.js +2 -0
  29. package/server/assets/chat/questions.js +6 -0
  30. package/server/assets/chat/resource-format.js +74 -0
  31. package/server/assets/chat/rooms.js +9 -1
  32. package/server/assets/chat/shortcuts.js +14 -3
  33. package/server/assets/chat/side-pane.js +136 -0
  34. package/server/assets/chat/state.js +85 -8
  35. package/server/assets/chat/system-messages.js +3 -1
  36. package/server/assets/chat/task-form.js +197 -0
  37. package/server/assets/chat/task-row.js +170 -0
  38. package/server/assets/chat/tasks.js +521 -0
  39. package/server/assets/chat/viewport.js +5 -0
  40. package/server/assets/conversation.css +25 -1
  41. package/server/assets/diagram-viewer.css +141 -0
  42. package/server/assets/doc-preview.css +24 -5
  43. package/server/assets/responsive.css +108 -14
  44. package/server/assets/tasks.css +419 -0
  45. package/server/chat-server.ts +9 -4
  46. package/server/chat.html +120 -21
  47. package/server/member-routes.ts +3 -0
  48. package/server/resource-routes.ts +3 -1
  49. package/server/sw.js +247 -4
  50. package/server/task-routes.ts +53 -0
  51. package/skills/chatroom/SKILL.md +3 -1
  52. package/src/README.md +3 -3
  53. package/src/agent/chatroom-skill.ts +8 -2
  54. package/src/agent/task-tool.ts +155 -0
  55. package/src/center/center-client.ts +44 -0
  56. package/src/rooms/resources.ts +2 -2
  57. package/src/rooms/tasks.ts +246 -0
  58. package/src/runtime/v2-plugin.ts +11 -2
  59. package/src/runtime/watch.ts +38 -5
  60. package/src/state/sqlite-state.ts +93 -8
  61. package/src/state/store.ts +2 -2
  62. package/src/tui/app.mjs +14 -4
  63. package/src/tui/http.mjs +2 -2
  64. package/src/tui/info-app.mjs +24 -15
  65. package/src/tui/join-app.mjs +3 -3
  66. package/src/tui/main.mjs +4 -4
  67. package/src/tui/markdown.mjs +31 -5
  68. package/src/tui/mentions.mjs +218 -0
  69. package/src/tui/message-app.mjs +15 -11
  70. package/src/tui/palette-app.mjs +19 -9
  71. package/src/tui/reminder-app.mjs +14 -10
  72. package/src/tui/ui-content.mjs +12 -3
  73. package/src/tui/ui-mentions.mjs +44 -0
  74. package/src/tui/ui-suggest-view.mjs +63 -0
  75. package/src/tui/ui-suggest.mjs +197 -0
  76. package/src/tui/ui-theme.mjs +2 -1
  77. package/src/tui/ui-view.mjs +2 -0
  78. package/src/tui/ui.mjs +17 -9
@@ -86,6 +86,8 @@ async function initialize(file: string): Promise<Database> {
86
86
  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));`);
87
87
  db.exec("CREATE TABLE IF NOT EXISTS announcements(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,content TEXT NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(room_id,name))");
88
88
  db.exec("CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,mime_type TEXT NOT NULL,size INTEGER NOT NULL,created_at INTEGER NOT NULL,uploader_session_id TEXT,uploader_name TEXT)");
89
+ db.exec("CREATE TABLE IF NOT EXISTS room_tasks(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,title TEXT NOT NULL,description TEXT NOT NULL DEFAULT '',assignee TEXT NOT NULL DEFAULT '',status TEXT NOT NULL CHECK(status IN ('todo','doing','done')),creator_name TEXT NOT NULL,creator_session_id TEXT NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,due_date TEXT NOT NULL DEFAULT '',participants TEXT NOT NULL DEFAULT '[]',conclusion TEXT NOT NULL DEFAULT '',steps TEXT NOT NULL DEFAULT '[]')");
90
+ db.exec("CREATE INDEX IF NOT EXISTS room_tasks_room_status_created ON room_tasks(room_id,status,created_at,id)");
89
91
  await ensureRoomColumns(db);
90
92
  await migrate(db, file);
91
93
  db.exec("PRAGMA busy_timeout=50;");
@@ -131,10 +133,16 @@ export async function putResource(file: string, resource: StoredResource): Promi
131
133
  return true;
132
134
  });
133
135
  }
134
- export async function listResources(file: string, roomID: string, limit = 500, offset = 0): Promise<{ items: StoredResource[]; total: number }> {
136
+ export async function listResources(file: string, roomID: string, limit = 500, offset = 0, beforeID?: string): Promise<{ items: StoredResource[]; total: number }> {
135
137
  const db = await initialize(file);
136
- const items = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?")
137
- .all(roomID, limit, offset) as StoredResource[];
138
+ const cursor = beforeID
139
+ ? db.query("SELECT created_at AS createdAt,id FROM resources WHERE room_id=? AND id=?").get(roomID, beforeID) as { createdAt: number; id: string } | null
140
+ : null;
141
+ const items = cursor
142
+ ? db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? AND (created_at<? OR (created_at=? AND id<?)) ORDER BY created_at DESC, id DESC LIMIT ?")
143
+ .all(roomID, cursor.createdAt, cursor.createdAt, cursor.id, limit) as StoredResource[]
144
+ : db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?")
145
+ .all(roomID, limit, offset) as StoredResource[];
138
146
  const total = Number((db.query("SELECT COUNT(*) AS count FROM resources WHERE room_id=?").get(roomID) as { count: number } | null)?.count ?? 0);
139
147
  return { items, total };
140
148
  }
@@ -151,6 +159,66 @@ export async function removeResource(file: string, roomID: string, id: string):
151
159
  const db = await openStateDatabase(file);
152
160
  return immediate(db, () => db.query("DELETE FROM resources WHERE room_id=? AND id=?").run(roomID, id).changes > 0);
153
161
  }
162
+
163
+ // --- Room tasks (group rooms only; HTTP permissions live in rooms/tasks.ts) ---
164
+ export const ROOM_TASK_STATUSES = ["todo", "doing", "done"] as const;
165
+ export type RoomTaskStatus = (typeof ROOM_TASK_STATUSES)[number];
166
+ export type RoomTaskStep = { text: string; done: boolean };
167
+ export type RoomTask = {
168
+ id: string; roomId: string; title: string; description: string; assignee: string;
169
+ status: RoomTaskStatus; creatorName: string; creatorSessionID: string;
170
+ createdAt: number; updatedAt: number; dueDate: string; participants: string[];
171
+ conclusion: string; steps: RoomTaskStep[];
172
+ };
173
+ type RoomTaskRow = Omit<RoomTask, "status" | "participants" | "steps"> & { status: string; participants: string; steps: string };
174
+ const ROOM_TASK_COLUMNS = "id,room_id AS roomId,title,description,assignee,status,creator_name AS creatorName,creator_session_id AS creatorSessionID,created_at AS createdAt,updated_at AS updatedAt,due_date AS dueDate,participants,conclusion,steps";
175
+ const jsonArray = <T>(value: string): T[] => {
176
+ try { const parsed = JSON.parse(value) as unknown; return Array.isArray(parsed) ? parsed as T[] : []; }
177
+ catch { return []; }
178
+ };
179
+ const roomTask = (row: RoomTaskRow): RoomTask => ({
180
+ ...row, status: row.status as RoomTaskStatus,
181
+ participants: jsonArray<string>(row.participants), steps: jsonArray<RoomTaskStep>(row.steps),
182
+ });
183
+
184
+ export function listRoomTasks(db: Database, roomID: string): RoomTask[] {
185
+ return (db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? ORDER BY created_at,id`).all(roomID) as RoomTaskRow[]).map(roomTask);
186
+ }
187
+
188
+ export function readRoomTask(db: Database, roomID: string, id: string): RoomTask | undefined {
189
+ const row = db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? AND id=?`).get(roomID, id) as RoomTaskRow | null;
190
+ return row ? roomTask(row) : undefined;
191
+ }
192
+
193
+ export function insertRoomTask(db: Database, task: RoomTask): void {
194
+ db.query("INSERT INTO room_tasks(id,room_id,title,description,assignee,status,creator_name,creator_session_id,created_at,updated_at,due_date,participants,conclusion,steps) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
195
+ .run(task.id, task.roomId, task.title, task.description, task.assignee, task.status, task.creatorName, task.creatorSessionID,
196
+ task.createdAt, task.updatedAt, task.dueDate, JSON.stringify(task.participants), task.conclusion, JSON.stringify(task.steps));
197
+ }
198
+
199
+ export type RoomTaskPatch = Partial<Pick<RoomTask, "title" | "description" | "assignee" | "status" | "dueDate" | "participants" | "conclusion" | "steps">>;
200
+
201
+ export function patchRoomTask(db: Database, roomID: string, id: string, patch: RoomTaskPatch, updatedAt: number): RoomTask | undefined {
202
+ const sets: string[] = [], values: string[] = [];
203
+ for (const [column, value] of [["title", patch.title], ["description", patch.description], ["assignee", patch.assignee], ["status", patch.status], ["due_date", patch.dueDate], ["conclusion", patch.conclusion]] as const) {
204
+ if (value !== undefined) { sets.push(`${column}=?`); values.push(value); }
205
+ }
206
+ if (patch.participants !== undefined) { sets.push("participants=?"); values.push(JSON.stringify(patch.participants)); }
207
+ if (patch.steps !== undefined) { sets.push("steps=?"); values.push(JSON.stringify(patch.steps)); }
208
+ db.query(`UPDATE room_tasks SET ${sets.map((set) => `${set},`).join("")}updated_at=? WHERE room_id=? AND id=?`)
209
+ .run(...values, updatedAt, roomID, id);
210
+ return readRoomTask(db, roomID, id);
211
+ }
212
+
213
+ export function deleteRoomTask(db: Database, roomID: string, id: string): boolean {
214
+ return db.query("DELETE FROM room_tasks WHERE room_id=? AND id=?").run(roomID, id).changes > 0;
215
+ }
216
+
217
+ export function deleteCompletedRoomTasks(db: Database, roomID: string, creatorSessionID?: string): number {
218
+ return creatorSessionID === undefined
219
+ ? db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done'").run(roomID).changes
220
+ : db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done' AND creator_session_id=?").run(roomID, creatorSessionID).changes;
221
+ }
154
222
  async function ensureRoomColumns(db: Database): Promise<void> {
155
223
  await immediate(db, () => {
156
224
  const messageColumns = db.query("PRAGMA table_info(messages)").all() as Array<{ name: string }>;
@@ -159,8 +227,17 @@ async function ensureRoomColumns(db: Database): Promise<void> {
159
227
  if (!messageColumns.some((column) => column.name === "answered_by")) db.exec("ALTER TABLE messages ADD COLUMN answered_by TEXT");
160
228
  if (!messageColumns.some((column) => column.name === "recalled_at")) db.exec("ALTER TABLE messages ADD COLUMN recalled_at INTEGER");
161
229
  if (!messageColumns.some((column) => column.name === "recalled_by")) db.exec("ALTER TABLE messages ADD COLUMN recalled_by TEXT");
230
+ if (!messageColumns.some((column) => column.name === "client_msg_id")) db.exec("ALTER TABLE messages ADD COLUMN client_msg_id TEXT");
231
+ // A retry after a lost response must return the first insert, not add a twin.
232
+ db.exec("DROP INDEX IF EXISTS messages_client_id");
233
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS messages_client_id ON messages(room_id,sender_session_id,client_msg_id) WHERE client_msg_id IS NOT NULL");
162
234
  db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
163
235
  db.exec("CREATE INDEX IF NOT EXISTS messages_room_recalled ON messages(room_id,recalled_at)");
236
+ const taskColumns = db.query("PRAGMA table_info(room_tasks)").all() as Array<{ name: string }>;
237
+ if (!taskColumns.some((column) => column.name === "due_date")) db.exec("ALTER TABLE room_tasks ADD COLUMN due_date TEXT NOT NULL DEFAULT ''");
238
+ if (!taskColumns.some((column) => column.name === "participants")) db.exec("ALTER TABLE room_tasks ADD COLUMN participants TEXT NOT NULL DEFAULT '[]'");
239
+ if (!taskColumns.some((column) => column.name === "conclusion")) db.exec("ALTER TABLE room_tasks ADD COLUMN conclusion TEXT NOT NULL DEFAULT ''");
240
+ if (!taskColumns.some((column) => column.name === "steps")) db.exec("ALTER TABLE room_tasks ADD COLUMN steps TEXT NOT NULL DEFAULT '[]'");
164
241
  db.exec("CREATE TABLE IF NOT EXISTS room_recall_versions(room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,version INTEGER NOT NULL)");
165
242
  db.exec(`CREATE TABLE IF NOT EXISTS room_join_requests(
166
243
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
@@ -478,37 +555,45 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
478
555
  });
479
556
  }
480
557
 
481
- export async function appendRoomMessage(file: string, roomID: string, sessionID: string, text: string, isQuestion: boolean): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" }> {
558
+ export async function appendRoomMessage(file: string, roomID: string, sessionID: string, text: string, isQuestion: boolean, clientMessageID?: string): Promise<{ status: "ok"; message: Message; duplicate?: true } | { status: "missing" | "member" }> {
482
559
  const db = await openStateDatabase(file);
483
560
  return immediate(db, () => {
484
561
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
485
562
  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;
486
563
  if (!member) return { status: "member" };
564
+ if (clientMessageID) {
565
+ const existing = 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 client_msg_id=? AND sender_session_id=?").get(roomID, clientMessageID, sessionID);
566
+ if (existing) return { status: "ok", message: rowMessage(existing as Record<string, string | number | null>), duplicate: true };
567
+ }
487
568
  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;
488
569
  const message: Message = {
489
570
  id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name,
490
571
  senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1),
491
572
  ...(isQuestion ? { isQuestion: true } : {}),
492
573
  };
493
- db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)")
494
- .run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0);
574
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,client_msg_id) VALUES(?,?,?,?,?,?,?,?)")
575
+ .run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0, clientMessageID ?? null);
495
576
  noteMessageInsert(db, roomID);
496
577
  return { status: "ok", message };
497
578
  });
498
579
  }
499
580
 
500
- export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" | "target" | "question" }> {
581
+ export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string, clientMessageID?: string): Promise<{ status: "ok"; message: Message; duplicate?: true } | { status: "missing" | "member" | "target" | "question" }> {
501
582
  const db = await openStateDatabase(file);
502
583
  return immediate(db, () => {
503
584
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
504
585
  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;
505
586
  if (!member) return { status: "member" };
587
+ if (clientMessageID) {
588
+ const existing = 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 client_msg_id=? AND sender_session_id=?").get(roomID, clientMessageID, sessionID);
589
+ if (existing) return { status: "ok", message: rowMessage(existing as Record<string, string | number | null>), duplicate: true };
590
+ }
506
591
  const target = db.query("SELECT is_question,recalled_at FROM messages WHERE room_id=? AND id=?").get(roomID, targetID) as { is_question: number; recalled_at: number | null } | null;
507
592
  if (!target || target.recalled_at !== null) return { status: "target" };
508
593
  if (target.is_question) return { status: "question" };
509
594
  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;
510
595
  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 };
511
- 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);
596
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,client_msg_id) VALUES(?,?,?,?,?,?,0,?,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, targetID, clientMessageID ?? null);
512
597
  noteMessageInsert(db, roomID);
513
598
  return { status: "ok", message };
514
599
  });
@@ -41,8 +41,8 @@ export async function countOpenQuestions(roomID: string): Promise<number> { retu
41
41
  export function acknowledgeRead(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeRead(databasePath(), roomID, sessionID, ts); }
42
42
  export function acknowledgeQueued(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeQueued(databasePath(), roomID, sessionID, ts); }
43
43
  export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
44
- export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text); }
45
- export function appendRoomMessage(roomID: string, sessionID: string, text: string, isQuestion: boolean) { return sqliteAppendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion); }
44
+ export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string, clientMessageID?: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text, clientMessageID); }
45
+ export function appendRoomMessage(roomID: string, sessionID: string, text: string, isQuestion: boolean, clientMessageID?: string) { return sqliteAppendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion, clientMessageID); }
46
46
  export async function readQuestionExcerpt(roomID: string, questionID: string) { return sqliteQuestionExcerpt(databasePath(), roomID, questionID); }
47
47
  export function readJoinRequest(roomID: string, sessionID: string): Promise<JoinRequest | undefined> { return sqliteReadJoinRequest(databasePath(), roomID, sessionID); }
48
48
  export function listJoinRequests(roomID: string, agentOnly = false): Promise<JoinRequest[]> { return sqliteListJoinRequests(databasePath(), roomID, agentOnly); }
package/src/tui/app.mjs CHANGED
@@ -7,6 +7,7 @@ import { attachReminders } from "./reminder-app.mjs";
7
7
  import { attachRoomSettings } from "./room-settings-app.mjs";
8
8
  import { attachMessageActions } from "./message-app.mjs";
9
9
  import { attachJoinRequests } from "./join-app.mjs";
10
+ import { canonicalizeMentions } from "./mentions.mjs";
10
11
  import { mergeMessages, messageStamp, oldestSeq } from "./messages.mjs";
11
12
 
12
13
  const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];
@@ -329,18 +330,26 @@ export class ChatApp {
329
330
  }
330
331
 
331
332
  async send() {
332
- const text = String(this.state.draft ?? "").trim();
333
- if (!text) return;
333
+ const raw = String(this.state.draft ?? "").trim();
334
+ if (!raw) return;
334
335
  const room = this.state.current;
335
336
  if (!room || !this.state.joined) {
336
337
  this.setStatus("join a room before sending", "error");
337
338
  return;
338
339
  }
340
+ const text = canonicalizeMentions(raw, room.participants);
341
+ // Reuse the attempt's id when the same failed text is sent again, so a lost
342
+ // response cannot produce two messages.
343
+ const attempt = this.pendingSend && this.pendingSend.text === raw
344
+ ? this.pendingSend
345
+ : { text: raw, clientMessageID: globalThis.crypto.randomUUID() };
346
+ this.pendingSend = attempt;
339
347
  this.state.draft = "";
340
348
  this.touch();
341
349
  try {
342
- const result = await this.api.send(room.id, this.sessionID, text);
350
+ const result = await this.api.send(room.id, this.sessionID, text, { clientMessageID: attempt.clientMessageID });
343
351
  if (!this.isCurrent(room.id)) return;
352
+ this.pendingSend = null;
344
353
  if (Array.isArray(result?.messages)) this.merge(result.messages);
345
354
  else if (result?.id) this.merge([result]);
346
355
  this.state.highlight = null;
@@ -348,7 +357,8 @@ export class ChatApp {
348
357
  this.setStatus("sent", "success");
349
358
  this.markRead();
350
359
  } catch (error) {
351
- if (!this.state.draft) this.state.draft = text;
360
+ // Keep text typed while the request was in flight; dropping it loses work.
361
+ this.state.draft = this.state.draft ? `${raw}\n${this.state.draft}` : raw;
352
362
  this.setStatus(`send failed: ${errorText(error)}`, "error");
353
363
  }
354
364
  }
package/src/tui/http.mjs CHANGED
@@ -87,10 +87,10 @@ export function createApi({ url, token, requestTimeoutMs = 10000 }) {
87
87
  async leave(roomId, sessionID) {
88
88
  await call(`${room(roomId)}/leave`, { method: "POST", body: { sessionID } });
89
89
  },
90
- async send(roomId, sessionID, text, { replyToMessageID, isQuestion } = {}) {
90
+ async send(roomId, sessionID, text, { replyToMessageID, isQuestion, clientMessageID } = {}) {
91
91
  return (await call(`${room(roomId)}/messages`, {
92
92
  method: "POST",
93
- body: { sessionID, text, ...(replyToMessageID ? { replyToMessageID } : {}), ...(isQuestion ? { isQuestion: true } : {}) },
93
+ body: { sessionID, text, ...(replyToMessageID ? { replyToMessageID } : {}), ...(isQuestion ? { isQuestion: true } : {}), ...(clientMessageID ? { clientMessageID } : {}) },
94
94
  })).data;
95
95
  },
96
96
  async poll(roomId, sessionID, afterTs, { signal, timeoutMs = 20000 } = {}) {
@@ -45,6 +45,18 @@ export function attachInfo(Class) {
45
45
  return null;
46
46
  },
47
47
 
48
+ // A palette acts on the room it was opened for, even if the rail has since
49
+ // switched rooms; otherwise an announcement prompt could overwrite the new
50
+ // room's same-named announcement.
51
+ paletteRoomId(palette) {
52
+ const roomId = palette.roomId || this.state.current?.id;
53
+ if (!roomId) {
54
+ palette.error = "open a joined room first";
55
+ this.touch();
56
+ }
57
+ return roomId;
58
+ },
59
+
48
60
  async openInfo(kind, title, hint, load) {
49
61
  const room = this.currentInfoRoom();
50
62
  if (!room) return;
@@ -172,13 +184,14 @@ export function attachInfo(Class) {
172
184
 
173
185
  async runFileDeleteConfirm(confirm) {
174
186
  const palette = this.state.palette;
175
- const room = this.state.current;
176
- if (!palette || !room) return;
187
+ if (!palette) return;
188
+ const roomId = this.paletteRoomId(palette);
189
+ if (!roomId) return;
177
190
  palette.searching = true;
178
191
  palette.error = "";
179
192
  this.touch();
180
193
  try {
181
- await this.api.deleteResource(room.id, confirm.data.id, this.sessionID);
194
+ await this.api.deleteResource(roomId, confirm.data.id, this.sessionID);
182
195
  this.setStatus(`deleted ${confirm.data.name}`, "success");
183
196
  await this.openFiles();
184
197
  } catch (error) {
@@ -292,13 +305,13 @@ export function attachInfo(Class) {
292
305
  },
293
306
 
294
307
  async downloadFile(item) {
295
- const room = this.state.current;
296
- if (!room || !item?.resource) return;
297
308
  const palette = this.state.palette;
309
+ const roomId = palette ? this.paletteRoomId(palette) : this.state.current?.id;
310
+ if (!roomId || !item?.resource) return;
298
311
  if (palette) palette.searching = true;
299
312
  this.touch();
300
313
  try {
301
- const payload = await this.api.resourceContent(room.id, item.resource.id);
314
+ const payload = await this.api.resourceContent(roomId, item.resource.id);
302
315
  const [{ mkdir, writeFile, access }, path] = await Promise.all([
303
316
  import("node:fs/promises"),
304
317
  import("node:path"),
@@ -341,12 +354,8 @@ export function attachInfo(Class) {
341
354
  await this.submitMessagePrompt(prompt, value);
342
355
  return;
343
356
  }
344
- const room = this.state.current;
345
- if (!room) {
346
- palette.error = "open a joined room first";
347
- this.touch();
348
- return;
349
- }
357
+ const roomId = this.paletteRoomId(palette);
358
+ if (!roomId) return;
350
359
  if (prompt.action === "announcement-name") {
351
360
  const name = String(value ?? "").trim();
352
361
  if (!name) {
@@ -365,7 +374,7 @@ export function attachInfo(Class) {
365
374
  palette.searching = true;
366
375
  this.touch();
367
376
  try {
368
- await this.api.saveAnnouncement(room.id, name, String(value ?? ""), this.sessionID);
377
+ await this.api.saveAnnouncement(roomId, name, String(value ?? ""), this.sessionID);
369
378
  this.setStatus(`saved announcement "${name}"`, "success");
370
379
  await this.openAnnouncements();
371
380
  } catch (error) {
@@ -387,7 +396,7 @@ export function attachInfo(Class) {
387
396
  palette.searching = true;
388
397
  this.touch();
389
398
  try {
390
- await this.api.answerQuestion(room.id, prompt.data?.id, this.sessionID, answer);
399
+ await this.api.answerQuestion(roomId, prompt.data?.id, this.sessionID, answer);
391
400
  this.setStatus("answer posted", "success");
392
401
  await this.openQuestions();
393
402
  } catch (error) {
@@ -419,7 +428,7 @@ export function attachInfo(Class) {
419
428
  return;
420
429
  }
421
430
  const bytes = new Uint8Array(await fs.readFile(file));
422
- await this.api.uploadResource(room.id, this.sessionID, path.basename(file), bytes);
431
+ await this.api.uploadResource(roomId, this.sessionID, path.basename(file), bytes);
423
432
  this.setStatus(`uploaded ${path.basename(file)}`, "success");
424
433
  await this.openFiles();
425
434
  } catch (error) {
@@ -45,14 +45,14 @@ export function attachJoinRequests(Class) {
45
45
 
46
46
  async runJoinConfirm(confirm) {
47
47
  const palette = this.state.palette;
48
- const room = this.state.current;
49
- if (!palette || !room) return;
48
+ const roomId = palette?.roomId || this.state.current?.id;
49
+ if (!palette || !roomId) return;
50
50
  const decision = confirm.action === "join-approve" ? "approve" : "deny";
51
51
  palette.searching = true;
52
52
  palette.error = "";
53
53
  this.touch();
54
54
  try {
55
- await this.api.decideJoin(room.id, confirm.data.sessionID, this.sessionID, decision);
55
+ await this.api.decideJoin(roomId, confirm.data.sessionID, this.sessionID, decision);
56
56
  this.setStatus(`${decision === "approve" ? "approved" : "denied"} ${confirm.data.name}`, "success");
57
57
  await this.openJoinRequests();
58
58
  } catch (error) {
package/src/tui/main.mjs CHANGED
@@ -5,7 +5,7 @@ import path from "node:path";
5
5
  import { createApp } from "./app.mjs";
6
6
 
7
7
  const NAME = "opencode-chat-room cli";
8
- const FALLBACK_VERSION = "0.7.6";
8
+ const FALLBACK_VERSION = "0.7.8";
9
9
 
10
10
  export const HELP = `opencode-chat-room cli - terminal client for a chat-room server
11
11
 
@@ -25,9 +25,9 @@ A token is never accepted on the command line. See the README for fields.
25
25
  Keys: arrows select rooms · Enter opens · Tab focuses the composer ·
26
26
  PageUp/PageDown scroll · Alt+Home/End jumps · Alt+Space or Ctrl+P opens the
27
27
  palette · Ctrl+C quits.
28
- Type / in an empty composer for commands: members, join requests, announcements,
29
- questions, files, reminders, room settings, recall/reveal/reply/ask,
30
- delete room and quit.
28
+ Type / at the start of the composer for inline commands; @ mentions members.
29
+ Commands include: members, join requests, announcements, questions, files,
30
+ reminders, room settings, recall/reveal/reply/ask, delete room and quit.
31
31
  This command needs an interactive terminal.
32
32
  `;
33
33
 
@@ -34,6 +34,21 @@ export function formatAttachments(text) {
34
34
  return `${clean} · Attachments`;
35
35
  }
36
36
 
37
+ function closingBackticks(source, from, end, length) {
38
+ let i = from;
39
+ while (i < end) {
40
+ if (source[i] !== "`") {
41
+ i += 1;
42
+ continue;
43
+ }
44
+ let run = 0;
45
+ while (i + run < end && source[i + run] === "`") run += 1;
46
+ if (run === length) return i;
47
+ i += run;
48
+ }
49
+ return -1;
50
+ }
51
+
37
52
  function inlineMentions(line) {
38
53
  let out = "";
39
54
  let index = 0;
@@ -41,8 +56,7 @@ function inlineMentions(line) {
41
56
  if (line[index] === "`") {
42
57
  let run = 0;
43
58
  while (line[index + run] === "`") run += 1;
44
- const fence = "`".repeat(run);
45
- const close = line.indexOf(fence, index + run);
59
+ const close = closingBackticks(line, index + run, line.length, run);
46
60
  if (close === -1) {
47
61
  out += line.slice(index);
48
62
  break;
@@ -66,16 +80,28 @@ function inlineMentions(line) {
66
80
  /** Rewrite <at>@name</at> in prose, leaving fenced and inline code untouched. */
67
81
  export function prepareMarkdown(text) {
68
82
  let fence = null;
83
+ let indented = false;
69
84
  return String(text ?? "")
70
85
  .split("\n")
71
86
  .map((line) => {
72
- const marker = line.match(/^\s*(`{3,}|~{3,})/);
87
+ const clean = line.replace(/\r$/, "");
88
+ const marker = clean.match(/^([ \t]*)(`{3,}|~{3,})/);
89
+ const closing = clean.match(/^([ \t]*)(`{3,}|~{3,})[ \t]*$/);
73
90
  if (fence) {
74
- if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length) fence = null;
91
+ if (closing && closing[2][0] === fence.char && closing[2].length >= fence.length
92
+ && closing[1].length <= fence.indent + 3) fence = null;
75
93
  return line;
76
94
  }
95
+ if (indented) {
96
+ if (!line.trim() || /^(?: {4,}|\t)/.test(line)) return line;
97
+ indented = false;
98
+ }
77
99
  if (marker) {
78
- fence = marker[1];
100
+ fence = { char: marker[2][0], length: marker[2].length, indent: marker[1].length };
101
+ return line;
102
+ }
103
+ if (/^(?: {4,}|\t)/.test(line)) {
104
+ indented = true;
79
105
  return line;
80
106
  }
81
107
  return inlineMentions(line);