@alexsun-top/opencode-chat-room 0.7.7 → 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 (59) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/dist/cli.js +80 -28
  5. package/package.json +2 -2
  6. package/server/assets/chat/announcements.js +5 -2
  7. package/server/assets/chat/clipboard.js +30 -0
  8. package/server/assets/chat/copy-action.js +48 -0
  9. package/server/assets/chat/diagram-viewer.js +253 -0
  10. package/server/assets/chat/doc-preview.js +150 -12
  11. package/server/assets/chat/events.js +25 -4
  12. package/server/assets/chat/files.js +26 -5
  13. package/server/assets/chat/history-loader.js +3 -1
  14. package/server/assets/chat/index.js +9 -1
  15. package/server/assets/chat/join-requests.js +6 -3
  16. package/server/assets/chat/locales/de.js +2 -2
  17. package/server/assets/chat/locales/es.js +2 -2
  18. package/server/assets/chat/locales/fr.js +2 -2
  19. package/server/assets/chat/locales/it.js +2 -2
  20. package/server/assets/chat/locales/ja.js +2 -2
  21. package/server/assets/chat/locales/ko.js +2 -2
  22. package/server/assets/chat/markdown.js +55 -92
  23. package/server/assets/chat/messages.js +6 -3
  24. package/server/assets/chat/palette.js +32 -15
  25. package/server/assets/chat/pwa.js +2 -0
  26. package/server/assets/chat/questions.js +5 -0
  27. package/server/assets/chat/resource-format.js +74 -0
  28. package/server/assets/chat/rooms.js +3 -0
  29. package/server/assets/chat/side-pane.js +136 -0
  30. package/server/assets/chat/state.js +49 -8
  31. package/server/assets/chat/task-row.js +2 -1
  32. package/server/assets/chat/tasks.js +29 -2
  33. package/server/assets/chat/viewport.js +5 -0
  34. package/server/assets/conversation.css +25 -1
  35. package/server/assets/diagram-viewer.css +141 -0
  36. package/server/assets/doc-preview.css +24 -5
  37. package/server/assets/responsive.css +82 -13
  38. package/server/assets/tasks.css +1 -4
  39. package/server/chat-server.ts +9 -4
  40. package/server/chat.html +23 -2
  41. package/server/resource-routes.ts +3 -1
  42. package/server/sw.js +235 -2
  43. package/skills/chatroom/SKILL.md +1 -1
  44. package/src/agent/chatroom-skill.ts +8 -2
  45. package/src/rooms/resources.ts +2 -2
  46. package/src/runtime/watch.ts +38 -5
  47. package/src/state/sqlite-state.ts +26 -8
  48. package/src/state/store.ts +2 -2
  49. package/src/tui/app.mjs +10 -2
  50. package/src/tui/http.mjs +2 -2
  51. package/src/tui/info-app.mjs +24 -15
  52. package/src/tui/join-app.mjs +3 -3
  53. package/src/tui/main.mjs +1 -1
  54. package/src/tui/markdown.mjs +5 -3
  55. package/src/tui/mentions.mjs +3 -3
  56. package/src/tui/message-app.mjs +14 -11
  57. package/src/tui/palette-app.mjs +10 -7
  58. package/src/tui/reminder-app.mjs +14 -10
  59. package/src/tui/ui-content.mjs +3 -1
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
3
- import { realpathSync } from "node:fs";
3
+ import { existsSync, realpathSync } from "node:fs";
4
4
  import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { spawn } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
@@ -212,6 +212,26 @@ function sameController(value: unknown, record: WatchRecord, status: string): bo
212
212
  body.instanceID === record.instanceID && body.nonce === record.nonce;
213
213
  }
214
214
 
215
+ // Run the same entry script that started this process. A relative ../cli.ts
216
+ // only exists in the source layout; inside dist/cli.js it would point outside
217
+ // the package (and Node cannot run a .ts daemon from node_modules).
218
+ function cliEntryPath(): string {
219
+ // Installed packages run through a bin shim (node_modules/.bin/...), so resolve
220
+ // the symlink before checking the file name; the shim itself is not cli.js.
221
+ const argv = process.argv[1];
222
+ if (argv) {
223
+ let resolved = path.resolve(argv);
224
+ try { resolved = realpathSync(resolved); } catch { /* keep the resolved path */ }
225
+ if (/^cli\.(?:ts|js)$/.test(path.basename(resolved))) return resolved;
226
+ }
227
+ const candidates = [
228
+ fileURLToPath(new URL("../../dist/cli.js", import.meta.url)),
229
+ fileURLToPath(new URL("../../cli.ts", import.meta.url)),
230
+ fileURLToPath(new URL("../cli.js", import.meta.url)),
231
+ ];
232
+ return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;
233
+ }
234
+
215
235
  export async function watchStatus(): Promise<"running" | "stopped" | "unavailable" | "starting"> {
216
236
  const record = await readRecord();
217
237
  if (!record) {
@@ -241,9 +261,9 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
241
261
  }
242
262
  throw new Error("watcher state exists or is starting; no process was signaled");
243
263
  }
244
- const cli = fileURLToPath(new URL("../../cli.ts", import.meta.url));
264
+ const cli = cliEntryPath();
245
265
  let childError: Error | undefined;
246
- const child = spawn(process.execPath, [path.resolve(cli), "watch", "run"], {
266
+ const child = spawn(process.execPath, [cli, "watch", "run"], {
247
267
  detached: true, stdio: "ignore",
248
268
  env: { ...process.env, CHAT_ROOM_WATCH_CONTROL_TOKEN: own.token, CHAT_ROOM_WATCH_START_NONCE: own.nonce, CHAT_ROOM_WATCH_INSTANCE_ID: own.instanceID },
249
269
  });
@@ -251,7 +271,7 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
251
271
  child.unref();
252
272
  const deadline = Date.now() + 20_000;
253
273
  while (Date.now() < deadline) {
254
- if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
274
+ if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
255
275
  const record = await readRecord();
256
276
  if (record?.token === own.token && record.nonce === own.nonce && record.phase === "running" && await control(record)) {
257
277
  return "watcher started";
@@ -263,7 +283,20 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
263
283
  }
264
284
  await new Promise((resolve) => setTimeout(resolve, 100));
265
285
  }
266
- throw new Error("watcher did not become ready; its process was not signaled");
286
+ // Leaving the child alive would keep the pid claim and block every later
287
+ // start, so stop it and release this attempt instead of only throwing.
288
+ child.kill("SIGTERM");
289
+ if (child.exitCode === null) {
290
+ // Give the dying daemon a bounded moment to finish its shutdown sweep so a
291
+ // new start cannot overlap it while the old pid still holds leases.
292
+ await Promise.race([
293
+ new Promise((resolve) => child.once("exit", resolve)),
294
+ new Promise((resolve) => setTimeout(resolve, 1000)),
295
+ ]);
296
+ }
297
+ await removeRecord(own.token, own.nonce);
298
+ releaseWatcherClaim(profile(), own.instanceID);
299
+ throw new Error("watcher did not become ready; its process was stopped");
267
300
  }
268
301
 
269
302
  export async function stopWatcher(): Promise<string> {
@@ -133,10 +133,16 @@ export async function putResource(file: string, resource: StoredResource): Promi
133
133
  return true;
134
134
  });
135
135
  }
136
- 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 }> {
137
137
  const db = await initialize(file);
138
- 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 ?")
139
- .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[];
140
146
  const total = Number((db.query("SELECT COUNT(*) AS count FROM resources WHERE room_id=?").get(roomID) as { count: number } | null)?.count ?? 0);
141
147
  return { items, total };
142
148
  }
@@ -221,6 +227,10 @@ async function ensureRoomColumns(db: Database): Promise<void> {
221
227
  if (!messageColumns.some((column) => column.name === "answered_by")) db.exec("ALTER TABLE messages ADD COLUMN answered_by TEXT");
222
228
  if (!messageColumns.some((column) => column.name === "recalled_at")) db.exec("ALTER TABLE messages ADD COLUMN recalled_at INTEGER");
223
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");
224
234
  db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
225
235
  db.exec("CREATE INDEX IF NOT EXISTS messages_room_recalled ON messages(room_id,recalled_at)");
226
236
  const taskColumns = db.query("PRAGMA table_info(room_tasks)").all() as Array<{ name: string }>;
@@ -545,37 +555,45 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
545
555
  });
546
556
  }
547
557
 
548
- 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" }> {
549
559
  const db = await openStateDatabase(file);
550
560
  return immediate(db, () => {
551
561
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
552
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;
553
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
+ }
554
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;
555
569
  const message: Message = {
556
570
  id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name,
557
571
  senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1),
558
572
  ...(isQuestion ? { isQuestion: true } : {}),
559
573
  };
560
- db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)")
561
- .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);
562
576
  noteMessageInsert(db, roomID);
563
577
  return { status: "ok", message };
564
578
  });
565
579
  }
566
580
 
567
- 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" }> {
568
582
  const db = await openStateDatabase(file);
569
583
  return immediate(db, () => {
570
584
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
571
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;
572
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
+ }
573
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;
574
592
  if (!target || target.recalled_at !== null) return { status: "target" };
575
593
  if (target.is_question) return { status: "question" };
576
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;
577
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 };
578
- 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);
579
597
  noteMessageInsert(db, roomID);
580
598
  return { status: "ok", message };
581
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
@@ -338,11 +338,18 @@ export class ChatApp {
338
338
  return;
339
339
  }
340
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;
341
347
  this.state.draft = "";
342
348
  this.touch();
343
349
  try {
344
- 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 });
345
351
  if (!this.isCurrent(room.id)) return;
352
+ this.pendingSend = null;
346
353
  if (Array.isArray(result?.messages)) this.merge(result.messages);
347
354
  else if (result?.id) this.merge([result]);
348
355
  this.state.highlight = null;
@@ -350,7 +357,8 @@ export class ChatApp {
350
357
  this.setStatus("sent", "success");
351
358
  this.markRead();
352
359
  } catch (error) {
353
- if (!this.state.draft) this.state.draft = raw;
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;
354
362
  this.setStatus(`send failed: ${errorText(error)}`, "error");
355
363
  }
356
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.7";
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
 
@@ -84,10 +84,12 @@ export function prepareMarkdown(text) {
84
84
  return String(text ?? "")
85
85
  .split("\n")
86
86
  .map((line) => {
87
- const marker = line.match(/^([ \t]*)(`{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]*$/);
88
90
  if (fence) {
89
- if (marker && marker[2][0] === fence.char && marker[2].length >= fence.length
90
- && marker[1].length <= fence.indent + 3) fence = null;
91
+ if (closing && closing[2][0] === fence.char && closing[2].length >= fence.length
92
+ && closing[1].length <= fence.indent + 3) fence = null;
91
93
  return line;
92
94
  }
93
95
  if (indented) {
@@ -73,7 +73,7 @@ function codeSegments(source) {
73
73
  while (lineStart < source.length) {
74
74
  const lineEnd = source.indexOf("\n", lineStart);
75
75
  const end = lineEnd < 0 ? source.length : lineEnd;
76
- const line = source.slice(lineStart, end);
76
+ const line = source.slice(lineStart, end).replace(/\r$/, "");
77
77
  const opener = /^([ \t]*)(`{3,}|~{3,})/.exec(line);
78
78
  if (opener) {
79
79
  if (lineStart > proseStart) splitInlineCode(source, proseStart, lineStart, segments);
@@ -84,7 +84,7 @@ function codeSegments(source) {
84
84
  while (scan < source.length) {
85
85
  const nextEnd = source.indexOf("\n", scan);
86
86
  const stop = nextEnd < 0 ? source.length : nextEnd;
87
- const close = /^([ \t]*)(`{3,}|~{3,})[ \t]*$/.exec(source.slice(scan, stop));
87
+ const close = /^([ \t]*)(`{3,}|~{3,})[ \t]*$/.exec(source.slice(scan, stop).replace(/\r$/, ""));
88
88
  if (close && close[2][0] === fence[0] && close[2].length >= fence.length
89
89
  && close[1].length <= indent + 3) {
90
90
  closed = nextEnd < 0 ? source.length : nextEnd + 1;
@@ -106,7 +106,7 @@ function codeSegments(source) {
106
106
  while (scan < source.length) {
107
107
  const nextEnd = source.indexOf("\n", scan);
108
108
  const stop = nextEnd < 0 ? source.length : nextEnd;
109
- const current = source.slice(scan, stop);
109
+ const current = source.slice(scan, stop).replace(/\r$/, "");
110
110
  if (current.trim() && !/^(?: {4,}|\t)/.test(current)) {
111
111
  closed = scan;
112
112
  break;
@@ -15,6 +15,8 @@ export function attachMessageActions(Class) {
15
15
  return null;
16
16
  }
17
17
  palette.mode = "prompt";
18
+ palette.roomId = this.state.current.id;
19
+ palette.roomParticipants = [...(this.state.current.participants || [])];
18
20
  palette.title = title;
19
21
  palette.subtitle = `#${this.state.current.name}`;
20
22
  palette.error = "";
@@ -42,15 +44,16 @@ export function attachMessageActions(Class) {
42
44
 
43
45
  async submitMessagePrompt(prompt, value) {
44
46
  const palette = this.state.palette;
45
- const room = this.state.current;
47
+ const roomId = palette?.roomId || this.state.current?.id;
48
+ const participants = palette?.roomParticipants || this.state.current?.participants;
46
49
  if (!palette || palette.mode !== "prompt") return;
47
- if (!room) {
50
+ if (!roomId) {
48
51
  palette.error = "open a joined room first";
49
52
  this.touch();
50
53
  return;
51
54
  }
52
55
  if (prompt.action === "message-ask") {
53
- const question = canonicalizeMentions(String(value ?? "").trim(), room.participants);
56
+ const question = canonicalizeMentions(String(value ?? "").trim(), participants);
54
57
  if (!question) {
55
58
  palette.error = "question text is required";
56
59
  this.touch();
@@ -60,7 +63,7 @@ export function attachMessageActions(Class) {
60
63
  palette.error = "";
61
64
  this.touch();
62
65
  try {
63
- const result = await this.api.send(room.id, this.sessionID, question, { isQuestion: true });
66
+ const result = await this.api.send(roomId, this.sessionID, question, { isQuestion: true });
64
67
  if (Array.isArray(result?.messages)) mergeMessages(this.state.messages, result.messages);
65
68
  else if (result?.id) mergeMessages(this.state.messages, [result]);
66
69
  this.state.connection = "online";
@@ -109,7 +112,7 @@ export function attachMessageActions(Class) {
109
112
  return;
110
113
  }
111
114
  if (prompt.action === "message-reply-text") {
112
- const text = canonicalizeMentions(String(value ?? "").trim(), room.participants);
115
+ const text = canonicalizeMentions(String(value ?? "").trim(), participants);
113
116
  if (!text) {
114
117
  palette.error = "reply text is required";
115
118
  this.touch();
@@ -119,8 +122,8 @@ export function attachMessageActions(Class) {
119
122
  palette.error = "";
120
123
  this.touch();
121
124
  try {
122
- const result = await this.api.send(room.id, this.sessionID, text, { replyToMessageID: prompt.data.id });
123
- if (!this.isCurrent(room.id)) return;
125
+ const result = await this.api.send(roomId, this.sessionID, text, { replyToMessageID: prompt.data.id });
126
+ if (!this.isCurrent(roomId)) return;
124
127
  if (Array.isArray(result?.messages)) mergeMessages(this.state.messages, result.messages);
125
128
  else if (result?.id) mergeMessages(this.state.messages, [result]);
126
129
  this.state.connection = "online";
@@ -139,22 +142,22 @@ export function attachMessageActions(Class) {
139
142
 
140
143
  async runMessageConfirm(confirm) {
141
144
  const palette = this.state.palette;
142
- const room = this.state.current;
143
- if (!palette || !room) return;
145
+ const roomId = palette?.roomId || this.state.current?.id;
146
+ if (!palette || !roomId) return;
144
147
  const id = confirm.data.id;
145
148
  palette.searching = true;
146
149
  palette.error = "";
147
150
  this.touch();
148
151
  try {
149
152
  if (confirm.action === "message-recall") {
150
- await this.api.recall(room.id, id, this.sessionID);
153
+ await this.api.recall(roomId, id, this.sessionID);
151
154
  const target = this.state.messages.find((message) => message.id === id);
152
155
  if (target) target.recalledAt = Date.now();
153
156
  this.closePalette();
154
157
  this.setStatus(`recalled ${id}`, "success");
155
158
  return;
156
159
  }
157
- const revealed = await this.api.reveal(room.id, id, this.sessionID);
160
+ const revealed = await this.api.reveal(roomId, id, this.sessionID);
158
161
  palette.mode = "detail";
159
162
  palette.title = "Revealed message";
160
163
  palette.confirm = null;
@@ -10,8 +10,10 @@ export function attachPalette(Class) {
10
10
  openPalette({ slash = false } = {}) {
11
11
  this.historyPages.clear();
12
12
  this.state.help = false;
13
+ // Same rule as the web palette: only "/" means commands; empty input
14
+ // waits for a search query instead of showing a command wall.
13
15
  this.state.palette = {
14
- mode: "commands",
16
+ mode: slash ? "commands" : "search",
15
17
  query: slash ? "/" : "",
16
18
  scope: "room",
17
19
  selected: 0,
@@ -88,16 +90,17 @@ export function attachPalette(Class) {
88
90
  this.historyInflight.add(room.id);
89
91
  try {
90
92
  await this.fetchHistoryPage(room.id);
93
+ // A failed page must not consume the room's search budget.
94
+ this.historyPages.set(room.id, (this.historyPages.get(room.id) ?? 0) + 1);
91
95
  } catch (error) {
92
- if (this.state.palette) this.state.palette.error = `history: ${error.message ?? error}`;
96
+ if (this.state.palette === palette) palette.error = `history: ${error.message ?? error}`;
93
97
  } finally {
94
98
  this.historyInflight.delete(room.id);
95
- this.historyPages.set(room.id, (this.historyPages.get(room.id) ?? 0) + 1);
96
99
  }
97
- if (this.state.palette) this.refreshPaletteResults();
100
+ if (this.state.palette === palette) this.refreshPaletteResults();
98
101
  }
99
- if (this.state.palette) {
100
- this.state.palette.searching = this.historyInflight.size > 0;
102
+ if (this.state.palette === palette) {
103
+ palette.searching = this.historyInflight.size > 0;
101
104
  this.refreshPaletteResults();
102
105
  }
103
106
  },
@@ -306,7 +309,7 @@ export function attachPalette(Class) {
306
309
  const query = String(value ?? "");
307
310
  palette.error = "";
308
311
  if (!query.trim()) {
309
- palette.mode = "commands";
312
+ palette.mode = "search";
310
313
  palette.query = "";
311
314
  palette.results = [];
312
315
  palette.selected = 0;
@@ -23,6 +23,10 @@ export function attachReminders(Class) {
23
23
  return palette?.mode === "info" && palette.kind === "reminders" ? palette : null;
24
24
  },
25
25
 
26
+ reminderRoomId(palette) {
27
+ return palette?.roomId || this.state.current?.id;
28
+ },
29
+
26
30
  selectedReminder() {
27
31
  const palette = this.reminderPalette();
28
32
  return palette ? this.paletteItems()[palette.selected] : null;
@@ -57,13 +61,13 @@ export function attachReminders(Class) {
57
61
  async toggleReminder() {
58
62
  const palette = this.reminderPalette();
59
63
  const reminder = this.selectedReminder();
60
- const room = this.state.current;
61
- if (!palette || !reminder || !room) return;
64
+ const roomId = this.reminderRoomId(palette);
65
+ if (!palette || !reminder || !roomId) return;
62
66
  palette.searching = true;
63
67
  palette.error = "";
64
68
  this.touch();
65
69
  try {
66
- await this.api.updateReminder(room.id, reminder.value, this.sessionID, { paused: !reminder.paused });
70
+ await this.api.updateReminder(roomId, reminder.value, this.sessionID, { paused: !reminder.paused });
67
71
  this.setStatus(`${reminder.paused ? "resumed" : "paused"} reminder`, "success");
68
72
  await this.openReminders();
69
73
  } catch (error) {
@@ -93,9 +97,9 @@ export function attachReminders(Class) {
93
97
 
94
98
  async submitReminderPrompt(prompt, value) {
95
99
  const palette = this.state.palette;
96
- const room = this.state.current;
100
+ const roomId = this.reminderRoomId(palette);
97
101
  if (!palette || palette.mode !== "prompt") return;
98
- if (!room) {
102
+ if (!roomId) {
99
103
  palette.error = "open a joined room first";
100
104
  this.touch();
101
105
  return;
@@ -131,7 +135,7 @@ export function attachReminders(Class) {
131
135
  palette.error = "";
132
136
  this.touch();
133
137
  try {
134
- await this.api.createReminder(room.id, this.sessionID, prompt.data.text, schedule);
138
+ await this.api.createReminder(roomId, this.sessionID, prompt.data.text, schedule);
135
139
  this.setStatus("reminder created", "success");
136
140
  await this.openReminders();
137
141
  } catch (error) {
@@ -154,7 +158,7 @@ export function attachReminders(Class) {
154
158
  palette.error = "";
155
159
  this.touch();
156
160
  try {
157
- await this.api.updateReminder(room.id, prompt.data.id, this.sessionID, { text });
161
+ await this.api.updateReminder(roomId, prompt.data.id, this.sessionID, { text });
158
162
  this.setStatus("reminder updated", "success");
159
163
  await this.openReminders();
160
164
  } catch (error) {
@@ -169,12 +173,12 @@ export function attachReminders(Class) {
169
173
 
170
174
  async runReminderConfirm(confirm) {
171
175
  const palette = this.state.palette;
172
- const room = this.state.current;
173
- if (!palette || !room) return;
176
+ const roomId = this.reminderRoomId(palette);
177
+ if (!palette || !roomId) return;
174
178
  palette.searching = true;
175
179
  this.touch();
176
180
  try {
177
- await this.api.deleteReminder(room.id, confirm.data.id, this.sessionID);
181
+ await this.api.deleteReminder(roomId, confirm.data.id, this.sessionID);
178
182
  this.setStatus("reminder deleted", "success");
179
183
  await this.openReminders();
180
184
  } catch (error) {
@@ -372,7 +372,9 @@ export function syncPalette(ui, state) {
372
372
  if (mode === "commands") {
373
373
  options = ui.app.paletteCommands().map((command) => ({ name: command.label, description: "", value: command.id }));
374
374
  } else if (mode === "search") {
375
- options = !palette.results.length
375
+ options = !String(palette.query ?? "").trim()
376
+ ? [{ name: "Type to search messages", description: "", value: "" }]
377
+ : !palette.results.length
376
378
  ? [{ name: palette.searching ? "Searching..." : "No matches", description: "", value: "" }]
377
379
  : palette.results.map((result) => {
378
380
  const info = formatMessage(result.message, null);