@alexsun-top/opencode-chat-room 0.8.4 → 0.8.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 (136) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/cli.ts +1 -1
  5. package/dist/cli.js +35 -16
  6. package/package.json +14 -11
  7. package/packages/chat-room-channeld/README.md +3 -2
  8. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  9. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  10. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  11. package/packages/chat-room-channeld/src/pg/worker.mjs +107 -99
  12. package/packages/chat-room-channeld/src/pg/worker.mts +166 -0
  13. package/plugin.ts +1 -1
  14. package/server/assets/chat/admin.js +4 -1
  15. package/server/assets/chat/announcements.js +3 -0
  16. package/server/assets/chat/attachments.js +3 -3
  17. package/server/assets/chat/clipboard.js +1 -1
  18. package/server/assets/chat/copy-action.js +1 -1
  19. package/server/assets/chat/doc-preview.js +1 -1
  20. package/server/assets/chat/editor.js +11 -7
  21. package/server/assets/chat/events.js +7 -5
  22. package/server/assets/chat/files.js +5 -1
  23. package/server/assets/chat/integration-editor.js +2 -0
  24. package/server/assets/chat/integrations.js +1 -1
  25. package/server/assets/chat/join-requests.js +1 -1
  26. package/server/assets/chat/markdown-footnotes.js +8 -7
  27. package/server/assets/chat/markdown.js +6 -5
  28. package/server/assets/chat/members.js +3 -3
  29. package/server/assets/chat/mentions.js +8 -5
  30. package/server/assets/chat/message-cache.js +1 -1
  31. package/server/assets/chat/message-polling.js +2 -2
  32. package/server/assets/chat/message-window.js +1 -1
  33. package/server/assets/chat/messages.js +17 -3
  34. package/server/assets/chat/office-preview.js +3 -3
  35. package/server/assets/chat/palette.js +5 -3
  36. package/server/assets/chat/panels.js +19 -0
  37. package/server/assets/chat/questions.js +3 -2
  38. package/server/assets/chat/reminders.js +3 -0
  39. package/server/assets/chat/replies.js +6 -3
  40. package/server/assets/chat/resource-format.js +2 -2
  41. package/server/assets/chat/rooms.js +7 -4
  42. package/server/assets/chat/settings.js +4 -3
  43. package/server/assets/chat/shortcuts.js +3 -1
  44. package/server/assets/chat/side-pane.js +1 -1
  45. package/server/assets/chat/state.js +30 -11
  46. package/server/assets/chat/system-events.js +3 -2
  47. package/server/assets/chat/system-messages.js +15 -15
  48. package/server/assets/chat/tasks.js +4 -3
  49. package/server/assets/chat/window-controls.js +3 -2
  50. package/server/assets/conversation.css +14 -2
  51. package/server/assets/doc-preview.css +6 -0
  52. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  53. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  54. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  55. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  56. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  57. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  58. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  59. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  60. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  61. package/server/sw.js +3 -1
  62. package/skills/chatroom/SKILL.md +9 -0
  63. package/src/README.md +1 -1
  64. package/src/agent/agent-receipts.ts +12 -4
  65. package/src/center/center-client.ts +1 -1
  66. package/src/state/pg-sql.mjs +157 -142
  67. package/src/state/pg-sql.mts +175 -0
  68. package/src/state/pg-worker.mjs +107 -99
  69. package/src/state/pg-worker.mts +166 -0
  70. package/src/state/store.ts +21 -7
  71. package/src/tui/app-types.mjs +1 -0
  72. package/src/tui/app-types.mts +175 -0
  73. package/src/tui/app.mjs +426 -423
  74. package/src/tui/app.mts +500 -0
  75. package/src/tui/config.mjs +166 -158
  76. package/src/tui/config.mts +247 -0
  77. package/src/tui/http.mjs +239 -206
  78. package/src/tui/http.mts +412 -0
  79. package/src/tui/i18n.mjs +17 -20
  80. package/src/tui/i18n.mts +42 -0
  81. package/src/tui/info-app.mjs +431 -427
  82. package/src/tui/info-app.mts +500 -0
  83. package/src/tui/info-content.mjs +205 -199
  84. package/src/tui/info-content.mts +341 -0
  85. package/src/tui/join-app.mjs +75 -64
  86. package/src/tui/join-app.mts +99 -0
  87. package/src/tui/locales/en.mjs +302 -320
  88. package/src/tui/locales/en.mts +349 -0
  89. package/src/tui/locales/zh-CN.mjs +302 -320
  90. package/src/tui/locales/zh-CN.mts +349 -0
  91. package/src/tui/main.mjs +219 -213
  92. package/src/tui/main.mts +255 -0
  93. package/src/tui/markdown.mjs +128 -272
  94. package/src/tui/markdown.mts +152 -0
  95. package/src/tui/mentions.mjs +181 -184
  96. package/src/tui/mentions.mts +251 -0
  97. package/src/tui/message-app.mjs +181 -173
  98. package/src/tui/message-app.mts +213 -0
  99. package/src/tui/message-view.mjs +90 -111
  100. package/src/tui/message-view.mts +151 -0
  101. package/src/tui/messages.mjs +55 -49
  102. package/src/tui/messages.mts +106 -0
  103. package/src/tui/palette-app.mjs +364 -344
  104. package/src/tui/palette-app.mts +388 -0
  105. package/src/tui/palette.mjs +100 -98
  106. package/src/tui/palette.mts +176 -0
  107. package/src/tui/prefs.mjs +56 -63
  108. package/src/tui/prefs.mts +126 -0
  109. package/src/tui/reminder-app.mjs +191 -181
  110. package/src/tui/reminder-app.mts +228 -0
  111. package/src/tui/room-settings-app.mjs +257 -242
  112. package/src/tui/room-settings-app.mts +301 -0
  113. package/src/tui/session.mjs +30 -29
  114. package/src/tui/session.mts +51 -0
  115. package/src/tui/settings-app.mjs +151 -138
  116. package/src/tui/settings-app.mts +179 -0
  117. package/src/tui/ui-content.mjs +426 -421
  118. package/src/tui/ui-content.mts +499 -0
  119. package/src/tui/ui-help.mjs +58 -67
  120. package/src/tui/ui-help.mts +87 -0
  121. package/src/tui/ui-mentions.mjs +34 -36
  122. package/src/tui/ui-mentions.mts +60 -0
  123. package/src/tui/ui-overlay-view.mjs +259 -267
  124. package/src/tui/ui-overlay-view.mts +322 -0
  125. package/src/tui/ui-suggest-view.mjs +54 -57
  126. package/src/tui/ui-suggest-view.mts +78 -0
  127. package/src/tui/ui-suggest.mjs +164 -167
  128. package/src/tui/ui-suggest.mts +248 -0
  129. package/src/tui/ui-theme.mjs +52 -57
  130. package/src/tui/ui-theme.mts +98 -0
  131. package/src/tui/ui-view.mjs +267 -275
  132. package/src/tui/ui-view.mts +308 -0
  133. package/src/tui/ui.mjs +372 -359
  134. package/src/tui/ui.mts +440 -0
  135. package/src/tui/wire.mjs +215 -0
  136. package/src/tui/wire.mts +383 -0
@@ -1,15 +1,10 @@
1
1
  import { parentPort } from "node:worker_threads";
2
2
  import pg from "pg";
3
3
  import { hasSql, translate } from "./sql.mjs";
4
-
5
- // One pg.Client per worker: transactions and their advisory locks belong to a
6
- // single session, so a pool would be incorrect here.
7
- //
8
- // The worker deliberately starts with no workerData. Some Bun versions fail to
9
- // load `pg` in a worker that received any workerData at startup. The main
10
- // thread sends one init message over the default worker channel instead; that
11
- // message also transfers the request MessagePort and the ready SharedArrayBuffer.
12
-
4
+ const ERROR_FIELDS = [
5
+ "name", "code", "detail", "hint", "severity",
6
+ "position", "constraint", "table", "column", "dataType",
7
+ ];
13
8
  let client;
14
9
  let port;
15
10
  let readyFlag;
@@ -18,116 +13,129 @@ let connected = false;
18
13
  let draining = false;
19
14
  let closing = false;
20
15
  const queue = [];
21
-
22
16
  // SQLite returns all integers as JS numbers; int8 is a string in node-postgres
23
17
  // by default and COUNT(*) / BIGINT columns must stay numbers.
24
18
  pg.types.setTypeParser(20, (value) => Number(value));
25
19
  pg.types.setTypeParser(1700, (value) => Number(value));
26
-
27
20
  function normalize(params) {
28
- return params.map((value) =>
29
- value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
21
+ return params.map((value) => value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
30
22
  }
31
-
32
23
  function serialize(error) {
33
- return {
34
- name: error?.name,
35
- message: error?.message ?? String(error),
36
- code: error?.code,
37
- detail: error?.detail,
38
- hint: error?.hint,
39
- severity: error?.severity,
40
- position: error?.position,
41
- constraint: error?.constraint,
42
- table: error?.table,
43
- column: error?.column,
44
- dataType: error?.dataType,
45
- };
24
+ const source = (typeof error === "object" && error !== null ? error : {});
25
+ const result = {
26
+ message: typeof source.message === "string" ? source.message : String(error),
27
+ };
28
+ for (const key of ERROR_FIELDS) {
29
+ const value = source[key];
30
+ if (typeof value === "string" || typeof value === "number")
31
+ result[key] = value;
32
+ }
33
+ return result;
46
34
  }
47
-
48
35
  function signalReady() {
49
- Atomics.store(readyFlag, 0, 1);
50
- Atomics.notify(readyFlag, 0);
36
+ if (!readyFlag)
37
+ return;
38
+ Atomics.store(readyFlag, 0, 1);
39
+ Atomics.notify(readyFlag, 0);
51
40
  }
52
-
53
41
  function reply(request, payload) {
54
- port.postMessage({ id: request.id, ...payload });
55
- const flag = new Int32Array(request.signal);
56
- Atomics.store(flag, 0, 1);
57
- Atomics.notify(flag, 0);
42
+ port?.postMessage({ id: request.id, ...payload });
43
+ const flag = new Int32Array(request.signal);
44
+ Atomics.store(flag, 0, 1);
45
+ Atomics.notify(flag, 0);
58
46
  }
59
-
60
47
  async function handle(request) {
61
- try {
62
- const text = translate(request.sql);
63
- if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
64
- const params = normalize(request.params ?? []);
65
- // exec without params uses the simple-query protocol so multi-statement
66
- // schema scripts (and BEGIN/COMMIT) run in one round trip.
67
- const result = request.mode === "exec" && params.length === 0
68
- ? await client.query(text)
69
- : await client.query({ text, values: params });
70
- if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
71
- if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
72
- const last = Array.isArray(result) ? result[result.length - 1] : result;
73
- // Identity columns are never read through Database.run in the state layer;
74
- // keep the API shape without pretending to know an insert id.
75
- return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
76
- } catch (error) {
77
- return reply(request, { ok: false, error: serialize(error) });
78
- }
48
+ const db = client;
49
+ if (!db) {
50
+ return reply(request, { ok: false, error: { message: "PostgreSQL worker is not connected" } });
51
+ }
52
+ try {
53
+ const text = translate(request.sql);
54
+ if (!hasSql(text))
55
+ return reply(request, { ok: true, rows: [], row: null, changes: 0 });
56
+ const params = normalize(request.params ?? []);
57
+ // exec without params uses the simple-query protocol so multi-statement
58
+ // schema scripts (and BEGIN/COMMIT) run in one round trip.
59
+ const result = request.mode === "exec" && params.length === 0
60
+ ? await db.query(text)
61
+ : await db.query({ text, values: params });
62
+ if (request.mode === "get")
63
+ return reply(request, { ok: true, row: result.rows?.[0] ?? null });
64
+ if (request.mode === "all")
65
+ return reply(request, { ok: true, rows: result.rows ?? [] });
66
+ const last = Array.isArray(result) ? result.at(-1) : result;
67
+ // Identity columns are never read through Database.run in the state layer;
68
+ // keep the API shape without pretending to know an insert id.
69
+ return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
70
+ }
71
+ catch (error) {
72
+ return reply(request, { ok: false, error: serialize(error) });
73
+ }
79
74
  }
80
-
81
75
  async function drain() {
82
- draining = true;
83
- while (queue.length && !closing) await handle(queue.shift());
84
- draining = false;
76
+ draining = true;
77
+ while (queue.length && !closing) {
78
+ const request = queue.shift();
79
+ if (request)
80
+ await handle(request);
81
+ }
82
+ draining = false;
85
83
  }
86
-
87
84
  async function shutdown(signal) {
88
- closing = true;
89
- try { await client.end(); } catch { /* connection already gone */ }
90
- try { port.close(); } catch { /* already closed */ }
91
- if (signal) {
92
- const flag = new Int32Array(signal);
93
- Atomics.store(flag, 0, 1);
94
- Atomics.notify(flag, 0);
95
- }
85
+ closing = true;
86
+ try {
87
+ await client?.end();
88
+ }
89
+ catch { /* connection already gone */ }
90
+ try {
91
+ port?.close();
92
+ }
93
+ catch { /* already closed */ }
94
+ if (signal) {
95
+ const flag = new Int32Array(signal);
96
+ Atomics.store(flag, 0, 1);
97
+ Atomics.notify(flag, 0);
98
+ }
96
99
  }
97
-
98
100
  function handlePortMessage(message) {
99
- if (message?.type === "close") {
100
- void shutdown(message.signal);
101
- return;
102
- }
103
- queue.push(message);
104
- if (connected && !draining) void drain();
101
+ if (!("id" in message)) {
102
+ void shutdown(message.signal);
103
+ return;
104
+ }
105
+ queue.push(message);
106
+ if (connected && !draining)
107
+ void drain();
105
108
  }
106
-
107
109
  async function startup(connectionString, ready, timeout) {
108
- readyFlag = new Int32Array(ready);
109
- statementTimeout = timeout;
110
- try {
111
- client = new pg.Client({
112
- connectionString,
113
- application_name: "chat-room-channeld",
114
- statement_timeout: statementTimeout,
110
+ readyFlag = new Int32Array(ready);
111
+ statementTimeout = timeout;
112
+ try {
113
+ const db = new pg.Client({
114
+ connectionString,
115
+ application_name: "chat-room-channeld",
116
+ statement_timeout: statementTimeout,
117
+ });
118
+ client = db;
119
+ await db.connect();
120
+ connected = true;
121
+ port?.postMessage({ type: "ready" });
122
+ signalReady();
123
+ if (queue.length && !draining)
124
+ void drain();
125
+ }
126
+ catch (error) {
127
+ port?.postMessage({ type: "fatal", error: serialize(error) });
128
+ signalReady();
129
+ }
130
+ }
131
+ const parent = parentPort;
132
+ if (parent) {
133
+ parent.on("message", (message) => {
134
+ if (message?.type !== "init" || client)
135
+ return;
136
+ port = message.port;
137
+ port.on("message", handlePortMessage);
138
+ parent.close();
139
+ void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
115
140
  });
116
- await client.connect();
117
- connected = true;
118
- port.postMessage({ type: "ready" });
119
- signalReady();
120
- if (queue.length && !draining) void drain();
121
- } catch (error) {
122
- port.postMessage({ type: "fatal", error: serialize(error) });
123
- signalReady();
124
- }
125
141
  }
126
-
127
- parentPort.on("message", (message) => {
128
- if (message?.type !== "init" || client) return;
129
- port = message.port;
130
- port.on("message", handlePortMessage);
131
- parentPort.close();
132
- void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
133
- });
@@ -0,0 +1,166 @@
1
+ import { parentPort, type MessagePort } from "node:worker_threads";
2
+ import pg from "pg";
3
+ import { hasSql, translate } from "./sql.mjs";
4
+
5
+ // One pg.Client per worker: transactions and their advisory locks belong to a
6
+ // single session, so a pool would be incorrect here.
7
+ //
8
+ // The worker deliberately starts with no workerData. Some Bun versions fail to
9
+ // load `pg` in a worker that received any workerData at startup. The main
10
+ // thread sends one init message over the default worker channel instead; that
11
+ // message also transfers the request MessagePort and the ready SharedArrayBuffer.
12
+
13
+ type Request = {
14
+ id: number;
15
+ mode: "all" | "get" | "run" | "exec";
16
+ sql: string;
17
+ params?: unknown[];
18
+ signal: SharedArrayBuffer;
19
+ };
20
+
21
+ type PortMessage = Request | { type: "close"; signal?: SharedArrayBuffer };
22
+
23
+ type InitMessage = {
24
+ type: "init";
25
+ connectionString: string;
26
+ ready: SharedArrayBuffer;
27
+ statementTimeout?: number;
28
+ port: MessagePort;
29
+ };
30
+
31
+ type SerializedError = { message: string; [field: string]: string | number | undefined };
32
+
33
+ const ERROR_FIELDS = [
34
+ "name", "code", "detail", "hint", "severity",
35
+ "position", "constraint", "table", "column", "dataType",
36
+ ] as const;
37
+
38
+ let client: pg.Client | undefined;
39
+ let port: MessagePort | undefined;
40
+ let readyFlag: Int32Array | undefined;
41
+ let statementTimeout = 4_500;
42
+ let connected = false;
43
+ let draining = false;
44
+ let closing = false;
45
+ const queue: Request[] = [];
46
+
47
+ // SQLite returns all integers as JS numbers; int8 is a string in node-postgres
48
+ // by default and COUNT(*) / BIGINT columns must stay numbers.
49
+ pg.types.setTypeParser(20, (value) => Number(value));
50
+ pg.types.setTypeParser(1700, (value) => Number(value));
51
+
52
+ function normalize(params: unknown[]): unknown[] {
53
+ return params.map((value) =>
54
+ value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
55
+ }
56
+
57
+ function serialize(error: unknown): SerializedError {
58
+ const source = (typeof error === "object" && error !== null ? error : {}) as Record<string, unknown>;
59
+ const result: SerializedError = {
60
+ message: typeof source.message === "string" ? source.message : String(error),
61
+ };
62
+ for (const key of ERROR_FIELDS) {
63
+ const value = source[key];
64
+ if (typeof value === "string" || typeof value === "number") result[key] = value;
65
+ }
66
+ return result;
67
+ }
68
+
69
+ function signalReady(): void {
70
+ if (!readyFlag) return;
71
+ Atomics.store(readyFlag, 0, 1);
72
+ Atomics.notify(readyFlag, 0);
73
+ }
74
+
75
+ function reply(request: Request, payload: Record<string, unknown>): void {
76
+ port?.postMessage({ id: request.id, ...payload });
77
+ const flag = new Int32Array(request.signal);
78
+ Atomics.store(flag, 0, 1);
79
+ Atomics.notify(flag, 0);
80
+ }
81
+
82
+ async function handle(request: Request): Promise<void> {
83
+ const db = client;
84
+ if (!db) {
85
+ return reply(request, { ok: false, error: { message: "PostgreSQL worker is not connected" } });
86
+ }
87
+ try {
88
+ const text = translate(request.sql);
89
+ if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
90
+ const params = normalize(request.params ?? []);
91
+ // exec without params uses the simple-query protocol so multi-statement
92
+ // schema scripts (and BEGIN/COMMIT) run in one round trip.
93
+ const result = request.mode === "exec" && params.length === 0
94
+ ? await db.query(text)
95
+ : await db.query({ text, values: params });
96
+ if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
97
+ if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
98
+ const last = Array.isArray(result) ? result.at(-1) : result;
99
+ // Identity columns are never read through Database.run in the state layer;
100
+ // keep the API shape without pretending to know an insert id.
101
+ return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
102
+ } catch (error) {
103
+ return reply(request, { ok: false, error: serialize(error) });
104
+ }
105
+ }
106
+
107
+ async function drain(): Promise<void> {
108
+ draining = true;
109
+ while (queue.length && !closing) {
110
+ const request = queue.shift();
111
+ if (request) await handle(request);
112
+ }
113
+ draining = false;
114
+ }
115
+
116
+ async function shutdown(signal?: SharedArrayBuffer): Promise<void> {
117
+ closing = true;
118
+ try { await client?.end(); } catch { /* connection already gone */ }
119
+ try { port?.close(); } catch { /* already closed */ }
120
+ if (signal) {
121
+ const flag = new Int32Array(signal);
122
+ Atomics.store(flag, 0, 1);
123
+ Atomics.notify(flag, 0);
124
+ }
125
+ }
126
+
127
+ function handlePortMessage(message: PortMessage): void {
128
+ if (!("id" in message)) {
129
+ void shutdown(message.signal);
130
+ return;
131
+ }
132
+ queue.push(message);
133
+ if (connected && !draining) void drain();
134
+ }
135
+
136
+ async function startup(connectionString: string, ready: SharedArrayBuffer, timeout: number): Promise<void> {
137
+ readyFlag = new Int32Array(ready);
138
+ statementTimeout = timeout;
139
+ try {
140
+ const db = new pg.Client({
141
+ connectionString,
142
+ application_name: "chat-room-channeld",
143
+ statement_timeout: statementTimeout,
144
+ });
145
+ client = db;
146
+ await db.connect();
147
+ connected = true;
148
+ port?.postMessage({ type: "ready" });
149
+ signalReady();
150
+ if (queue.length && !draining) void drain();
151
+ } catch (error) {
152
+ port?.postMessage({ type: "fatal", error: serialize(error) });
153
+ signalReady();
154
+ }
155
+ }
156
+
157
+ const parent = parentPort;
158
+ if (parent) {
159
+ parent.on("message", (message: InitMessage) => {
160
+ if (message?.type !== "init" || client) return;
161
+ port = message.port;
162
+ port.on("message", handlePortMessage);
163
+ parent.close();
164
+ void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
165
+ });
166
+ }
package/plugin.ts CHANGED
@@ -501,7 +501,7 @@ const roomExecute = async (
501
501
  );
502
502
  const room = svc.getRoom(args.roomId);
503
503
  notifications.push({ roomId: args.roomId, roomName: room.name, messages: [...room.messages] });
504
- return `sent: ${args.text}\nmessage_id=${msg.id} room_id=${room.id}\n${formatRoom(svc, room)}`;
504
+ return `sent message_id=${msg.id} room_id=${room.id}`;
505
505
  }
506
506
  case "poll": {
507
507
  if (!args.roomId) {
@@ -1,5 +1,6 @@
1
1
  import { LS } from "./state.js";
2
2
  import { isRoomAdmin } from "./admin-badge.js";
3
+ import { closeOnBackdrop } from "./panels.js";
3
4
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
4
5
  // Owners and delegated humans manage settings; the agent designation comes from
5
6
  // the room payload and room owners manage it here instead of an operator token.
@@ -31,7 +32,7 @@ export function initAdmin(app) {
31
32
  if (target < 0)
32
33
  return;
33
34
  event.preventDefault();
34
- activateTab(items[target].dataset.editRoomTab, { focus: true });
35
+ activateTab(items[target]?.dataset.editRoomTab, { focus: true });
35
36
  };
36
37
  for (const tab of tabs) {
37
38
  tab.addEventListener("click", () => activateTab(tab.dataset.editRoomTab));
@@ -141,6 +142,8 @@ export function initAdmin(app) {
141
142
  });
142
143
  $("#btnCloseOwnerOnly").addEventListener("click", () => ownerDialog.close());
143
144
  $("#btnOwnerOnlyOk").addEventListener("click", () => ownerDialog.close());
145
+ // A plain explanation, not a form: a backdrop click dismisses it.
146
+ closeOnBackdrop(ownerDialog, () => ownerDialog.close());
144
147
  $("#btnCloseEditRoom").addEventListener("click", () => dialog.close());
145
148
  $("#btnCancelEditRoom").addEventListener("click", () => dialog.close());
146
149
  dialog.addEventListener("close", () => {
@@ -1,4 +1,5 @@
1
1
  import { LS } from "./state.js";
2
+ import { closeOnBackdrop } from "./panels.js";
2
3
  export function initAnnouncements(app) {
3
4
  const $ = (selector) => {
4
5
  const node = app.$(selector);
@@ -265,6 +266,8 @@ export function initAnnouncements(app) {
265
266
  openSurface();
266
267
  });
267
268
  $("#btnCloseAnnouncements").addEventListener("click", () => closeSurface());
269
+ // The announcement list is a list, so a backdrop click closes it; the editor stays.
270
+ closeOnBackdrop(surface, () => closeSurface());
268
271
  surface.addEventListener("cancel", (event) => { event.preventDefault(); closeSurface(); });
269
272
  surface.addEventListener("close", () => {
270
273
  if (pendingReopen) {
@@ -27,8 +27,8 @@ export function initAttachments(app) {
27
27
  // crypto.randomUUID needs a secure context; the chat also runs on plain-HTTP LANs.
28
28
  function newUploadID() {
29
29
  const bytes = crypto.getRandomValues(new Uint8Array(16));
30
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
31
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
30
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
31
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
32
32
  const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
33
33
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
34
34
  }
@@ -234,7 +234,7 @@ export function initAttachments(app) {
234
234
  if (roomId() === id)
235
235
  render();
236
236
  };
237
- app.completeAttachmentsFromText = (id, text) => app.completeAttachments?.(id, [...String(text).matchAll(/\[\[resource:([\da-f-]{36})\]\]/gi)].map((match) => match[1]));
237
+ app.completeAttachmentsFromText = (id, text) => app.completeAttachments?.(id, [...String(text).matchAll(/\[\[resource:([\da-f-]{36})\]\]/gi)].map((match) => match[1] ?? ""));
238
238
  const applyLocale = app.applyLocale;
239
239
  app.applyLocale = () => { applyLocale(); updateLocale(); };
240
240
  function updateLocale() {
@@ -3,7 +3,7 @@
3
3
  const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
4
4
  export async function copyTextToClipboard(text, mentionSource = false) {
5
5
  // The HTML marker lets a later paste rebuild mention chips; unmarked external text stays literal.
6
- const html = mentionSource ? `<div data-chatroom-mentions>${String(text).replace(/[&<>"]/g, (char) => ESCAPES[char])}</div>` : "";
6
+ const html = mentionSource ? `<div data-chatroom-mentions>${String(text).replace(/[&<>"]/g, (char) => ESCAPES[char] ?? char)}</div>` : "";
7
7
  try {
8
8
  if (html && navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
9
9
  await navigator.clipboard.write([new ClipboardItem({ "text/plain": new Blob([text], { type: "text/plain" }), "text/html": new Blob([html], { type: "text/html" }) })]);
@@ -25,7 +25,7 @@ export function setCopyFeedback(button, app, copied) {
25
25
  feedback.textContent = app.t(key);
26
26
  button.setAttribute("aria-label", app.t(key));
27
27
  button.title = app.t(key);
28
- button._copyFeedbackTimer = setTimeout(() => {
28
+ button._copyFeedbackTimer = window.setTimeout(() => {
29
29
  button.classList.remove("is-copied", "is-copy-failed");
30
30
  button.setAttribute("aria-label", app.t("copyMessage"));
31
31
  button.title = app.t("copyMessage");
@@ -242,7 +242,7 @@ export function initDocPreview(app) {
242
242
  if (width < 200 || Math.abs(width - pptxWidth) < 8)
243
243
  return;
244
244
  clearTimeout(pptxTimer);
245
- pptxTimer = setTimeout(() => {
245
+ pptxTimer = window.setTimeout(() => {
246
246
  if (dialog.open && officeKind === "pptx" && blob) {
247
247
  void renderOfficeDocument("pptx", blob, token, width).catch(() => undefined);
248
248
  }
@@ -15,7 +15,7 @@ export function editorText(editor, draft = false) {
15
15
  if (editor.childNodes.length === 1 && editor.firstChild?.nodeName === "DIV" && editor.firstElementChild?.nodeName === "BR")
16
16
  return "";
17
17
  let value = "";
18
- const block = (node) => node.nodeName === "DIV";
18
+ const block = (node) => node?.nodeName === "DIV";
19
19
  const walk = (node) => {
20
20
  if (node.nodeType === Node.TEXT_NODE)
21
21
  value += draft ? encodeDraftText(node.nodeValue ?? "") : node.nodeValue ?? "";
@@ -80,7 +80,7 @@ export function setEditorText(editor, value, draft = false) {
80
80
  offset = pattern.lastIndex;
81
81
  continue;
82
82
  }
83
- editor.append(createMention(editor, draft ? match[2] : match[1]));
83
+ editor.append(createMention(editor, (draft ? match[2] : match[1]) ?? ""));
84
84
  offset = pattern.lastIndex;
85
85
  }
86
86
  appendText(editor, String(value).slice(offset));
@@ -113,7 +113,7 @@ export function editorSelectionOffsets(editor) {
113
113
  return [offset(selected.startContainer, selected.startOffset, true), offset(selected.endContainer, selected.endOffset, false)];
114
114
  }
115
115
  function lengthBefore(root, target, position) {
116
- const block = (node) => node.nodeName === "DIV";
116
+ const block = (node) => node?.nodeName === "DIV";
117
117
  const length = (node) => {
118
118
  if (node instanceof Text)
119
119
  return node.length;
@@ -128,6 +128,8 @@ function lengthBefore(root, target, position) {
128
128
  let sum = 0;
129
129
  for (let index = 0; index < until; index++) {
130
130
  const child = parent.childNodes[index];
131
+ if (!child)
132
+ break;
131
133
  if (index && (block(child) || block(parent.childNodes[index - 1])))
132
134
  sum++;
133
135
  if (!(block(child) && child.childNodes.length === 1 && child.firstChild?.nodeName === "BR"))
@@ -142,6 +144,8 @@ function lengthBefore(root, target, position) {
142
144
  let total = 0;
143
145
  for (let index = 0; index < node.childNodes.length; index++) {
144
146
  const child = node.childNodes[index];
147
+ if (!child)
148
+ break;
145
149
  if (index && (block(child) || block(node.childNodes[index - 1])))
146
150
  total++;
147
151
  if (child === target || child.contains(target))
@@ -208,7 +212,7 @@ function editorPoint(editor, offset) {
208
212
  }
209
213
  return [editor, editor.childNodes.length - 1];
210
214
  }
211
- const block = (node) => node.nodeName === "DIV";
215
+ const block = (node) => node?.nodeName === "DIV";
212
216
  let left = offset, point = null;
213
217
  const visit = (node) => {
214
218
  if (point)
@@ -273,9 +277,9 @@ export function replaceEditorRange(editor, start, end, value, parseMentions = tr
273
277
  let html = "", cursor = 0, match;
274
278
  while (token && (match = token.exec(content))) {
275
279
  html += textHTML(content.slice(cursor, match.index));
276
- const name = escapeHTML(match[1]), label = escapeHTML(chipLabel(editor, match[1]));
280
+ const mention = match[1] ?? "", name = escapeHTML(mention), label = escapeHTML(chipLabel(editor, mention));
277
281
  const chipID = createRandomId();
278
- trustedChipNames.set(chipID, match[1]);
282
+ trustedChipNames.set(chipID, mention);
279
283
  html += `<span class="editor-mention" data-mention="${name}" data-chat-chip="${chipID}" data-insert-marker="${marker}" contenteditable="false" role="img" aria-label="Mention ${label}">@${label}</span>`;
280
284
  cursor = token.lastIndex;
281
285
  }
@@ -332,7 +336,7 @@ function knownMentions(editor, text) {
332
336
  return text.replace(/<at>@([^<]+)<\/at>/g, (token, name) => editor.isKnownMention && !editor.isKnownMention(name) ? `@${name}` : token);
333
337
  }
334
338
  const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
335
- function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]); }
339
+ function escapeHTML(text) { return String(text).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char); }
336
340
  function textHTML(text) { return escapeHTML(text).replace(/\r\n|\r|\n/g, "<br>"); }
337
341
  function createMention(editor, name) {
338
342
  const chip = document.createElement("span"), label = chipLabel(editor, name);
@@ -188,7 +188,7 @@ export function initEvents(app) {
188
188
  backdrop.hidden = true;
189
189
  return;
190
190
  }
191
- backdropTimer = setTimeout(() => { backdrop.hidden = true; }, 200);
191
+ backdropTimer = window.setTimeout(() => { backdrop.hidden = true; }, 200);
192
192
  }
193
193
  function syncRoomDrawer() {
194
194
  // Crossing the drawer breakpoint jumps straight to the target layout instead
@@ -198,7 +198,7 @@ export function initEvents(app) {
198
198
  drawerWasSmall = small;
199
199
  roomRail.classList.add("no-drawer-animation");
200
200
  clearTimeout(drawerAnimationTimer);
201
- drawerAnimationTimer = setTimeout(() => roomRail.classList.remove("no-drawer-animation"), 260);
201
+ drawerAnimationTimer = window.setTimeout(() => roomRail.classList.remove("no-drawer-animation"), 260);
202
202
  }
203
203
  if (!small) {
204
204
  roomRail.classList.remove("drawer-open");
@@ -225,7 +225,7 @@ export function initEvents(app) {
225
225
  app.state.receiptObservationFrame = 0;
226
226
  app.state.receiptObservation = null;
227
227
  clearTimeout(resizeResetTimer);
228
- resizeResetTimer = setTimeout(() => { if (generation === resizeGeneration)
228
+ resizeResetTimer = window.setTimeout(() => { if (generation === resizeGeneration)
229
229
  app.state.resizeScrollAdjusting = false; }, 500);
230
230
  if (resizeFrame)
231
231
  cancelAnimationFrame(resizeFrame);
@@ -500,7 +500,7 @@ export function initEvents(app) {
500
500
  selectedChips.forEach((chip) => chip.replaceWith(document.createTextNode(`<at>@${chip.dataset.mention ?? chip.textContent?.slice(1) ?? ""}</at>`)));
501
501
  const text = fragment.textContent ?? "";
502
502
  const escapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
503
- const html = `<div data-chatroom-mentions>${text.replace(/[&<>"]/g, (char) => escapes[char])}</div>`;
503
+ const html = `<div data-chatroom-mentions>${text.replace(/[&<>"]/g, (char) => escapes[char] ?? char)}</div>`;
504
504
  event.clipboardData?.setData("text/plain", text);
505
505
  event.clipboardData?.setData("text/html", html);
506
506
  event.preventDefault();
@@ -663,7 +663,9 @@ function handleMessageKey(event, app) {
663
663
  if (event.key === "Enter" || event.key === "Tab") {
664
664
  if (app.mention?.items.length) {
665
665
  event.preventDefault();
666
- app.insertMention(app.mention.items[app.mention.index]);
666
+ const item = app.mention.items[app.mention.index];
667
+ if (item)
668
+ app.insertMention(item);
667
669
  return;
668
670
  }
669
671
  app.closeMention();
@@ -3,6 +3,7 @@ import { isRoomAdmin } from "./admin-badge.js";
3
3
  import { icon } from "./icons.js";
4
4
  import { docPreviewFormat, isDocPreviewResource, OFFICE_KINDS, TEXT_PREVIEW_LIMIT } from "./resource-format.js";
5
5
  import { createCopyButton, copyResourceText } from "./copy-action.js";
6
+ import { closeOnBackdrop } from "./panels.js";
6
7
  const PAGE_SIZE = 500;
7
8
  const UNKNOWN_UPLOADER = "__unknown_uploader__";
8
9
  const ICONS = {
@@ -321,7 +322,8 @@ export function initFiles(app) {
321
322
  summary.textContent = app.t("filesLoading");
322
323
  try {
323
324
  const offset = reset ? 0 : items.length;
324
- const before = !reset && items.length ? `&before=${encodeURIComponent(items[items.length - 1].id)}` : "";
325
+ const lastItem = items.at(-1);
326
+ const before = !reset && lastItem ? `&before=${encodeURIComponent(lastItem.id)}` : "";
325
327
  const page = await app.api(`/rooms/${encodeURIComponent(room.id)}/resources?limit=${PAGE_SIZE}&offset=${offset}${before}`, {
326
328
  headers: { "x-session-id": LS.sessionID },
327
329
  });
@@ -423,6 +425,8 @@ export function initFiles(app) {
423
425
  };
424
426
  trigger?.addEventListener("click", () => { app.closePanels(); open(); });
425
427
  $("#btnCloseFiles")?.addEventListener("click", () => close());
428
+ // The file browser is a list, so a backdrop click dismisses it; pane mode has no backdrop.
429
+ closeOnBackdrop(dialog, () => close());
426
430
  document.addEventListener("keydown", (event) => {
427
431
  if (event.key !== "Escape" || event.altKey || !dialog.open || !dialog.classList.contains("is-pane"))
428
432
  return;