@alexsun-top/opencode-chat-room 0.8.4 → 0.8.6

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 (206) hide show
  1. package/CHANGELOG.md +17 -3
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +20 -1
  5. package/dist/cli.js +3785 -1462
  6. package/package.json +19 -11
  7. package/packages/chat-room-channeld/README.md +16 -10
  8. package/packages/chat-room-channeld/src/delivery.ts +0 -4
  9. package/packages/chat-room-channeld/src/host.ts +48 -37
  10. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  11. package/packages/chat-room-channeld/src/pg/database.ts +141 -49
  12. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  13. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  14. package/packages/chat-room-channeld/src/pg/worker.mjs +148 -99
  15. package/packages/chat-room-channeld/src/pg/worker.mts +201 -0
  16. package/packages/chat-room-channeld/src/state-rows.ts +132 -0
  17. package/packages/chat-room-channeld/src/state.ts +129 -157
  18. package/plugin.ts +21 -5
  19. package/server/app.ts +9 -0
  20. package/server/assets/base.css +22 -2
  21. package/server/assets/chat/admin.js +17 -1
  22. package/server/assets/chat/announcements.js +79 -34
  23. package/server/assets/chat/attachments.js +3 -3
  24. package/server/assets/chat/clipboard.js +1 -1
  25. package/server/assets/chat/confirm-dialog.js +3 -0
  26. package/server/assets/chat/copy-action.js +1 -1
  27. package/server/assets/chat/create-room-dialog.js +7 -0
  28. package/server/assets/chat/diagram-viewer.js +4 -8
  29. package/server/assets/chat/doc-preview.js +71 -31
  30. package/server/assets/chat/editor.js +49 -10
  31. package/server/assets/chat/events.js +13 -6
  32. package/server/assets/chat/files.js +33 -27
  33. package/server/assets/chat/history-loader.js +31 -15
  34. package/server/assets/chat/integration-editor.js +27 -1
  35. package/server/assets/chat/integrations.js +108 -16
  36. package/server/assets/chat/join-requests.js +40 -2
  37. package/server/assets/chat/locales/de.js +5 -3
  38. package/server/assets/chat/locales/es.js +5 -3
  39. package/server/assets/chat/locales/fr.js +5 -3
  40. package/server/assets/chat/locales/it.js +5 -3
  41. package/server/assets/chat/locales/ja.js +5 -3
  42. package/server/assets/chat/locales/ko.js +5 -3
  43. package/server/assets/chat/markdown-footnotes.js +27 -15
  44. package/server/assets/chat/markdown.js +6 -12
  45. package/server/assets/chat/members.js +34 -22
  46. package/server/assets/chat/mentions.js +8 -5
  47. package/server/assets/chat/message-cache.js +9 -3
  48. package/server/assets/chat/message-polling.js +10 -4
  49. package/server/assets/chat/message-window.js +58 -1
  50. package/server/assets/chat/messages.js +90 -37
  51. package/server/assets/chat/office-preview.js +3 -3
  52. package/server/assets/chat/operator.js +624 -0
  53. package/server/assets/chat/palette.js +7 -10
  54. package/server/assets/chat/panels.js +42 -0
  55. package/server/assets/chat/questions.js +75 -58
  56. package/server/assets/chat/recall.js +14 -5
  57. package/server/assets/chat/receipts.js +63 -7
  58. package/server/assets/chat/refresh-timing.js +6 -0
  59. package/server/assets/chat/reminders.js +47 -13
  60. package/server/assets/chat/replies.js +39 -25
  61. package/server/assets/chat/resource-format.js +6 -3
  62. package/server/assets/chat/room-list.js +202 -3
  63. package/server/assets/chat/room-watcher.js +3 -1
  64. package/server/assets/chat/rooms.js +29 -7
  65. package/server/assets/chat/settings.js +37 -6
  66. package/server/assets/chat/shortcuts.js +3 -1
  67. package/server/assets/chat/side-pane.js +1 -1
  68. package/server/assets/chat/state.js +51 -18
  69. package/server/assets/chat/system-events.js +3 -2
  70. package/server/assets/chat/system-messages.js +15 -15
  71. package/server/assets/chat/tasks.js +37 -14
  72. package/server/assets/chat/window-controls.js +25 -15
  73. package/server/assets/code-highlight.css +0 -13
  74. package/server/assets/conversation.css +45 -5
  75. package/server/assets/doc-preview.css +9 -0
  76. package/server/assets/files.css +4 -0
  77. package/server/assets/monaco/integration-rules.js +1 -1
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  79. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  80. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  81. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  82. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  83. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  84. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  85. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  86. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  87. package/server/assets/responsive.css +12 -2
  88. package/server/assets/settings.css +3 -1
  89. package/server/assets/tasks.css +6 -1
  90. package/server/assets/window-controls.css +3 -1
  91. package/server/channels.ts +3 -2
  92. package/server/chat.html +7 -2
  93. package/server/inbox.ts +3 -1
  94. package/server/join-requests.ts +8 -1
  95. package/server/member-routes.ts +16 -2
  96. package/server/newrooms.ts +2 -13
  97. package/server/operator-auth.ts +21 -0
  98. package/server/operator-routes.ts +150 -0
  99. package/server/operator-state.ts +64 -0
  100. package/server/operator.css +139 -0
  101. package/server/room-owner.ts +17 -0
  102. package/server/routes/inbox.ts +15 -5
  103. package/server/routes/pages.ts +12 -2
  104. package/server/routes/room-actions.ts +4 -3
  105. package/server/sw.js +3 -1
  106. package/server/system.html +109 -0
  107. package/server/wake.ts +1 -1
  108. package/skills/chatroom/SKILL.md +9 -0
  109. package/src/README.md +1 -1
  110. package/src/acp/client.ts +254 -0
  111. package/src/acp/protocol.ts +300 -0
  112. package/src/acp/watch.ts +498 -0
  113. package/src/agent/agent-receipts.ts +98 -8
  114. package/src/center/center-client.ts +6 -1
  115. package/src/center/center-inbox.ts +54 -7
  116. package/src/center/center-wake.ts +57 -3
  117. package/src/center/forward-client.ts +48 -0
  118. package/src/center/mentions.ts +16 -3
  119. package/src/center/notification-delay.ts +139 -0
  120. package/src/center/queue.ts +3 -0
  121. package/src/config/file-config.ts +25 -0
  122. package/src/mcp/server.ts +389 -0
  123. package/src/protocol/config.ts +7 -0
  124. package/src/runtime/plugin-notifications.ts +43 -9
  125. package/src/runtime/v2-plugin.ts +14 -3
  126. package/src/runtime/v2-receiver.ts +10 -2
  127. package/src/runtime/watch.ts +5 -1
  128. package/src/state/pg-database.ts +133 -49
  129. package/src/state/pg-sql.mjs +157 -142
  130. package/src/state/pg-sql.mts +175 -0
  131. package/src/state/pg-worker.mjs +148 -99
  132. package/src/state/pg-worker.mts +201 -0
  133. package/src/state/receiver-state.ts +47 -0
  134. package/src/state/sqlite-database.ts +6 -2
  135. package/src/state/sqlite-members.ts +48 -4
  136. package/src/state/sqlite-messages.ts +25 -12
  137. package/src/state/sqlite-schema.ts +4 -1
  138. package/src/state/sqlite-state.ts +1 -1
  139. package/src/state/store.ts +31 -11
  140. package/src/tui/app-types.mjs +1 -0
  141. package/src/tui/app-types.mts +175 -0
  142. package/src/tui/app.mjs +473 -423
  143. package/src/tui/app.mts +543 -0
  144. package/src/tui/config.mjs +166 -158
  145. package/src/tui/config.mts +247 -0
  146. package/src/tui/http.mjs +239 -206
  147. package/src/tui/http.mts +412 -0
  148. package/src/tui/i18n.mjs +17 -20
  149. package/src/tui/i18n.mts +42 -0
  150. package/src/tui/info-app.mjs +431 -427
  151. package/src/tui/info-app.mts +500 -0
  152. package/src/tui/info-content.mjs +205 -199
  153. package/src/tui/info-content.mts +341 -0
  154. package/src/tui/join-app.mjs +75 -64
  155. package/src/tui/join-app.mts +99 -0
  156. package/src/tui/locales/en.mjs +302 -320
  157. package/src/tui/locales/en.mts +349 -0
  158. package/src/tui/locales/zh-CN.mjs +302 -320
  159. package/src/tui/locales/zh-CN.mts +349 -0
  160. package/src/tui/main.mjs +219 -213
  161. package/src/tui/main.mts +255 -0
  162. package/src/tui/markdown.mjs +128 -272
  163. package/src/tui/markdown.mts +152 -0
  164. package/src/tui/mentions.mjs +181 -184
  165. package/src/tui/mentions.mts +251 -0
  166. package/src/tui/message-app.mjs +181 -173
  167. package/src/tui/message-app.mts +213 -0
  168. package/src/tui/message-view.mjs +90 -111
  169. package/src/tui/message-view.mts +151 -0
  170. package/src/tui/messages.mjs +55 -49
  171. package/src/tui/messages.mts +106 -0
  172. package/src/tui/palette-app.mjs +364 -344
  173. package/src/tui/palette-app.mts +388 -0
  174. package/src/tui/palette.mjs +100 -98
  175. package/src/tui/palette.mts +176 -0
  176. package/src/tui/prefs.mjs +56 -63
  177. package/src/tui/prefs.mts +126 -0
  178. package/src/tui/reminder-app.mjs +191 -181
  179. package/src/tui/reminder-app.mts +228 -0
  180. package/src/tui/room-settings-app.mjs +275 -242
  181. package/src/tui/room-settings-app.mts +318 -0
  182. package/src/tui/session.mjs +30 -29
  183. package/src/tui/session.mts +51 -0
  184. package/src/tui/settings-app.mjs +151 -138
  185. package/src/tui/settings-app.mts +179 -0
  186. package/src/tui/ui-content.mjs +426 -421
  187. package/src/tui/ui-content.mts +499 -0
  188. package/src/tui/ui-help.mjs +58 -67
  189. package/src/tui/ui-help.mts +87 -0
  190. package/src/tui/ui-mentions.mjs +34 -36
  191. package/src/tui/ui-mentions.mts +60 -0
  192. package/src/tui/ui-overlay-view.mjs +259 -267
  193. package/src/tui/ui-overlay-view.mts +322 -0
  194. package/src/tui/ui-suggest-view.mjs +54 -57
  195. package/src/tui/ui-suggest-view.mts +78 -0
  196. package/src/tui/ui-suggest.mjs +164 -167
  197. package/src/tui/ui-suggest.mts +248 -0
  198. package/src/tui/ui-theme.mjs +52 -57
  199. package/src/tui/ui-theme.mts +98 -0
  200. package/src/tui/ui-view.mjs +267 -275
  201. package/src/tui/ui-view.mts +308 -0
  202. package/src/tui/ui.mjs +372 -359
  203. package/src/tui/ui.mts +440 -0
  204. package/src/tui/wire.mjs +215 -0
  205. package/src/tui/wire.mts +383 -0
  206. package/src/web/integration-rules-editor.ts +25 -2
@@ -0,0 +1,176 @@
1
+ // Pure command palette logic: command lists, scoped client-side search,
2
+ // ranking and snippets. No I/O lives here so it is easy to test.
3
+ import { t } from "./i18n.mjs";
4
+ import type { ChatMessage } from "./messages.mjs";
5
+
6
+ const SEARCH_LIMIT = 50;
7
+
8
+ export interface Command {
9
+ id: string;
10
+ label: string;
11
+ keywords?: string[];
12
+ roomId?: string;
13
+ }
14
+
15
+ export interface PaletteRoom {
16
+ id: string;
17
+ name: string;
18
+ joined?: boolean;
19
+ }
20
+
21
+ export interface PaletteCurrent {
22
+ id: string;
23
+ name: string;
24
+ }
25
+
26
+ export interface BuildCommandsInput {
27
+ rooms?: readonly PaletteRoom[];
28
+ current?: PaletteCurrent | null;
29
+ joined?: boolean;
30
+ help?: boolean;
31
+ }
32
+
33
+ export interface MessageSource {
34
+ roomId: string;
35
+ roomName: string;
36
+ messages?: readonly ChatMessage[];
37
+ }
38
+
39
+ export interface SearchResult {
40
+ roomId: string;
41
+ roomName: string;
42
+ message: ChatMessage;
43
+ snippet: string;
44
+ score: number;
45
+ }
46
+
47
+ export type MessageCache = Map<string, ChatMessage[]> | Record<string, ChatMessage[]>;
48
+ export type Scope = "room" | "all";
49
+
50
+ /** Match the visible label plus optional search aliases such as exit/quit. */
51
+ export function filterCommands(commands: readonly Command[], query: string): Command[] {
52
+ const normalize = (value: unknown) => String(value ?? "").trim().toLowerCase()
53
+ .replace(/^[/\\]+/, "").replace(/[-_]+/g, " ");
54
+ const needle = normalize(query);
55
+ if (!needle) return commands.slice();
56
+ return commands.filter((command) => {
57
+ const haystack = normalize([command.label, ...(command.keywords ?? [])].join(" "));
58
+ return haystack.includes(needle);
59
+ });
60
+ }
61
+
62
+ /** Commands shown when the palette query is empty. */
63
+ export function buildCommands({ rooms = [], current = null, joined = false, help = false }: BuildCommandsInput = {}): Command[] {
64
+ const commands: Command[] = [
65
+ { id: "refresh", label: t("command.refresh") },
66
+ { id: "new-room", label: t("command.newRoom") },
67
+ ];
68
+ for (const room of rooms) {
69
+ if (!room.joined) commands.push({ id: `join:${room.id}`, label: t("command.join", { name: room.name }), roomId: room.id });
70
+ }
71
+ if (current && joined) commands.push({ id: "leave-room", label: t("command.leave", { name: current.name }) });
72
+ commands.push({ id: "toggle-help", label: help ? t("command.hideHelp") : t("command.showHelp") });
73
+ for (const room of rooms) {
74
+ if (room.joined) commands.push({ id: `switch:${room.id}`, label: t("command.switch", { name: room.name }), roomId: room.id });
75
+ }
76
+ commands.push({ id: "search-room", label: t("command.searchRoom") });
77
+ commands.push({ id: "search-all", label: t("command.searchAll") });
78
+ commands.push({ id: "members", label: t("command.members") });
79
+ commands.push({ id: "join-requests", label: t("command.joinRequests") });
80
+ commands.push({ id: "announcements", label: t("command.announcements") });
81
+ commands.push({ id: "questions", label: t("command.questions") });
82
+ commands.push({ id: "files", label: t("command.files") });
83
+ commands.push({ id: "reminders", label: t("command.reminders") });
84
+ commands.push({ id: "settings", label: t("command.settings") });
85
+ commands.push({ id: "room-settings", label: t("command.roomSettings") });
86
+ commands.push({ id: "delete-room", label: t("command.deleteRoom") });
87
+ commands.push({ id: "recall-message", label: t("command.recall") });
88
+ commands.push({ id: "reveal-message", label: t("command.reveal") });
89
+ commands.push({ id: "reply-message", label: t("command.reply") });
90
+ commands.push({ id: "ask-question", label: t("command.ask") });
91
+ commands.push({ id: "quit", label: t("command.quit"), keywords: ["exit", "quit", "q"] });
92
+ return commands;
93
+ }
94
+
95
+ export function nextScope(scope: string): Scope {
96
+ return scope === "all" ? "room" : "all";
97
+ }
98
+
99
+ /** Pick the message sources for a scope from the local cache. */
100
+ export function scopeSources(
101
+ { rooms = [], current = null, scope = "room", cache = new Map() }: {
102
+ rooms?: readonly PaletteRoom[];
103
+ current?: PaletteCurrent | null;
104
+ scope?: string;
105
+ cache?: MessageCache;
106
+ } = {},
107
+ ): MessageSource[] {
108
+ const messagesOf = (id: string): ChatMessage[] => {
109
+ const value = cache instanceof Map ? cache.get(id) : cache[id];
110
+ return Array.isArray(value) ? value : [];
111
+ };
112
+ if (scope !== "all") {
113
+ return current ? [{ roomId: current.id, roomName: current.name, messages: messagesOf(current.id) }] : [];
114
+ }
115
+ return rooms
116
+ .filter((room) => room.joined)
117
+ .map((room) => ({ roomId: room.id, roomName: room.name, messages: messagesOf(room.id) }));
118
+ }
119
+
120
+ function stamp(message: ChatMessage | null | undefined): number {
121
+ const value = message?.createdAt;
122
+ if (typeof value === "number" && Number.isFinite(value)) return value;
123
+ const parsed = Date.parse(String(value ?? ""));
124
+ return Number.isFinite(parsed) ? parsed : 0;
125
+ }
126
+
127
+ function scoreOf(text: string, needle: string, index: number): number {
128
+ let score = 0;
129
+ let from = 0;
130
+ let hits = 0;
131
+ while ((from = text.indexOf(needle, from)) !== -1) {
132
+ hits += 1;
133
+ from += needle.length;
134
+ }
135
+ score += hits * 10;
136
+ if (index === 0) score += 5;
137
+ else if (/[\s.,!?;:]/.test(text[index - 1] ?? "")) score += 3;
138
+ return score;
139
+ }
140
+
141
+ export function snippetOf(text: string, index: number, length: number, radius = 24): string {
142
+ const plain = String(text).replace(/\s+/g, " ").trim();
143
+ const start = Math.max(0, index - radius);
144
+ const end = Math.min(plain.length, index + length + radius);
145
+ return `${start > 0 ? "…" : ""}${plain.slice(start, end)}${end < plain.length ? "…" : ""}`;
146
+ }
147
+
148
+ /** Search loaded messages. Recalled messages are never searchable. */
149
+ export function searchMessages(
150
+ query: string,
151
+ sources: readonly MessageSource[],
152
+ { limit = SEARCH_LIMIT }: { limit?: number } = {},
153
+ ): SearchResult[] {
154
+ const needle = String(query ?? "").trim().toLowerCase();
155
+ if (!needle) return [];
156
+ const results: SearchResult[] = [];
157
+ for (const source of sources) {
158
+ for (const message of source.messages ?? []) {
159
+ if (!message || message.recalledAt) continue;
160
+ const text = String(message.text ?? "").replace(/\s+/g, " ").trim();
161
+ if (!text || text === "[recalled]") continue;
162
+ const lower = text.toLowerCase();
163
+ const index = lower.indexOf(needle);
164
+ if (index < 0) continue;
165
+ results.push({
166
+ roomId: source.roomId,
167
+ roomName: source.roomName,
168
+ message,
169
+ snippet: snippetOf(text, index, needle.length),
170
+ score: scoreOf(lower, needle, index),
171
+ });
172
+ }
173
+ }
174
+ results.sort((a, b) => b.score - a.score || stamp(b.message) - stamp(a.message));
175
+ return results.slice(0, limit);
176
+ }
package/src/tui/prefs.mjs CHANGED
@@ -7,86 +7,79 @@ import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { loadTuiConfig } from "./config.mjs";
9
9
  import { DEFAULT_LANGUAGE, normalizeLanguage } from "./i18n.mjs";
10
-
11
10
  export const PREFS_FILE_NAME = "tui.json";
12
11
  export const DEFAULT_THEME = "dark";
13
12
  export const THEMES = ["dark", "light"];
14
13
  const LANGUAGE_VALUES = ["en", "zh", "zh-cn", "zh_cn"];
15
-
16
14
  export function normalizeTheme(value) {
17
- return String(value ?? "").trim().toLowerCase() === "light" ? "light" : "dark";
15
+ return String(value ?? "").trim().toLowerCase() === "light" ? "light" : "dark";
18
16
  }
19
-
20
17
  export function tuiPrefsFile(env = process.env) {
21
- const home = env.HOME || os.homedir();
22
- const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
23
- return path.join(configHome, "chatroom", PREFS_FILE_NAME);
18
+ const home = env.HOME || os.homedir();
19
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
20
+ return path.join(configHome, "chatroom", PREFS_FILE_NAME);
24
21
  }
25
-
26
22
  /** Keep only known, valid fields; unknown or malformed values are dropped. */
27
23
  function cleanPrefs(value) {
28
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
29
- const prefs = {};
30
- const language = typeof value.language === "string" ? value.language.trim().toLowerCase() : "";
31
- if (LANGUAGE_VALUES.includes(language)) prefs.language = normalizeLanguage(language);
32
- const theme = typeof value.theme === "string" ? value.theme.trim().toLowerCase() : "";
33
- if (THEMES.includes(theme)) prefs.theme = theme;
34
- if (typeof value.participant === "string" && value.participant.trim()) {
35
- prefs.participant = value.participant.trim().slice(0, 64);
36
- }
37
- if (typeof value.url === "string" && /^https?:\/\/[^/]+/i.test(value.url.trim())) {
38
- prefs.url = value.url.trim().replace(/\/+$/, "");
39
- }
40
- return prefs;
24
+ if (!value || typeof value !== "object" || Array.isArray(value))
25
+ return {};
26
+ const record = value;
27
+ const prefs = {};
28
+ const language = typeof record.language === "string" ? record.language.trim().toLowerCase() : "";
29
+ if (LANGUAGE_VALUES.includes(language))
30
+ prefs.language = normalizeLanguage(language);
31
+ const theme = typeof record.theme === "string" ? record.theme.trim().toLowerCase() : "";
32
+ if (THEMES.includes(theme))
33
+ prefs.theme = theme;
34
+ if (typeof record.participant === "string" && record.participant.trim()) {
35
+ prefs.participant = record.participant.trim().slice(0, 64);
36
+ }
37
+ if (typeof record.url === "string" && /^https?:\/\/[^/]+/i.test(record.url.trim())) {
38
+ prefs.url = record.url.trim().replace(/\/+$/, "");
39
+ }
40
+ return prefs;
41
41
  }
42
-
43
42
  /** A missing or malformed file is not an error: it means "no preferences". */
44
43
  export function loadTuiPrefs(env = process.env) {
45
- try {
46
- const data = JSON.parse(readFileSync(tuiPrefsFile(env), "utf8"));
47
- return cleanPrefs(data);
48
- } catch {
49
- return {};
50
- }
44
+ try {
45
+ const data = JSON.parse(readFileSync(tuiPrefsFile(env), "utf8"));
46
+ return cleanPrefs(data);
47
+ }
48
+ catch {
49
+ return {};
50
+ }
51
51
  }
52
-
53
52
  export function saveTuiPrefs(env = process.env, patch = {}) {
54
- const prefs = cleanPrefs({ ...loadTuiPrefs(env), ...cleanPrefs(patch) });
55
- const file = tuiPrefsFile(env);
56
- mkdirSync(path.dirname(file), { recursive: true });
57
- const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
58
- writeFileSync(temp, `${JSON.stringify(prefs, null, 2)}\n`, { mode: 0o600 });
59
- renameSync(temp, file);
60
- return prefs;
53
+ const prefs = cleanPrefs({ ...loadTuiPrefs(env), ...cleanPrefs(patch) });
54
+ const file = tuiPrefsFile(env);
55
+ mkdirSync(path.dirname(file), { recursive: true });
56
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
57
+ writeFileSync(temp, `${JSON.stringify(prefs, null, 2)}\n`, { mode: 0o600 });
58
+ renameSync(temp, file);
59
+ return prefs;
61
60
  }
62
-
63
61
  function envValue(env, key) {
64
- const value = env[key];
65
- return value === undefined || value === "" ? undefined : value;
62
+ const value = env[key];
63
+ return value === undefined || value === "" ? undefined : value;
66
64
  }
67
-
68
65
  /** Resolve language and theme: flags > env > tui.json > project config > defaults. */
69
66
  export function resolveTuiPreferences(env = process.env, cwd = process.cwd(), flags = {}, sources = {}) {
70
- const prefs = sources.prefs ?? loadTuiPrefs(env);
71
- const project = sources.project === undefined ? loadTuiConfig(env, cwd) : sources.project;
72
- return {
73
- language: normalizeLanguage(
74
- flags.language
75
- ?? envValue(env, "CHAT_ROOM_TUI_LANGUAGE")
76
- ?? prefs.language
77
- ?? project?.client?.language
78
- ?? project?.language
79
- ?? DEFAULT_LANGUAGE,
80
- ),
81
- theme: normalizeTheme(
82
- flags.theme
83
- ?? envValue(env, "CHAT_ROOM_TUI_THEME")
84
- ?? prefs.theme
85
- ?? project?.client?.theme
86
- ?? project?.theme
87
- ?? DEFAULT_THEME,
88
- ),
89
- prefs,
90
- prefsFile: tuiPrefsFile(env),
91
- };
92
- }
67
+ const prefs = sources.prefs ?? loadTuiPrefs(env);
68
+ const project = sources.project === undefined ? loadTuiConfig(env, cwd) : sources.project;
69
+ return {
70
+ language: normalizeLanguage(flags.language
71
+ ?? envValue(env, "CHAT_ROOM_TUI_LANGUAGE")
72
+ ?? prefs.language
73
+ ?? project?.client?.language
74
+ ?? project?.language
75
+ ?? DEFAULT_LANGUAGE),
76
+ theme: normalizeTheme(flags.theme
77
+ ?? envValue(env, "CHAT_ROOM_TUI_THEME")
78
+ ?? prefs.theme
79
+ ?? project?.client?.theme
80
+ ?? project?.theme
81
+ ?? DEFAULT_THEME),
82
+ prefs,
83
+ prefsFile: tuiPrefsFile(env),
84
+ };
85
+ }
@@ -0,0 +1,126 @@
1
+ // Persistent TUI preferences in $XDG_CONFIG_HOME/chatroom/tui.json. The file
2
+ // only stores language, theme, participant and url; a server token is never
3
+ // written or accepted from this layer.
4
+ import { randomUUID } from "node:crypto";
5
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import type { Env, TuiProjectConfig } from "./config.mjs";
9
+ import { loadTuiConfig } from "./config.mjs";
10
+ import { DEFAULT_LANGUAGE, normalizeLanguage } from "./i18n.mjs";
11
+ import type { Language } from "./i18n.mjs";
12
+
13
+ export type Theme = "dark" | "light";
14
+
15
+ export interface TuiPreferences {
16
+ language?: Language;
17
+ theme?: Theme;
18
+ participant?: string;
19
+ url?: string;
20
+ }
21
+
22
+ export interface ResolvedTuiPreferences {
23
+ language: Language;
24
+ theme: Theme;
25
+ prefs: TuiPreferences;
26
+ prefsFile: string;
27
+ }
28
+
29
+ export interface PreferenceFlags {
30
+ language?: string;
31
+ theme?: string;
32
+ }
33
+
34
+ export interface PreferenceSources {
35
+ prefs?: TuiPreferences;
36
+ project?: TuiProjectConfig | null;
37
+ }
38
+
39
+ export const PREFS_FILE_NAME = "tui.json";
40
+ export const DEFAULT_THEME: Theme = "dark";
41
+ export const THEMES: readonly Theme[] = ["dark", "light"];
42
+ const LANGUAGE_VALUES: readonly string[] = ["en", "zh", "zh-cn", "zh_cn"];
43
+
44
+ export function normalizeTheme(value: unknown): Theme {
45
+ return String(value ?? "").trim().toLowerCase() === "light" ? "light" : "dark";
46
+ }
47
+
48
+ export function tuiPrefsFile(env: Env = process.env): string {
49
+ const home = env.HOME || os.homedir();
50
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
51
+ return path.join(configHome, "chatroom", PREFS_FILE_NAME);
52
+ }
53
+
54
+ /** Keep only known, valid fields; unknown or malformed values are dropped. */
55
+ function cleanPrefs(value: unknown): TuiPreferences {
56
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
57
+ const record = value as Record<string, unknown>;
58
+ const prefs: TuiPreferences = {};
59
+ const language = typeof record.language === "string" ? record.language.trim().toLowerCase() : "";
60
+ if (LANGUAGE_VALUES.includes(language)) prefs.language = normalizeLanguage(language);
61
+ const theme = typeof record.theme === "string" ? record.theme.trim().toLowerCase() : "";
62
+ if (THEMES.includes(theme as Theme)) prefs.theme = theme as Theme;
63
+ if (typeof record.participant === "string" && record.participant.trim()) {
64
+ prefs.participant = record.participant.trim().slice(0, 64);
65
+ }
66
+ if (typeof record.url === "string" && /^https?:\/\/[^/]+/i.test(record.url.trim())) {
67
+ prefs.url = record.url.trim().replace(/\/+$/, "");
68
+ }
69
+ return prefs;
70
+ }
71
+
72
+ /** A missing or malformed file is not an error: it means "no preferences". */
73
+ export function loadTuiPrefs(env: Env = process.env): TuiPreferences {
74
+ try {
75
+ const data: unknown = JSON.parse(readFileSync(tuiPrefsFile(env), "utf8"));
76
+ return cleanPrefs(data);
77
+ } catch {
78
+ return {};
79
+ }
80
+ }
81
+
82
+ export function saveTuiPrefs(env: Env = process.env, patch: TuiPreferences = {}): TuiPreferences {
83
+ const prefs = cleanPrefs({ ...loadTuiPrefs(env), ...cleanPrefs(patch) });
84
+ const file = tuiPrefsFile(env);
85
+ mkdirSync(path.dirname(file), { recursive: true });
86
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
87
+ writeFileSync(temp, `${JSON.stringify(prefs, null, 2)}\n`, { mode: 0o600 });
88
+ renameSync(temp, file);
89
+ return prefs;
90
+ }
91
+
92
+ function envValue(env: Env, key: string): string | undefined {
93
+ const value = env[key];
94
+ return value === undefined || value === "" ? undefined : value;
95
+ }
96
+
97
+ /** Resolve language and theme: flags > env > tui.json > project config > defaults. */
98
+ export function resolveTuiPreferences(
99
+ env: Env = process.env,
100
+ cwd = process.cwd(),
101
+ flags: PreferenceFlags = {},
102
+ sources: PreferenceSources = {},
103
+ ): ResolvedTuiPreferences {
104
+ const prefs = sources.prefs ?? loadTuiPrefs(env);
105
+ const project = sources.project === undefined ? loadTuiConfig(env, cwd) : sources.project;
106
+ return {
107
+ language: normalizeLanguage(
108
+ flags.language
109
+ ?? envValue(env, "CHAT_ROOM_TUI_LANGUAGE")
110
+ ?? prefs.language
111
+ ?? project?.client?.language
112
+ ?? project?.language
113
+ ?? DEFAULT_LANGUAGE,
114
+ ),
115
+ theme: normalizeTheme(
116
+ flags.theme
117
+ ?? envValue(env, "CHAT_ROOM_TUI_THEME")
118
+ ?? prefs.theme
119
+ ?? project?.client?.theme
120
+ ?? project?.theme
121
+ ?? DEFAULT_THEME,
122
+ ),
123
+ prefs,
124
+ prefsFile: tuiPrefsFile(env),
125
+ };
126
+ }