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

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 (54) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/cli.js +735 -164
  5. package/package.json +2 -1
  6. package/plugin.ts +15 -3
  7. package/server/assets/base.css +0 -2
  8. package/server/assets/chat/doc-preview.js +11 -2
  9. package/server/assets/chat/editor.js +10 -7
  10. package/server/assets/chat/events.js +1 -1
  11. package/server/assets/chat/index.js +2 -0
  12. package/server/assets/chat/locales/de.js +18 -0
  13. package/server/assets/chat/locales/es.js +18 -0
  14. package/server/assets/chat/locales/fr.js +18 -0
  15. package/server/assets/chat/locales/it.js +18 -0
  16. package/server/assets/chat/locales/ja.js +18 -0
  17. package/server/assets/chat/locales/ko.js +18 -0
  18. package/server/assets/chat/markdown.js +27 -1
  19. package/server/assets/chat/messages.js +1 -0
  20. package/server/assets/chat/palette.js +9 -4
  21. package/server/assets/chat/questions.js +1 -0
  22. package/server/assets/chat/rooms.js +6 -1
  23. package/server/assets/chat/shortcuts.js +14 -3
  24. package/server/assets/chat/state.js +36 -0
  25. package/server/assets/chat/system-messages.js +3 -1
  26. package/server/assets/chat/task-form.js +197 -0
  27. package/server/assets/chat/task-row.js +169 -0
  28. package/server/assets/chat/tasks.js +494 -0
  29. package/server/assets/responsive.css +26 -1
  30. package/server/assets/tasks.css +422 -0
  31. package/server/chat.html +97 -19
  32. package/server/member-routes.ts +3 -0
  33. package/server/sw.js +12 -2
  34. package/server/task-routes.ts +53 -0
  35. package/skills/chatroom/SKILL.md +3 -1
  36. package/src/README.md +3 -3
  37. package/src/agent/task-tool.ts +155 -0
  38. package/src/center/center-client.ts +44 -0
  39. package/src/rooms/tasks.ts +246 -0
  40. package/src/runtime/v2-plugin.ts +11 -2
  41. package/src/state/sqlite-state.ts +67 -0
  42. package/src/tui/app.mjs +5 -3
  43. package/src/tui/main.mjs +4 -4
  44. package/src/tui/markdown.mjs +29 -5
  45. package/src/tui/mentions.mjs +218 -0
  46. package/src/tui/message-app.mjs +3 -2
  47. package/src/tui/palette-app.mjs +9 -2
  48. package/src/tui/ui-content.mjs +9 -2
  49. package/src/tui/ui-mentions.mjs +44 -0
  50. package/src/tui/ui-suggest-view.mjs +63 -0
  51. package/src/tui/ui-suggest.mjs +197 -0
  52. package/src/tui/ui-theme.mjs +2 -1
  53. package/src/tui/ui-view.mjs +2 -0
  54. 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;");
@@ -151,6 +153,66 @@ export async function removeResource(file: string, roomID: string, id: string):
151
153
  const db = await openStateDatabase(file);
152
154
  return immediate(db, () => db.query("DELETE FROM resources WHERE room_id=? AND id=?").run(roomID, id).changes > 0);
153
155
  }
156
+
157
+ // --- Room tasks (group rooms only; HTTP permissions live in rooms/tasks.ts) ---
158
+ export const ROOM_TASK_STATUSES = ["todo", "doing", "done"] as const;
159
+ export type RoomTaskStatus = (typeof ROOM_TASK_STATUSES)[number];
160
+ export type RoomTaskStep = { text: string; done: boolean };
161
+ export type RoomTask = {
162
+ id: string; roomId: string; title: string; description: string; assignee: string;
163
+ status: RoomTaskStatus; creatorName: string; creatorSessionID: string;
164
+ createdAt: number; updatedAt: number; dueDate: string; participants: string[];
165
+ conclusion: string; steps: RoomTaskStep[];
166
+ };
167
+ type RoomTaskRow = Omit<RoomTask, "status" | "participants" | "steps"> & { status: string; participants: string; steps: string };
168
+ 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";
169
+ const jsonArray = <T>(value: string): T[] => {
170
+ try { const parsed = JSON.parse(value) as unknown; return Array.isArray(parsed) ? parsed as T[] : []; }
171
+ catch { return []; }
172
+ };
173
+ const roomTask = (row: RoomTaskRow): RoomTask => ({
174
+ ...row, status: row.status as RoomTaskStatus,
175
+ participants: jsonArray<string>(row.participants), steps: jsonArray<RoomTaskStep>(row.steps),
176
+ });
177
+
178
+ export function listRoomTasks(db: Database, roomID: string): RoomTask[] {
179
+ return (db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? ORDER BY created_at,id`).all(roomID) as RoomTaskRow[]).map(roomTask);
180
+ }
181
+
182
+ export function readRoomTask(db: Database, roomID: string, id: string): RoomTask | undefined {
183
+ const row = db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? AND id=?`).get(roomID, id) as RoomTaskRow | null;
184
+ return row ? roomTask(row) : undefined;
185
+ }
186
+
187
+ export function insertRoomTask(db: Database, task: RoomTask): void {
188
+ 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(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
189
+ .run(task.id, task.roomId, task.title, task.description, task.assignee, task.status, task.creatorName, task.creatorSessionID,
190
+ task.createdAt, task.updatedAt, task.dueDate, JSON.stringify(task.participants), task.conclusion, JSON.stringify(task.steps));
191
+ }
192
+
193
+ export type RoomTaskPatch = Partial<Pick<RoomTask, "title" | "description" | "assignee" | "status" | "dueDate" | "participants" | "conclusion" | "steps">>;
194
+
195
+ export function patchRoomTask(db: Database, roomID: string, id: string, patch: RoomTaskPatch, updatedAt: number): RoomTask | undefined {
196
+ const sets: string[] = [], values: string[] = [];
197
+ 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) {
198
+ if (value !== undefined) { sets.push(`${column}=?`); values.push(value); }
199
+ }
200
+ if (patch.participants !== undefined) { sets.push("participants=?"); values.push(JSON.stringify(patch.participants)); }
201
+ if (patch.steps !== undefined) { sets.push("steps=?"); values.push(JSON.stringify(patch.steps)); }
202
+ db.query(`UPDATE room_tasks SET ${sets.map((set) => `${set},`).join("")}updated_at=? WHERE room_id=? AND id=?`)
203
+ .run(...values, updatedAt, roomID, id);
204
+ return readRoomTask(db, roomID, id);
205
+ }
206
+
207
+ export function deleteRoomTask(db: Database, roomID: string, id: string): boolean {
208
+ return db.query("DELETE FROM room_tasks WHERE room_id=? AND id=?").run(roomID, id).changes > 0;
209
+ }
210
+
211
+ export function deleteCompletedRoomTasks(db: Database, roomID: string, creatorSessionID?: string): number {
212
+ return creatorSessionID === undefined
213
+ ? db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done'").run(roomID).changes
214
+ : db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done' AND creator_session_id=?").run(roomID, creatorSessionID).changes;
215
+ }
154
216
  async function ensureRoomColumns(db: Database): Promise<void> {
155
217
  await immediate(db, () => {
156
218
  const messageColumns = db.query("PRAGMA table_info(messages)").all() as Array<{ name: string }>;
@@ -161,6 +223,11 @@ async function ensureRoomColumns(db: Database): Promise<void> {
161
223
  if (!messageColumns.some((column) => column.name === "recalled_by")) db.exec("ALTER TABLE messages ADD COLUMN recalled_by TEXT");
162
224
  db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
163
225
  db.exec("CREATE INDEX IF NOT EXISTS messages_room_recalled ON messages(room_id,recalled_at)");
226
+ const taskColumns = db.query("PRAGMA table_info(room_tasks)").all() as Array<{ name: string }>;
227
+ if (!taskColumns.some((column) => column.name === "due_date")) db.exec("ALTER TABLE room_tasks ADD COLUMN due_date TEXT NOT NULL DEFAULT ''");
228
+ if (!taskColumns.some((column) => column.name === "participants")) db.exec("ALTER TABLE room_tasks ADD COLUMN participants TEXT NOT NULL DEFAULT '[]'");
229
+ if (!taskColumns.some((column) => column.name === "conclusion")) db.exec("ALTER TABLE room_tasks ADD COLUMN conclusion TEXT NOT NULL DEFAULT ''");
230
+ if (!taskColumns.some((column) => column.name === "steps")) db.exec("ALTER TABLE room_tasks ADD COLUMN steps TEXT NOT NULL DEFAULT '[]'");
164
231
  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
232
  db.exec(`CREATE TABLE IF NOT EXISTS room_join_requests(
166
233
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
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,13 +330,14 @@ 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);
339
341
  this.state.draft = "";
340
342
  this.touch();
341
343
  try {
@@ -348,7 +350,7 @@ export class ChatApp {
348
350
  this.setStatus("sent", "success");
349
351
  this.markRead();
350
352
  } catch (error) {
351
- if (!this.state.draft) this.state.draft = text;
353
+ if (!this.state.draft) this.state.draft = raw;
352
354
  this.setStatus(`send failed: ${errorText(error)}`, "error");
353
355
  }
354
356
  }
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.7";
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,26 @@ 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 marker = line.match(/^([ \t]*)(`{3,}|~{3,})/);
73
88
  if (fence) {
74
- if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length) fence = null;
89
+ if (marker && marker[2][0] === fence.char && marker[2].length >= fence.length
90
+ && marker[1].length <= fence.indent + 3) fence = null;
75
91
  return line;
76
92
  }
93
+ if (indented) {
94
+ if (!line.trim() || /^(?: {4,}|\t)/.test(line)) return line;
95
+ indented = false;
96
+ }
77
97
  if (marker) {
78
- fence = marker[1];
98
+ fence = { char: marker[2][0], length: marker[2].length, indent: marker[1].length };
99
+ return line;
100
+ }
101
+ if (/^(?: {4,}|\t)/.test(line)) {
102
+ indented = true;
79
103
  return line;
80
104
  }
81
105
  return inlineMentions(line);
@@ -0,0 +1,218 @@
1
+ // Mention helpers shared by the composer suggestions and outgoing messages.
2
+ // Display names stay visible while typing; the wire format is applied on send.
3
+ const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4
+
5
+ export function mentionNames(participants = []) {
6
+ const names = [];
7
+ const seen = new Set(["all"]);
8
+ for (const participant of Array.isArray(participants) ? participants : []) {
9
+ const name = String(participant?.name ?? participant?.id ?? "").trim();
10
+ if (!name || seen.has(name.toLowerCase())) continue;
11
+ seen.add(name.toLowerCase());
12
+ names.push(name);
13
+ }
14
+ return names;
15
+ }
16
+
17
+ export function mentionItems(participants, query = "") {
18
+ const needle = String(query ?? "").toLowerCase();
19
+ const items = mentionNames(participants).map((name) => ({
20
+ name,
21
+ insert: `@${name}`,
22
+ label: name,
23
+ }));
24
+ items.push({ name: "all", insert: "@all", label: "Everyone (@all)" });
25
+ return items.filter((item) => {
26
+ const haystack = `${item.label} ${item.name}`.toLowerCase();
27
+ return !needle || haystack.includes(needle);
28
+ });
29
+ }
30
+
31
+ /** Locate the @token at the end of the draft, outside email-like tokens. */
32
+ export function mentionTrigger(text) {
33
+ const source = String(text ?? "");
34
+ const match = source.match(/(^|[^\p{L}\p{N}_@])@([^\n@]{0,64})$/u);
35
+ if (!match) return null;
36
+ const query = match[2];
37
+ return { start: source.length - query.length - 1, query, cursor: source.length };
38
+ }
39
+
40
+ export function insertMention(draft, trigger, insert) {
41
+ const source = String(draft ?? "");
42
+ const at = trigger ?? mentionTrigger(source);
43
+ if (!at) return source;
44
+ const before = source.slice(0, at.start);
45
+ const after = source.slice(at.cursor ?? source.length);
46
+ return `${before}${insert} ${after}`;
47
+ }
48
+
49
+ /** Find a closing backtick run of exactly `length`, never a longer run. */
50
+ function closingBackticks(source, from, end, length) {
51
+ let i = from;
52
+ while (i < end) {
53
+ if (source[i] !== "`") {
54
+ i += 1;
55
+ continue;
56
+ }
57
+ let run = 0;
58
+ while (i + run < end && source[i + run] === "`") run += 1;
59
+ if (run === length) return i;
60
+ i += run;
61
+ }
62
+ return -1;
63
+ }
64
+
65
+ /** Split Markdown prose from fenced/indented code and inline code spans. */
66
+ function codeSegments(source) {
67
+ const segments = [];
68
+ let proseStart = 0;
69
+ let lineStart = 0;
70
+ const push = (start, end, code) => {
71
+ if (end > start) segments.push({ text: source.slice(start, end), code, start, end });
72
+ };
73
+ while (lineStart < source.length) {
74
+ const lineEnd = source.indexOf("\n", lineStart);
75
+ const end = lineEnd < 0 ? source.length : lineEnd;
76
+ const line = source.slice(lineStart, end);
77
+ const opener = /^([ \t]*)(`{3,}|~{3,})/.exec(line);
78
+ if (opener) {
79
+ if (lineStart > proseStart) splitInlineCode(source, proseStart, lineStart, segments);
80
+ const fence = opener[2];
81
+ const indent = opener[1].length;
82
+ let scan = lineEnd < 0 ? source.length : lineEnd + 1;
83
+ let closed = source.length;
84
+ while (scan < source.length) {
85
+ const nextEnd = source.indexOf("\n", scan);
86
+ const stop = nextEnd < 0 ? source.length : nextEnd;
87
+ const close = /^([ \t]*)(`{3,}|~{3,})[ \t]*$/.exec(source.slice(scan, stop));
88
+ if (close && close[2][0] === fence[0] && close[2].length >= fence.length
89
+ && close[1].length <= indent + 3) {
90
+ closed = nextEnd < 0 ? source.length : nextEnd + 1;
91
+ break;
92
+ }
93
+ scan = nextEnd < 0 ? source.length : nextEnd + 1;
94
+ }
95
+ push(lineStart, closed, true);
96
+ proseStart = closed;
97
+ lineStart = closed;
98
+ continue;
99
+ }
100
+ // CommonMark indented code is also literal. Treat four spaces/tab as code
101
+ // rather than risking a mention rewrite inside it.
102
+ if (/^(?: {4,}|\t)/.test(line)) {
103
+ if (lineStart > proseStart) splitInlineCode(source, proseStart, lineStart, segments);
104
+ let scan = lineStart;
105
+ let closed = source.length;
106
+ while (scan < source.length) {
107
+ const nextEnd = source.indexOf("\n", scan);
108
+ const stop = nextEnd < 0 ? source.length : nextEnd;
109
+ const current = source.slice(scan, stop);
110
+ if (current.trim() && !/^(?: {4,}|\t)/.test(current)) {
111
+ closed = scan;
112
+ break;
113
+ }
114
+ scan = nextEnd < 0 ? source.length : nextEnd + 1;
115
+ }
116
+ push(lineStart, closed, true);
117
+ proseStart = closed;
118
+ lineStart = closed;
119
+ continue;
120
+ }
121
+ lineStart = lineEnd < 0 ? source.length : lineEnd + 1;
122
+ }
123
+ splitInlineCode(source, proseStart, source.length, segments);
124
+ return segments;
125
+ }
126
+
127
+ function splitInlineCode(source, start, end, segments) {
128
+ let prose = start;
129
+ let i = start;
130
+ while (i < end) {
131
+ if (source[i] !== "`") {
132
+ i += 1;
133
+ continue;
134
+ }
135
+ let run = 1;
136
+ while (i + run < end && source[i + run] === "`") run += 1;
137
+ const close = closingBackticks(source, i + run, end, run);
138
+ if (close < 0) {
139
+ i += run;
140
+ continue;
141
+ }
142
+ if (i > prose) segments.push({ text: source.slice(prose, i), code: false, start: prose, end: i });
143
+ segments.push({ text: source.slice(i, close + run), code: true, start: i, end: close + run });
144
+ prose = close + run;
145
+ i = prose;
146
+ }
147
+ if (end > prose) segments.push({ text: source.slice(prose, end), code: false, start: prose, end });
148
+ }
149
+
150
+ function convertPlain(segment, names) {
151
+ if (!segment) return segment;
152
+ const candidates = ["all", ...names].sort((a, b) => b.length - a.length);
153
+ const pattern = new RegExp(
154
+ `(?<![\\p{L}\\p{N}_.@])@(${candidates.map(escapeRegExp).join("|")})(?![\\p{L}\\p{N}_])`,
155
+ "gu",
156
+ );
157
+ return segment.replace(pattern, (_match, name) => `<at>@${name}</at>`);
158
+ }
159
+
160
+ function convertProse(source, names) {
161
+ const tag = /<at>[\s\S]*?<\/at>/giu;
162
+ let output = "";
163
+ let last = 0;
164
+ for (const match of source.matchAll(tag)) {
165
+ output += convertPlain(source.slice(last, match.index), names);
166
+ output += match[0];
167
+ last = match.index + match[0].length;
168
+ }
169
+ return output + convertPlain(source.slice(last), names);
170
+ }
171
+
172
+ /** Convert known @names and @all to <at> tags, preserving code and existing tags. */
173
+ export function canonicalizeMentions(text, participants = []) {
174
+ const source = String(text ?? "");
175
+ const names = mentionNames(participants);
176
+ return codeSegments(source)
177
+ .map((segment) => (segment.code ? segment.text : convertProse(segment.text, names)))
178
+ .join("");
179
+ }
180
+
181
+ /** Character ranges for visible mention chips, excluding email-like tokens. */
182
+ export function mentionRanges(text, participants = []) {
183
+ const source = String(text ?? "");
184
+ const ranges = [];
185
+ const candidates = ["all", ...mentionNames(participants)].sort((a, b) => b.length - a.length);
186
+ const pattern = new RegExp(
187
+ `(?<![\\p{L}\\p{N}_.@])@(${candidates.map(escapeRegExp).join("|")})(?![\\p{L}\\p{N}_])`,
188
+ "gu",
189
+ );
190
+ for (const segment of codeSegments(source)) {
191
+ if (segment.code) continue;
192
+ const tag = /<at>([\s\S]*?)<\/at>/giu;
193
+ let last = 0;
194
+ const plain = [];
195
+ for (const match of segment.text.matchAll(tag)) {
196
+ const inner = match[1];
197
+ const trimmed = inner.trim();
198
+ const at = trimmed.indexOf("@");
199
+ if (at >= 0) {
200
+ const innerStart = segment.start + match.index + 4 + (inner.length - inner.trimStart().length);
201
+ ranges.push({ start: innerStart + at, end: innerStart + trimmed.length });
202
+ }
203
+ plain.push([last, match.index]);
204
+ last = match.index + match[0].length;
205
+ }
206
+ plain.push([last, segment.text.length]);
207
+ for (const [start, end] of plain) {
208
+ const piece = segment.text.slice(start, end);
209
+ for (const match of piece.matchAll(pattern)) {
210
+ ranges.push({
211
+ start: segment.start + start + match.index,
212
+ end: segment.start + start + match.index + match[0].length,
213
+ });
214
+ }
215
+ }
216
+ }
217
+ return ranges.sort((a, b) => a.start - b.start);
218
+ }
@@ -1,6 +1,7 @@
1
1
  // Message actions on top of the palette prompts: recall and reveal by id with
2
2
  // confirmation, and a prompt-based reply flow that uses api.send's replyTo.
3
3
  import { mergeMessages } from "./messages.mjs";
4
+ import { canonicalizeMentions } from "./mentions.mjs";
4
5
 
5
6
  const errorText = (error) => (error instanceof Error ? error.message : String(error ?? "unknown error"));
6
7
 
@@ -49,7 +50,7 @@ export function attachMessageActions(Class) {
49
50
  return;
50
51
  }
51
52
  if (prompt.action === "message-ask") {
52
- const question = String(value ?? "").trim();
53
+ const question = canonicalizeMentions(String(value ?? "").trim(), room.participants);
53
54
  if (!question) {
54
55
  palette.error = "question text is required";
55
56
  this.touch();
@@ -108,7 +109,7 @@ export function attachMessageActions(Class) {
108
109
  return;
109
110
  }
110
111
  if (prompt.action === "message-reply-text") {
111
- const text = String(value ?? "").trim();
112
+ const text = canonicalizeMentions(String(value ?? "").trim(), room.participants);
112
113
  if (!text) {
113
114
  palette.error = "reply text is required";
114
115
  this.touch();
@@ -19,6 +19,12 @@ export function attachPalette(Class) {
19
19
  prompt: null,
20
20
  searching: false,
21
21
  error: "",
22
+ commands: buildCommands({
23
+ rooms: this.state.rooms,
24
+ current: this.state.current,
25
+ joined: this.state.joined,
26
+ help: this.state.help,
27
+ }),
22
28
  };
23
29
  this.touch();
24
30
  },
@@ -32,12 +38,13 @@ export function attachPalette(Class) {
32
38
  paletteCommands() {
33
39
  const palette = this.state.palette;
34
40
  const query = palette?.mode === "commands" ? String(palette.query ?? "").replace(/^\s*\//, "") : "";
35
- return filterCommands(buildCommands({
41
+ const commands = palette?.commands ?? buildCommands({
36
42
  rooms: this.state.rooms,
37
43
  current: this.state.current,
38
44
  joined: this.state.joined,
39
45
  help: this.state.help,
40
- }), query);
46
+ });
47
+ return filterCommands(commands, query);
41
48
  },
42
49
 
43
50
  paletteItems() {
@@ -3,6 +3,7 @@
3
3
  import { BoxRenderable, StyledText, TextRenderable, bold, fg } from "@opentui/core";
4
4
  import { formatMessage, messageStamp, sanitizeText } from "./messages.mjs";
5
5
  import { addNotice, buildMessageBlock, hashText, markdownStyle } from "./message-view.mjs";
6
+ import { syncMentionHighlights } from "./ui-mentions.mjs";
6
7
  import { connectionStyle } from "./ui-theme.mjs";
7
8
 
8
9
  const clear = (container) => {
@@ -256,7 +257,10 @@ export function syncComposer(ui, state) {
256
257
  ui.textarea.textColor = ui.theme.text;
257
258
  ui.textarea.focusedTextColor = ui.theme.text;
258
259
  ui.prompt.fg = ui.theme.accent;
259
- if (ui.textarea.plainText === draft) return;
260
+ if (ui.textarea.plainText === draft) {
261
+ syncMentionHighlights(ui, state);
262
+ return;
263
+ }
260
264
  ui.syncingComposer = true;
261
265
  try {
262
266
  ui.textarea.setText(draft);
@@ -266,6 +270,8 @@ export function syncComposer(ui, state) {
266
270
  } finally {
267
271
  ui.syncingComposer = false;
268
272
  }
273
+ ui.mentionSignature = "";
274
+ syncMentionHighlights(ui, state);
269
275
  }
270
276
 
271
277
  export function syncStatus(ui, state) {
@@ -461,7 +467,8 @@ export function syncHelp(ui, state) {
461
467
  ["Enter", "send message"],
462
468
  ["Ctrl+J", "insert newline"],
463
469
  ["Esc", "clear / blur"],
464
- ["/", "commands (empty composer)"],
470
+ ["/", "inline commands"],
471
+ ["@", "mention members"],
465
472
  ["Alt+Space", "palette / search"],
466
473
  ["Ctrl+R", "refresh rooms"],
467
474
  ["Ctrl+C", "quit"],
@@ -0,0 +1,44 @@
1
+ // Accent-colored mention chips inside the composer. Extmarks keep ranges tied
2
+ // to the text; we rebuild them only when the visible ranges or theme change.
3
+ import { SyntaxStyle } from "@opentui/core";
4
+ import { mentionNames, mentionRanges } from "./mentions.mjs";
5
+
6
+ function styleFor(ui) {
7
+ let style = ui.mentionStyles.get(ui.theme.mode);
8
+ if (!style) {
9
+ style = SyntaxStyle.fromStyles({
10
+ mention: { fg: ui.theme.accent, bold: true },
11
+ });
12
+ ui.mentionStyles.set(ui.theme.mode, style);
13
+ }
14
+ return style;
15
+ }
16
+
17
+ export function syncMentionHighlights(ui, state) {
18
+ const textarea = ui.textarea;
19
+ const text = textarea.plainText;
20
+ const ranges = mentionRanges(text, state.current?.participants);
21
+ const names = mentionNames(state.current?.participants).join(",");
22
+ const signature = `${ui.theme.mode}:${names}:${ranges.map((range) => `${range.start}-${range.end}`).join(",")}`;
23
+ if (signature === ui.mentionSignature) return;
24
+ if (!ranges.length) {
25
+ textarea.extmarks.clear();
26
+ ui.mentionSignature = signature;
27
+ return;
28
+ }
29
+
30
+ const style = styleFor(ui);
31
+ const styleId = style.getStyleId("mention") ?? style.registerStyle("mention", {
32
+ fg: ui.theme.accent,
33
+ bold: true,
34
+ });
35
+ textarea.syntaxStyle = style;
36
+ const extmarks = textarea.extmarks;
37
+ const typeId = ui.mentionTypeId ??= extmarks.registerType("mention");
38
+ extmarks.clear();
39
+ for (const range of ranges) {
40
+ extmarks.create({ start: range.start, end: range.end, styleId, typeId });
41
+ }
42
+ ui.mentionSignature = signature;
43
+ ui.renderer.requestRender();
44
+ }
@@ -0,0 +1,63 @@
1
+ // Compact command/mention suggestions floating just above the composer.
2
+ // Rows are plain renderables so the popup never owns keyboard focus.
3
+ import { BoxRenderable, TextRenderable } from "@opentui/core";
4
+
5
+ export const SUGGEST_LIMIT = 6;
6
+
7
+ export function createSuggestView(renderer, theme, view) {
8
+ view.suggestBox = new BoxRenderable(renderer, {
9
+ id: "suggest",
10
+ position: "absolute",
11
+ left: 1,
12
+ right: 1,
13
+ bottom: 7,
14
+ height: 5,
15
+ zIndex: 80,
16
+ visible: false,
17
+ focusable: false,
18
+ border: true,
19
+ borderStyle: "rounded",
20
+ borderColor: theme.border,
21
+ backgroundColor: theme.surface,
22
+ title: " commands ",
23
+ titleAlignment: "left",
24
+ flexDirection: "column",
25
+ });
26
+ renderer.root.add(view.suggestBox);
27
+
28
+ view.suggestRows = [];
29
+ for (let index = 0; index < SUGGEST_LIMIT; index += 1) {
30
+ const row = new BoxRenderable(renderer, {
31
+ id: `suggest-row-${index}`,
32
+ height: 1,
33
+ flexShrink: 0,
34
+ flexDirection: "row",
35
+ paddingX: 1,
36
+ visible: false,
37
+ });
38
+ const label = new TextRenderable(renderer, {
39
+ id: `suggest-label-${index}`,
40
+ flexGrow: 1,
41
+ height: 1,
42
+ wrapMode: "none",
43
+ truncate: true,
44
+ fg: theme.text,
45
+ content: "",
46
+ });
47
+ row.add(label);
48
+ view.suggestBox.add(row);
49
+ view.suggestRows.push({ row, label });
50
+ }
51
+
52
+ view.suggestHint = new TextRenderable(renderer, {
53
+ id: "suggest-hint",
54
+ height: 1,
55
+ flexShrink: 0,
56
+ truncate: true,
57
+ wrapMode: "none",
58
+ paddingX: 1,
59
+ fg: theme.muted,
60
+ content: "",
61
+ });
62
+ view.suggestBox.add(view.suggestHint);
63
+ }