@alexsun-top/opencode-chat-room 0.7.3 → 0.7.5

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 (89) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +12 -5
  3. package/README.zh-CN.md +12 -5
  4. package/cli.ts +26 -6
  5. package/dist/cli.js +7804 -0
  6. package/package.json +19 -6
  7. package/plugin.ts +7 -4
  8. package/server/admin-auth.ts +1 -1
  9. package/server/admin-routes.ts +2 -2
  10. package/server/admin-state.ts +2 -1
  11. package/server/assets/FLUENT-ICONS-LICENSE +25 -0
  12. package/server/assets/NOTICE.txt +2 -1
  13. package/server/assets/attachments.css +1 -1
  14. package/server/assets/base.css +29 -7
  15. package/server/assets/chat/admin.js +43 -3
  16. package/server/assets/chat/announcements.js +5 -3
  17. package/server/assets/chat/confirm-dialog.js +12 -2
  18. package/server/assets/chat/create-room-dialog.js +5 -3
  19. package/server/assets/chat/events.js +32 -7
  20. package/server/assets/chat/files.js +369 -0
  21. package/server/assets/chat/history-loader.js +36 -26
  22. package/server/assets/chat/icons.js +15 -0
  23. package/server/assets/chat/index.js +7 -1
  24. package/server/assets/chat/locales/de.js +19 -2
  25. package/server/assets/chat/locales/es.js +19 -2
  26. package/server/assets/chat/locales/fr.js +19 -2
  27. package/server/assets/chat/locales/it.js +19 -2
  28. package/server/assets/chat/locales/ja.js +19 -2
  29. package/server/assets/chat/locales/ko.js +19 -2
  30. package/server/assets/chat/markdown.js +5 -33
  31. package/server/assets/chat/message-polling.js +61 -6
  32. package/server/assets/chat/message-window.js +28 -0
  33. package/server/assets/chat/messages.js +32 -12
  34. package/server/assets/chat/palette.js +396 -0
  35. package/server/assets/chat/pwa.js +67 -9
  36. package/server/assets/chat/recall.js +3 -2
  37. package/server/assets/chat/replies.js +2 -1
  38. package/server/assets/chat/rooms.js +20 -7
  39. package/server/assets/chat/search.js +137 -0
  40. package/server/assets/chat/settings.js +11 -5
  41. package/server/assets/chat/shortcuts.js +1 -1
  42. package/server/assets/chat/state.js +38 -4
  43. package/server/assets/code-highlight.css +0 -5
  44. package/server/assets/conversation.css +5 -4
  45. package/server/assets/edit-room.css +77 -0
  46. package/server/assets/files.css +222 -0
  47. package/server/assets/fluent-icons.svg +42 -0
  48. package/server/assets/icons.css +9 -0
  49. package/server/assets/palette.css +263 -0
  50. package/server/assets/recall.css +2 -2
  51. package/server/assets/responsive.css +6 -5
  52. package/server/assets/room-create.css +1 -1
  53. package/server/assets/settings.css +10 -7
  54. package/server/chat-server.ts +46 -29
  55. package/server/chat.html +175 -61
  56. package/server/http-server.ts +182 -0
  57. package/server/join-requests.ts +4 -4
  58. package/server/manifest.webmanifest +1 -1
  59. package/server/member-routes.ts +3 -3
  60. package/server/message-recall-routes.ts +1 -1
  61. package/server/newrooms.ts +4 -4
  62. package/server/resource-routes.ts +19 -4
  63. package/server/room-join.ts +1 -1
  64. package/server/room-payload.ts +1 -1
  65. package/server/sw.js +12 -1
  66. package/server/wake.ts +1 -1
  67. package/src/README.md +4 -2
  68. package/src/config/file-config.ts +294 -0
  69. package/src/rooms/resource-read.ts +2 -1
  70. package/src/rooms/resource-upload.ts +6 -3
  71. package/src/rooms/resources.ts +7 -2
  72. package/src/runtime/watch.ts +13 -8
  73. package/src/state/receiver-state.ts +3 -5
  74. package/src/state/sqlite-state.ts +11 -7
  75. package/src/state/sqlite.ts +80 -0
  76. package/src/state/store.ts +1 -0
  77. package/src/tui/app.mjs +417 -0
  78. package/src/tui/config.mjs +194 -0
  79. package/src/tui/http.mjs +103 -0
  80. package/src/tui/main.mjs +176 -0
  81. package/src/tui/messages.mjs +67 -0
  82. package/src/tui/palette-app.mjs +265 -0
  83. package/src/tui/palette.mjs +101 -0
  84. package/src/tui/session.mjs +40 -0
  85. package/src/tui/ui-content.mjs +426 -0
  86. package/src/tui/ui-theme.mjs +60 -0
  87. package/src/tui/ui-view.mjs +452 -0
  88. package/src/tui/ui.mjs +262 -0
  89. package/src/tests/announcement-board.ts +0 -186
@@ -0,0 +1,103 @@
1
+ // Minimal runtime-neutral HTTP client for the central chat-room server. Uses
2
+ // global fetch; requests fail fast on a dead center and honor caller aborts.
3
+ const JOIN_PENDING = "Join request submitted. You are not a member yet; a human administrator must approve it.";
4
+
5
+ export class ApiError extends Error {
6
+ constructor(message, status) {
7
+ super(message);
8
+ this.name = "ApiError";
9
+ this.status = status;
10
+ }
11
+ }
12
+
13
+ const HINTS = {
14
+ 401: "unauthorized: check the server token (CHAT_ROOM_SERVER_TOKEN)",
15
+ 403: "forbidden: your session is not a room member or lacks permission",
16
+ 404: "not found: the room or resource does not exist",
17
+ 409: "conflict: you are not a room member, or the name is already in use",
18
+ };
19
+
20
+ function apiError(status, statusText, data) {
21
+ const hint = HINTS[status];
22
+ if (hint) return new ApiError(`${hint} (HTTP ${status})`, status);
23
+ const serverText = typeof data?.error === "string" ? data.error.trim() : "";
24
+ const detail = serverText || statusText || "request failed";
25
+ return new ApiError(`HTTP ${status}: ${detail}`, status);
26
+ }
27
+
28
+ function query(params) {
29
+ return Object.entries(params)
30
+ .filter(([, value]) => value !== undefined)
31
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
32
+ .join("&");
33
+ }
34
+
35
+ export function createApi({ url, token, requestTimeoutMs = 10000 }) {
36
+ const base = String(url ?? "").replace(/\/+$/, "");
37
+
38
+ async function call(route, { method = "GET", body, signal } = {}) {
39
+ const headers = {};
40
+ if (token) headers.Authorization = `Bearer ${token}`;
41
+ if (body !== undefined) headers["Content-Type"] = "application/json";
42
+ const timeout = AbortSignal.timeout(requestTimeoutMs);
43
+ const res = await fetch(`${base}${route}`, {
44
+ method,
45
+ headers,
46
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
47
+ signal: signal ? AbortSignal.any([timeout, signal]) : timeout,
48
+ });
49
+ const data = await res.json().catch(() => ({}));
50
+ if (!res.ok) throw apiError(res.status, res.statusText, data);
51
+ return { status: res.status, data };
52
+ }
53
+
54
+ const room = (roomId) => `/rooms/${encodeURIComponent(roomId)}`;
55
+
56
+ return {
57
+ async listRooms(sessionID) {
58
+ return (await call(`/rooms?${query({ sessionID })}`)).data;
59
+ },
60
+ async getRoom(roomId) {
61
+ return (await call(room(roomId))).data;
62
+ },
63
+ async history(roomId, sessionID, beforeSeq, limit = 100) {
64
+ const pageSize = Math.min(200, Math.max(1, Math.floor(limit)));
65
+ const params = { limit: pageSize, excludeSessionID: sessionID, beforeSeq };
66
+ const { data } = await call(`${room(roomId)}/history?${query(params)}`);
67
+ return data;
68
+ },
69
+ async join(roomId, sessionID, name) {
70
+ const { status, data } = await call(`${room(roomId)}/join`, {
71
+ method: "POST",
72
+ body: { sessionID, participantId: name, participantName: name },
73
+ });
74
+ if (status === 202) {
75
+ return { pending: true, message: typeof data.message === "string" ? data.message : JOIN_PENDING };
76
+ }
77
+ return { pending: false, room: data };
78
+ },
79
+ async joinStatus(roomId, sessionID) {
80
+ const { data } = await call(`${room(roomId)}/join-requests/status?${query({ sessionID })}`);
81
+ return data.status === "pending" || data.status === "joined" ? data.status : "none";
82
+ },
83
+ async leave(roomId, sessionID) {
84
+ await call(`${room(roomId)}/leave`, { method: "POST", body: { sessionID } });
85
+ },
86
+ async send(roomId, sessionID, text) {
87
+ return (await call(`${room(roomId)}/messages`, { method: "POST", body: { sessionID, text } })).data;
88
+ },
89
+ async poll(roomId, sessionID, afterTs, { signal, timeoutMs = 20000 } = {}) {
90
+ const wait = Number.isFinite(timeoutMs) ? Math.max(0, Math.floor(timeoutMs)) : 20000;
91
+ const after = Number.isFinite(afterTs) && afterTs >= 0 ? afterTs : undefined;
92
+ const params = { sessionID, roomId, excludeSelf: 0, timeout: wait, afterTs: after };
93
+ return (await call(`/inbox?${query(params)}`, { signal })).data;
94
+ },
95
+ async markRead(roomId, sessionID, ts) {
96
+ await call("/read", { method: "POST", body: { roomId, sessionID, ts } });
97
+ },
98
+ async createRoom(name, sessionID, ownerId, joinPolicy = "open") {
99
+ const body = { name, sessionID, ownerId, joinPolicy };
100
+ return (await call("/rooms", { method: "POST", body })).data;
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,176 @@
1
+ // CLI entry for `opencode-chat-room cli`. Config, HTTP and session helpers are
2
+ // imported lazily so --help/--version work without a terminal or OpenTUI.
3
+ import { readFileSync } from "node:fs";
4
+ import { createApp } from "./app.mjs";
5
+
6
+ const NAME = "opencode-chat-room cli";
7
+ const FALLBACK_VERSION = "0.7.5";
8
+
9
+ export const HELP = `opencode-chat-room cli - terminal client for a chat-room server
10
+
11
+ Usage: opencode-chat-room cli [--name <display name>]
12
+ opencode-chat-room cli --help
13
+ opencode-chat-room cli --version
14
+
15
+ Options:
16
+ --name <name> display name for this session
17
+ --help show this help
18
+ --version print the version
19
+
20
+ Config is read from chatroom.json / chatroom.jsonc / chatroom.yaml in the
21
+ current directory or ~/.config/chatroom, and from environment variables.
22
+ A token is never accepted on the command line. See the README for fields.
23
+
24
+ Keys: arrows select rooms · Enter opens · Tab focuses the composer ·
25
+ PageUp/PageDown scroll · Alt+Home/End jumps · Alt+Space or Ctrl+P opens the
26
+ palette · Ctrl+C quits.
27
+ This command needs an interactive terminal.
28
+ `;
29
+
30
+ export function parseArgs(argv = []) {
31
+ const options = { help: false, version: false, name: undefined };
32
+ for (let index = 0; index < argv.length; index += 1) {
33
+ const arg = argv[index];
34
+ if (arg === "--help" || arg === "-h") options.help = true;
35
+ else if (arg === "--version" || arg === "-v") options.version = true;
36
+ else if (arg === "--name") {
37
+ const value = argv[index + 1];
38
+ if (!value || value.startsWith("-")) return { error: "--name requires a display name" };
39
+ options.name = value;
40
+ index += 1;
41
+ } else if (arg.startsWith("--name=")) {
42
+ const value = arg.slice("--name=".length);
43
+ if (!value) return { error: "--name requires a display name" };
44
+ options.name = value;
45
+ } else {
46
+ return { error: `unknown option: ${arg}` };
47
+ }
48
+ }
49
+ return options;
50
+ }
51
+
52
+ function runtimeProblem() {
53
+ const [nodeMajor = 0, nodeMinor = 0] = (process.versions.node ?? "").split(".").map(Number);
54
+ const [bunMajor = 0, bunMinor = 0, bunPatch = 0] = (process.versions.bun ?? "").split(".").map(Number);
55
+ const bunSupported = Boolean(process.versions.bun) &&
56
+ (bunMajor > 1 || (bunMajor === 1 && (bunMinor > 3 || (bunMinor === 3 && bunPatch >= 14))));
57
+ const nodeSupported = nodeMajor > 26 || (nodeMajor === 26 && nodeMinor >= 4);
58
+ if (typeof globalThis.Deno !== "undefined" || (!bunSupported && !nodeSupported)) {
59
+ return "the terminal client requires Bun 1.3.14+ or Node.js 26.4+. Run it with bunx, or with node --experimental-ffi on Node 26.4+.";
60
+ }
61
+ return "";
62
+ }
63
+
64
+ function version() {
65
+ try {
66
+ for (const candidate of ["../../package.json", "../package.json"]) {
67
+ try {
68
+ const data = JSON.parse(readFileSync(new URL(candidate, import.meta.url), "utf8"));
69
+ if (typeof data.version === "string") return data.version;
70
+ } catch {
71
+ // Source runs from src/tui, bundled CLI runs from dist.
72
+ }
73
+ }
74
+ return FALLBACK_VERSION;
75
+ } catch {
76
+ return FALLBACK_VERSION;
77
+ }
78
+ }
79
+
80
+ function redact(text, token) {
81
+ if (!token) return text;
82
+ return String(text).split(token).join("***");
83
+ }
84
+
85
+ function errorText(error) {
86
+ return error instanceof Error ? error.message : String(error ?? "unknown error");
87
+ }
88
+
89
+ export async function main(argv = process.argv.slice(2)) {
90
+ const options = parseArgs(argv);
91
+ if (options.error) {
92
+ process.stderr.write(`${NAME}: ${options.error}\n`);
93
+ return 1;
94
+ }
95
+ if (options.help) {
96
+ process.stdout.write(HELP);
97
+ return 0;
98
+ }
99
+ if (options.version) {
100
+ process.stdout.write(`${NAME} ${version()}\n`);
101
+ return 0;
102
+ }
103
+ const unsupported = runtimeProblem();
104
+ if (unsupported) {
105
+ process.stderr.write(`${NAME}: ${unsupported}\n`);
106
+ return 1;
107
+ }
108
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
109
+ process.stderr.write(`${NAME}: requires an interactive terminal. Use --help for usage.\n`);
110
+ return 1;
111
+ }
112
+
113
+ let config;
114
+ let renderer;
115
+ let ui;
116
+ try {
117
+ const [{ resolveTuiConfig }, { loadSession, saveSession }, { createApi }] = await Promise.all([
118
+ import("./config.mjs"),
119
+ import("./session.mjs"),
120
+ import("./http.mjs"),
121
+ ]);
122
+ config = resolveTuiConfig(process.env, process.cwd());
123
+ const requested = options.name?.trim();
124
+ const session = loadSession(config.stateFile, requested || config.participant);
125
+ const participant = requested || session.name || config.participant;
126
+ if (session.name !== participant) {
127
+ try {
128
+ saveSession(config.stateFile, { ...session, name: participant });
129
+ } catch {
130
+ // A read-only state file only costs a new identity next time.
131
+ }
132
+ }
133
+ const api = createApi({ url: config.url, token: config.token, requestTimeoutMs: config.requestTimeoutMs });
134
+ let host = config.url;
135
+ try {
136
+ host = new URL(config.url).host;
137
+ } catch {
138
+ // Keep the raw URL when it is not parseable.
139
+ }
140
+
141
+ const [{ createCliRenderer }, { createTui }] = await Promise.all([
142
+ import("@opentui/core"),
143
+ import("./ui.mjs"),
144
+ ]);
145
+ renderer = await createCliRenderer({
146
+ screenMode: "alternate-screen",
147
+ exitOnCtrlC: false,
148
+ useMouse: true,
149
+ targetFps: 30,
150
+ clearOnShutdown: true,
151
+ });
152
+ const app = createApp({ api, sessionID: session.sessionID, participant, host });
153
+ ui = createTui(renderer, app);
154
+ await app.init();
155
+ ui.sync();
156
+
157
+ return await new Promise((resolve) => {
158
+ const finish = () => resolve(0);
159
+ if (app.state.quit) {
160
+ finish();
161
+ return;
162
+ }
163
+ const unsubscribe = app.subscribe(() => {
164
+ if (!app.state.quit) return;
165
+ unsubscribe();
166
+ finish();
167
+ });
168
+ });
169
+ } catch (error) {
170
+ process.stderr.write(`${NAME}: ${redact(errorText(error), config?.token)}\n`);
171
+ return 1;
172
+ } finally {
173
+ ui?.destroy();
174
+ renderer?.destroy();
175
+ }
176
+ }
@@ -0,0 +1,67 @@
1
+ // Shared message helpers: ordering, sequence cursors, merging and display text.
2
+ export function messageStamp(message) {
3
+ const value = message?.createdAt;
4
+ if (typeof value === "number" && Number.isFinite(value)) return value;
5
+ const parsed = Date.parse(String(value ?? ""));
6
+ return Number.isFinite(parsed) ? parsed : 0;
7
+ }
8
+
9
+ export function oldestSeq(messages) {
10
+ let oldest;
11
+ for (const message of messages) {
12
+ if (typeof message?.seq === "number" && (oldest === undefined || message.seq < oldest)) oldest = message.seq;
13
+ }
14
+ return oldest;
15
+ }
16
+
17
+ /** Merge by message id, keep the first copy, and pick up recall updates. */
18
+ export function mergeMessages(target, items) {
19
+ if (!Array.isArray(items) || !items.length) return target;
20
+ const known = new Map(target.map((message) => [message.id, message]));
21
+ for (const item of items) {
22
+ if (!item || typeof item !== "object" || !item.id) continue;
23
+ const found = known.get(item.id);
24
+ if (found) {
25
+ if (item.recalledAt && !found.recalledAt) found.recalledAt = item.recalledAt;
26
+ continue;
27
+ }
28
+ const copy = { ...item };
29
+ known.set(item.id, copy);
30
+ target.push(copy);
31
+ }
32
+ target.sort((a, b) => messageStamp(a) - messageStamp(b));
33
+ return target;
34
+ }
35
+
36
+ /** Strip terminal control characters from server-provided text. */
37
+ export function sanitizeText(value) {
38
+ return String(value ?? "")
39
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, " ")
40
+ .replace(/\t/g, " ");
41
+ }
42
+
43
+ function formatTime(value) {
44
+ const date = new Date(typeof value === "number" ? value : String(value ?? ""));
45
+ if (Number.isNaN(date.getTime())) return "--:--";
46
+ const hours = String(date.getHours()).padStart(2, "0");
47
+ const minutes = String(date.getMinutes()).padStart(2, "0");
48
+ return `${hours}:${minutes}`;
49
+ }
50
+
51
+ function senderName(room, message) {
52
+ const id = message?.senderId ?? message?.senderSessionID ?? "?";
53
+ const person = (room?.participants ?? []).find((entry) => entry?.id === id);
54
+ return sanitizeText(person?.name ?? id);
55
+ }
56
+
57
+ /** Display fields for one message; recalled bodies are never shown. */
58
+ export function formatMessage(message, room) {
59
+ const recalled = Boolean(message?.recalledAt);
60
+ return {
61
+ time: formatTime(message?.createdAt),
62
+ sender: senderName(room, message),
63
+ body: recalled ? "[recalled]" : sanitizeText(message?.text),
64
+ recalled,
65
+ question: Boolean(message?.isQuestion),
66
+ };
67
+ }
@@ -0,0 +1,265 @@
1
+ // Command palette controller attached to ChatApp. Kept in its own file so the
2
+ // terminal core stays under the project line budget.
3
+ import { buildCommands, nextScope, scopeSources, searchMessages } from "./palette.mjs";
4
+ import { mergeMessages, oldestSeq } from "./messages.mjs";
5
+
6
+ const SEARCH_PAGES = 2;
7
+
8
+ export function attachPalette(Class) {
9
+ Object.assign(Class.prototype, {
10
+ openPalette() {
11
+ this.historyPages.clear();
12
+ this.state.help = false;
13
+ this.state.palette = {
14
+ mode: "commands",
15
+ query: "",
16
+ scope: "room",
17
+ selected: 0,
18
+ results: [],
19
+ prompt: null,
20
+ searching: false,
21
+ error: "",
22
+ };
23
+ this.touch();
24
+ },
25
+
26
+ closePalette() {
27
+ this.state.palette = null;
28
+ this.state.focus = "composer";
29
+ this.touch();
30
+ },
31
+
32
+ paletteCommands() {
33
+ return buildCommands({
34
+ rooms: this.state.rooms,
35
+ current: this.state.current,
36
+ joined: this.state.joined,
37
+ help: this.state.help,
38
+ });
39
+ },
40
+
41
+ paletteItems() {
42
+ const palette = this.state.palette;
43
+ if (!palette) return [];
44
+ if (palette.mode === "search") return palette.results;
45
+ if (palette.mode === "commands") return this.paletteCommands();
46
+ return [];
47
+ },
48
+
49
+ paletteScopeRooms(scope) {
50
+ if (scope === "all") return this.state.rooms.filter((room) => room.joined);
51
+ return this.state.current && this.state.joined ? [this.state.current] : [];
52
+ },
53
+
54
+ refreshPaletteResults() {
55
+ const palette = this.state.palette;
56
+ if (!palette || palette.mode !== "search") return;
57
+ palette.results = searchMessages(palette.query, scopeSources({
58
+ rooms: this.state.rooms,
59
+ current: this.state.current,
60
+ scope: palette.scope,
61
+ cache: this.cache,
62
+ }));
63
+ palette.selected = Math.min(palette.selected, Math.max(0, palette.results.length - 1));
64
+ this.touch();
65
+ },
66
+
67
+ async ensureSearchHistory() {
68
+ const palette = this.state.palette;
69
+ if (!palette || palette.mode !== "search" || typeof this.api.history !== "function") return;
70
+ const jobs = this.paletteScopeRooms(palette.scope).filter((room) =>
71
+ (this.historyPages.get(room.id) ?? 0) < SEARCH_PAGES
72
+ && this.historyMore.get(room.id) !== false
73
+ && !this.historyInflight.has(room.id));
74
+ if (!jobs.length) return;
75
+ palette.searching = true;
76
+ this.touch();
77
+ for (const room of jobs) {
78
+ this.historyInflight.add(room.id);
79
+ try {
80
+ await this.fetchHistoryPage(room.id);
81
+ } catch (error) {
82
+ if (this.state.palette) this.state.palette.error = `history: ${error.message ?? error}`;
83
+ } finally {
84
+ this.historyInflight.delete(room.id);
85
+ this.historyPages.set(room.id, (this.historyPages.get(room.id) ?? 0) + 1);
86
+ }
87
+ if (this.state.palette) this.refreshPaletteResults();
88
+ }
89
+ if (this.state.palette) {
90
+ this.state.palette.searching = this.historyInflight.size > 0;
91
+ this.refreshPaletteResults();
92
+ }
93
+ },
94
+
95
+ async fetchHistoryPage(roomID) {
96
+ const beforeSeq = this.historyCursor.get(roomID);
97
+ const result = await this.api.history(roomID, this.sessionID, beforeSeq);
98
+ const messages = Array.isArray(result) ? result : result?.messages ?? result?.items ?? [];
99
+ mergeMessages(this.historyList(roomID), messages);
100
+ this.historyMore.set(roomID, result?.hasMore === true);
101
+ const next = result?.nextBeforeSeq ?? result?.beforeSeq ?? oldestSeq(this.historyList(roomID));
102
+ if (typeof next === "number" && Number.isFinite(next)) this.historyCursor.set(roomID, next);
103
+ },
104
+
105
+ movePalette(delta) {
106
+ const items = this.paletteItems();
107
+ if (!items.length) return;
108
+ const palette = this.state.palette;
109
+ palette.selected = Math.min(items.length - 1, Math.max(0, palette.selected + delta));
110
+ this.touch();
111
+ },
112
+
113
+ async runPaletteSelection() {
114
+ const palette = this.state.palette;
115
+ if (!palette) return;
116
+ if (palette.mode === "prompt") {
117
+ await this.createRoomFromPrompt();
118
+ return;
119
+ }
120
+ if (palette.mode === "commands") {
121
+ const command = this.paletteCommands()[palette.selected];
122
+ if (command) await this.runPaletteCommand(command);
123
+ return;
124
+ }
125
+ const result = palette.results[palette.selected];
126
+ if (result) await this.activateResult(result);
127
+ },
128
+
129
+ async runPaletteCommand(command) {
130
+ const palette = this.state.palette;
131
+ switch (command.id) {
132
+ case "refresh":
133
+ this.closePalette();
134
+ await this.refreshRooms();
135
+ return;
136
+ case "new-room":
137
+ palette.mode = "prompt";
138
+ palette.prompt = { label: "New room name", value: "" };
139
+ palette.selected = 0;
140
+ palette.error = "";
141
+ this.touch();
142
+ return;
143
+ case "toggle-help":
144
+ this.state.help = !this.state.help;
145
+ this.state.palette = null;
146
+ this.state.focus = "rooms";
147
+ this.touch();
148
+ return;
149
+ case "leave-room":
150
+ this.closePalette();
151
+ await this.leaveCurrent();
152
+ return;
153
+ case "search-room":
154
+ case "search-all":
155
+ palette.mode = "search";
156
+ palette.scope = command.id === "search-all" ? "all" : "room";
157
+ palette.query = "";
158
+ palette.results = [];
159
+ palette.selected = 0;
160
+ palette.error = "";
161
+ this.touch();
162
+ void this.ensureSearchHistory();
163
+ return;
164
+ default:
165
+ if (command.roomId) {
166
+ const index = this.state.rooms.findIndex((room) => room.id === command.roomId);
167
+ this.closePalette();
168
+ if (index >= 0) await this.openRoom(index);
169
+ }
170
+ }
171
+ },
172
+
173
+ async activateResult(result) {
174
+ const index = this.state.rooms.findIndex((room) => room.id === result.roomId);
175
+ this.closePalette();
176
+ if (index >= 0 && this.state.current?.id !== result.roomId) await this.openRoom(index);
177
+ this.state.highlight = result.message.id;
178
+ this.state.focus = "composer";
179
+ this.touch();
180
+ },
181
+
182
+ async createRoomFromPrompt() {
183
+ const palette = this.state.palette;
184
+ const name = String(palette?.prompt?.value ?? "").trim();
185
+ if (!name) {
186
+ palette.error = "enter a room name";
187
+ this.touch();
188
+ return;
189
+ }
190
+ palette.searching = true;
191
+ palette.error = "";
192
+ this.touch();
193
+ try {
194
+ const created = await this.api.createRoom(name, this.sessionID, this.participant);
195
+ const roomID = created?.room?.id ?? created?.id;
196
+ await this.refreshRooms(true);
197
+ const index = this.state.rooms.findIndex((room) => room.id === roomID);
198
+ this.closePalette();
199
+ if (index >= 0) await this.openRoom(index);
200
+ else this.setStatus(`created #${name}`, "success");
201
+ } catch (error) {
202
+ if (this.state.palette) {
203
+ this.state.palette.searching = false;
204
+ this.state.palette.error = error.message ?? String(error);
205
+ this.touch();
206
+ }
207
+ }
208
+ },
209
+
210
+ async leaveCurrent() {
211
+ const room = this.state.current;
212
+ if (!room || !this.state.joined) {
213
+ this.setStatus("not joined to a room", "error");
214
+ return;
215
+ }
216
+ try {
217
+ await this.api.leave(room.id, this.sessionID);
218
+ this.stopPolling();
219
+ this.state.joined = false;
220
+ const summary = this.state.rooms.find((item) => item.id === room.id);
221
+ if (summary) summary.joined = false;
222
+ await this.refreshRooms(true);
223
+ this.setStatus(`left #${room.name}`, "success");
224
+ } catch (error) {
225
+ this.setStatus(`could not leave: ${error.message ?? error}`, "error");
226
+ }
227
+ },
228
+
229
+ setPaletteQuery(value) {
230
+ const palette = this.state.palette;
231
+ if (!palette || palette.mode === "prompt") return;
232
+ const query = String(value ?? "");
233
+ palette.error = "";
234
+ if (!query) {
235
+ palette.mode = "commands";
236
+ palette.query = "";
237
+ palette.results = [];
238
+ palette.selected = 0;
239
+ palette.searching = false;
240
+ this.touch();
241
+ return;
242
+ }
243
+ palette.mode = "search";
244
+ palette.query = query;
245
+ palette.selected = 0;
246
+ this.refreshPaletteResults();
247
+ void this.ensureSearchHistory();
248
+ },
249
+
250
+ setPalettePrompt(value) {
251
+ const palette = this.state.palette;
252
+ if (palette?.prompt) palette.prompt.value = String(value ?? "");
253
+ },
254
+
255
+ togglePaletteScope() {
256
+ const palette = this.state.palette;
257
+ if (!palette || palette.mode !== "search") return;
258
+ palette.scope = nextScope(palette.scope);
259
+ palette.selected = 0;
260
+ palette.error = "";
261
+ this.refreshPaletteResults();
262
+ void this.ensureSearchHistory();
263
+ },
264
+ });
265
+ }