@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
package/src/tui/app.mjs CHANGED
@@ -12,436 +12,487 @@ import { canonicalizeMentions } from "./mentions.mjs";
12
12
  import { mergeMessages, messageStamp, oldestSeq } from "./messages.mjs";
13
13
  import { normalizeLanguage, setLanguage, t } from "./i18n.mjs";
14
14
  import { normalizeTheme } from "./prefs.mjs";
15
-
16
15
  const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];
17
-
16
+ const FIRST_BACKOFF = BACKOFF_MS[0] ?? 1000;
17
+ const MAX_BACKOFF = BACKOFF_MS.at(-1) ?? 15000;
18
+ const joinStatusOf = (result) => typeof result === "string" ? result
19
+ : result !== null && typeof result === "object" && "status" in result ? result.status : undefined;
18
20
  const errorText = (error) => (error instanceof Error ? error.message : String(error ?? "unknown error"));
19
-
20
21
  const normalizeRoom = (room) => ({
21
- id: String(room.id ?? ""),
22
- name: String(room.name ?? room.id ?? "room"),
23
- participants: Array.isArray(room.participants) ? room.participants : [],
24
- joined: room.joined === true,
22
+ id: String(room.id ?? ""),
23
+ name: String(room.name ?? room.id ?? "room"),
24
+ participants: Array.isArray(room.participants) ? room.participants : [],
25
+ joined: room.joined === true,
25
26
  });
26
-
27
27
  export class ChatApp {
28
- constructor({ api, sessionID, participant, host = "", autoPoll = true, settings = {}, savePrefs = null, downloadDir = process.cwd(), schedule = (fn, ms) => setTimeout(fn, ms) }) {
29
- this.api = api;
30
- this.sessionID = sessionID;
31
- this.participant = participant;
32
- this.autoPoll = autoPoll;
33
- this.schedule = schedule;
34
- this.savePrefs = typeof savePrefs === "function" ? savePrefs : null;
35
- this.settings = { ...settings };
36
- this.token = this.settings.token ?? "";
37
- delete this.settings.token;
38
- this.prefs = {
39
- language: normalizeLanguage(this.settings.language),
40
- theme: normalizeTheme(this.settings.theme),
41
- participant: this.settings.participant ?? participant,
42
- url: this.settings.server ?? "",
43
- };
44
- setLanguage(this.prefs.language);
45
- this.downloadDir = downloadDir;
46
- this.closed = false;
47
- this.pollToken = 0;
48
- this.timers = new Set();
49
- this.pollAbort = null;
50
- this.cache = new Map();
51
- this.historyCursor = new Map();
52
- this.historyMore = new Map();
53
- this.historyPages = new Map();
54
- this.historyInflight = new Set();
55
- this.listeners = new Set();
56
- this.state = {
57
- host,
58
- participant,
59
- theme: this.prefs.theme,
60
- language: this.prefs.language,
61
- connection: "connecting",
62
- rooms: [],
63
- selected: 0,
64
- current: null,
65
- joined: false,
66
- messages: [],
67
- pending: null,
68
- focus: "rooms",
69
- draft: "",
70
- highlight: null,
71
- help: false,
72
- status: "",
73
- statusKind: "info",
74
- palette: null,
75
- quit: false,
76
- };
77
- }
78
-
79
- subscribe(listener) {
80
- this.listeners.add(listener);
81
- return () => this.listeners.delete(listener);
82
- }
83
-
84
- touch() {
85
- for (const listener of this.listeners) listener(this.state);
86
- }
87
-
88
- later(fn, ms) {
89
- if (this.closed) return undefined;
90
- let timer;
91
- const run = () => {
92
- if (timer !== undefined) this.timers.delete(timer);
93
- return fn();
94
- };
95
- timer = this.schedule(run, ms);
96
- if (timer !== undefined) this.timers.add(timer);
97
- return timer;
98
- }
99
-
100
- setStatus(text, kind = "info") {
101
- this.state.status = text;
102
- this.state.statusKind = kind;
103
- this.touch();
104
- }
105
-
106
- async init() {
107
- await this.refreshRooms(true);
108
- }
109
-
110
- async refreshRooms(quiet = false) {
111
- try {
112
- const list = await this.api.listRooms(this.sessionID);
113
- const rooms = (Array.isArray(list) ? list : []).map(normalizeRoom);
114
- const selectedID = this.state.rooms[this.state.selected]?.id;
115
- this.state.rooms = rooms;
116
- const found = selectedID ? rooms.findIndex((room) => room.id === selectedID) : -1;
117
- this.state.selected = found >= 0 ? found : Math.min(this.state.selected, Math.max(0, rooms.length - 1));
118
- this.state.connection = "online";
119
- if (!quiet) {
120
- this.state.status = t("status.refreshed");
121
- this.state.statusKind = "info";
122
- }
123
- this.touch();
124
- return true;
125
- } catch (error) {
126
- this.state.connection = "offline";
127
- this.state.status = t("status.refreshFailed", { error: errorText(error) });
128
- this.state.statusKind = "error";
129
- this.touch();
130
- return false;
131
- }
132
- }
133
-
134
- isCurrent(roomID) {
135
- return this.state.current?.id === roomID;
136
- }
137
-
138
- async openSelected() {
139
- return this.openRoom(this.state.selected);
140
- }
141
-
142
- async openRoom(indexOrRoom) {
143
- const index = typeof indexOrRoom === "number" ? indexOrRoom : this.state.rooms.indexOf(indexOrRoom);
144
- const summary = this.state.rooms[index];
145
- if (!summary) return;
146
- this.state.selected = index;
147
- this.stopPolling();
148
- this.state.current = { id: summary.id, name: summary.name, participants: summary.participants };
149
- this.state.joined = summary.joined;
150
- this.state.messages = [];
151
- this.state.pending = null;
152
- this.state.highlight = null;
153
- this.state.status = t("status.opening", { name: summary.name });
154
- this.state.statusKind = "info";
155
- this.touch();
156
- if (summary.joined) await this.loadRoom(summary.id);
157
- else await this.joinRoom(summary.id);
158
- }
159
-
160
- async joinRoom(roomID) {
161
- try {
162
- const result = await this.api.join(roomID, this.sessionID, this.participant);
163
- if (!this.isCurrent(roomID)) return;
164
- if (result?.pending) {
165
- const message = String(result.message ?? t("status.joinPending"));
166
- this.state.pending = { roomId: roomID, message };
167
- this.state.joined = false;
168
- this.state.status = message;
28
+ constructor({ api, sessionID, participant, host = "", autoPoll = true, settings = {}, savePrefs = null, downloadDir = process.cwd(), schedule = (fn, ms) => setTimeout(fn, ms) }) {
29
+ this.api = api;
30
+ this.sessionID = sessionID;
31
+ this.participant = participant;
32
+ this.autoPoll = autoPoll;
33
+ this.schedule = schedule;
34
+ this.savePrefs = typeof savePrefs === "function" ? savePrefs : null;
35
+ this.settings = { ...settings };
36
+ this.token = this.settings.token ?? "";
37
+ delete this.settings.token;
38
+ this.prefs = {
39
+ language: normalizeLanguage(this.settings.language),
40
+ theme: normalizeTheme(this.settings.theme),
41
+ participant: this.settings.participant ?? participant,
42
+ url: this.settings.server ?? "",
43
+ };
44
+ setLanguage(this.prefs.language);
45
+ this.downloadDir = downloadDir;
46
+ this.closed = false;
47
+ this.pollToken = 0;
48
+ this.timers = new Set();
49
+ this.pollAbort = null;
50
+ this.cache = new Map();
51
+ this.historyCursor = new Map();
52
+ this.historyMore = new Map();
53
+ this.historyPages = new Map();
54
+ this.historyInflight = new Set();
55
+ this.listeners = new Set();
56
+ this.drafts = new Map();
57
+ this.pendingSends = new Map();
58
+ this.inflightSends = new Set();
59
+ this.state = {
60
+ host,
61
+ participant,
62
+ theme: this.prefs.theme,
63
+ language: this.prefs.language,
64
+ connection: "connecting",
65
+ rooms: [],
66
+ selected: 0,
67
+ current: null,
68
+ joined: false,
69
+ messages: [],
70
+ pending: null,
71
+ focus: "rooms",
72
+ draft: "",
73
+ highlight: null,
74
+ help: false,
75
+ status: "",
76
+ statusKind: "info",
77
+ palette: null,
78
+ quit: false,
79
+ };
80
+ }
81
+ subscribe(listener) {
82
+ this.listeners.add(listener);
83
+ return () => this.listeners.delete(listener);
84
+ }
85
+ touch() {
86
+ for (const listener of this.listeners)
87
+ listener(this.state);
88
+ }
89
+ later(fn, ms) {
90
+ if (this.closed)
91
+ return undefined;
92
+ let timer;
93
+ const run = () => {
94
+ if (timer !== undefined)
95
+ this.timers.delete(timer);
96
+ return fn();
97
+ };
98
+ timer = this.schedule(run, ms);
99
+ if (timer !== undefined)
100
+ this.timers.add(timer);
101
+ return timer;
102
+ }
103
+ setStatus(text, kind = "info") {
104
+ this.state.status = text;
105
+ this.state.statusKind = kind;
106
+ this.touch();
107
+ }
108
+ async init() {
109
+ await this.refreshRooms(true);
110
+ }
111
+ async refreshRooms(quiet = false) {
112
+ try {
113
+ const list = await this.api.listRooms(this.sessionID);
114
+ const rooms = (Array.isArray(list) ? list : []).map(normalizeRoom);
115
+ const selectedID = this.state.rooms[this.state.selected]?.id;
116
+ this.state.rooms = rooms;
117
+ const found = selectedID ? rooms.findIndex((room) => room.id === selectedID) : -1;
118
+ this.state.selected = found >= 0 ? found : Math.min(this.state.selected, Math.max(0, rooms.length - 1));
119
+ this.state.connection = "online";
120
+ if (!quiet) {
121
+ this.state.status = t("status.refreshed");
122
+ this.state.statusKind = "info";
123
+ }
124
+ this.touch();
125
+ return true;
126
+ }
127
+ catch (error) {
128
+ this.state.connection = "offline";
129
+ this.state.status = t("status.refreshFailed", { error: errorText(error) });
130
+ this.state.statusKind = "error";
131
+ this.touch();
132
+ return false;
133
+ }
134
+ }
135
+ isCurrent(roomID) {
136
+ return this.state.current?.id === roomID;
137
+ }
138
+ async openSelected() {
139
+ return this.openRoom(this.state.selected);
140
+ }
141
+ async openRoom(indexOrRoom) {
142
+ const index = typeof indexOrRoom === "number" ? indexOrRoom : this.state.rooms.indexOf(indexOrRoom);
143
+ const summary = this.state.rooms[index];
144
+ if (!summary)
145
+ return;
146
+ const previous = this.state.current;
147
+ if (previous)
148
+ this.drafts.set(previous.id, this.state.draft);
149
+ this.state.selected = index;
150
+ this.stopPolling();
151
+ this.state.current = { id: summary.id, name: summary.name, participants: summary.participants };
152
+ // Restore the destination's draft so unsent text never follows the user.
153
+ // With no current room, prefer the destination's draft and otherwise keep
154
+ // text typed from the room list.
155
+ this.state.draft = this.drafts.get(summary.id)
156
+ ?? (previous ? "" : String(this.state.draft ?? ""));
157
+ this.state.joined = summary.joined;
158
+ this.state.messages = [];
159
+ this.state.pending = null;
160
+ this.state.highlight = null;
161
+ this.state.status = t("status.opening", { name: summary.name });
169
162
  this.state.statusKind = "info";
170
163
  this.touch();
171
- this.later(() => this.checkJoin(roomID), 1500);
172
- return;
173
- }
174
- this.enterRoom(result?.room ?? result, roomID, true);
175
- } catch (error) {
176
- if (this.isCurrent(roomID)) this.setStatus(t("status.joinFailed", { error: errorText(error) }), "error");
177
- }
178
- }
179
-
180
- async checkJoin(roomID) {
181
- if (this.closed || !this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
182
- try {
183
- const result = await this.api.joinStatus(roomID, this.sessionID);
184
- if (!this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
185
- const status = typeof result === "string" ? result : result?.status;
186
- if (status === "joined") {
164
+ if (summary.joined)
165
+ await this.loadRoom(summary.id);
166
+ else
167
+ await this.joinRoom(summary.id);
168
+ }
169
+ async joinRoom(roomID) {
170
+ try {
171
+ const result = await this.api.join(roomID, this.sessionID, this.participant);
172
+ if (!this.isCurrent(roomID))
173
+ return;
174
+ if (result.pending) {
175
+ const message = String(result.message ?? t("status.joinPending"));
176
+ this.state.pending = { roomId: roomID, message };
177
+ this.state.joined = false;
178
+ this.state.status = message;
179
+ this.state.statusKind = "info";
180
+ this.touch();
181
+ this.later(() => this.checkJoin(roomID), 1500);
182
+ return;
183
+ }
184
+ this.enterRoom(result.room, roomID, true);
185
+ }
186
+ catch (error) {
187
+ if (this.isCurrent(roomID))
188
+ this.setStatus(t("status.joinFailed", { error: errorText(error) }), "error");
189
+ }
190
+ }
191
+ async checkJoin(roomID) {
192
+ if (this.closed || !this.isCurrent(roomID) || this.state.pending?.roomId !== roomID)
193
+ return;
194
+ try {
195
+ const status = joinStatusOf(await this.api.joinStatus(roomID, this.sessionID));
196
+ if (!this.isCurrent(roomID) || this.state.pending?.roomId !== roomID)
197
+ return;
198
+ if (status === "joined") {
199
+ this.state.pending = null;
200
+ this.setStatus(t("status.joinApproved"), "success");
201
+ await this.loadRoom(roomID);
202
+ return;
203
+ }
204
+ if (status === "pending") {
205
+ this.later(() => this.checkJoin(roomID), 1500);
206
+ return;
207
+ }
208
+ this.state.pending = null;
209
+ this.setStatus(t("status.joinStale"), "error");
210
+ }
211
+ catch {
212
+ this.later(() => this.checkJoin(roomID), 1500);
213
+ }
214
+ }
215
+ async loadRoom(roomID) {
216
+ try {
217
+ const room = await this.api.getRoom(roomID);
218
+ if (!this.isCurrent(roomID) || !room)
219
+ return;
220
+ if (room.joined === false) {
221
+ this.notJoined(roomID, t("status.notMember"));
222
+ return;
223
+ }
224
+ this.enterRoom(room, roomID, false);
225
+ }
226
+ catch (error) {
227
+ if (this.isCurrent(roomID))
228
+ this.setStatus(t("status.openFailed", { error: errorText(error) }), "error");
229
+ }
230
+ }
231
+ enterRoom(room, roomID, joinedNow) {
232
+ if (!room || typeof room !== "object") {
233
+ this.setStatus(t("status.roomMissing"), "error");
234
+ return;
235
+ }
236
+ const summary = this.state.rooms.find((item) => item.id === roomID);
237
+ if (summary) {
238
+ summary.joined = true;
239
+ summary.name = String(room.name ?? summary.name);
240
+ if (Array.isArray(room.participants))
241
+ summary.participants = room.participants;
242
+ }
243
+ const cache = this.historyList(roomID);
244
+ mergeMessages(cache, room.messages);
245
+ this.state.current = {
246
+ id: roomID,
247
+ name: String(room.name ?? summary?.name ?? roomID),
248
+ participants: Array.isArray(room.participants) ? room.participants : summary?.participants ?? [],
249
+ };
250
+ this.state.joined = true;
187
251
  this.state.pending = null;
188
- this.setStatus(t("status.joinApproved"), "success");
189
- await this.loadRoom(roomID);
190
- return;
191
- }
192
- if (status === "pending") {
193
- this.later(() => this.checkJoin(roomID), 1500);
194
- return;
195
- }
196
- this.state.pending = null;
197
- this.setStatus(t("status.joinStale"), "error");
198
- } catch {
199
- this.later(() => this.checkJoin(roomID), 1500);
200
- }
201
- }
202
-
203
- async loadRoom(roomID) {
204
- try {
205
- const room = await this.api.getRoom(roomID);
206
- if (!this.isCurrent(roomID) || !room) return;
207
- if (room.joined === false) {
208
- this.notJoined(roomID, t("status.notMember"));
209
- return;
210
- }
211
- this.enterRoom(room, roomID, false);
212
- } catch (error) {
213
- if (this.isCurrent(roomID)) this.setStatus(t("status.openFailed", { error: errorText(error) }), "error");
214
- }
215
- }
216
-
217
- enterRoom(room, roomID, joinedNow) {
218
- if (!room || typeof room !== "object") {
219
- this.setStatus(t("status.roomMissing"), "error");
220
- return;
221
- }
222
- const summary = this.state.rooms.find((item) => item.id === roomID);
223
- if (summary) {
224
- summary.joined = true;
225
- summary.name = String(room.name ?? summary.name);
226
- if (Array.isArray(room.participants)) summary.participants = room.participants;
227
- }
228
- const cache = this.historyList(roomID);
229
- mergeMessages(cache, room.messages);
230
- this.state.current = {
231
- id: roomID,
232
- name: String(room.name ?? summary?.name ?? roomID),
233
- participants: Array.isArray(room.participants) ? room.participants : summary?.participants ?? [],
234
- };
235
- this.state.joined = true;
236
- this.state.pending = null;
237
- this.state.messages = cache;
238
- this.state.connection = "online";
239
- this.state.status = joinedNow ? t("status.joined", { name: this.state.current.name }) : "";
240
- this.state.statusKind = "success";
241
- if (typeof room.hasMore === "boolean") this.historyMore.set(roomID, room.hasMore);
242
- const oldest = oldestSeq(cache);
243
- if (oldest !== undefined) this.historyCursor.set(roomID, oldest);
244
- this.touch();
245
- this.markRead();
246
- if (this.autoPoll) this.startPolling();
247
- }
248
-
249
- historyList(roomID) {
250
- let list = this.cache.get(roomID);
251
- if (!list) {
252
- list = [];
253
- this.cache.set(roomID, list);
254
- }
255
- return list;
256
- }
257
-
258
- merge(items) {
259
- mergeMessages(this.state.messages, items);
260
- }
261
-
262
- lastTs() {
263
- return this.state.messages.reduce((max, message) => Math.max(max, messageStamp(message)), 0);
264
- }
265
-
266
- async pollOnce() {
267
- const room = this.state.current;
268
- if (!room || !this.state.joined) return false;
269
- const roomID = room.id;
270
- const controller = typeof AbortController === "function" ? new AbortController() : null;
271
- this.pollAbort = controller;
272
- try {
273
- const result = await this.api.poll(
274
- roomID,
275
- this.sessionID,
276
- this.lastTs(),
277
- controller ? { signal: controller.signal } : undefined,
278
- );
279
- if (!this.isCurrent(roomID)) return false;
280
- if (!result || result.member === false) {
281
- this.notJoined(roomID, t("status.memberLost"));
282
- return false;
283
- }
284
- const wasOffline = this.state.connection !== "online";
285
- this.merge(result.items);
286
- this.state.connection = "online";
287
- if (wasOffline) {
288
- this.state.status = t("status.reconnected");
252
+ this.state.messages = cache;
253
+ this.state.connection = "online";
254
+ this.state.status = joinedNow ? t("status.joined", { name: this.state.current.name }) : "";
289
255
  this.state.statusKind = "success";
290
- }
291
- this.touch();
292
- this.markRead();
293
- return true;
294
- } catch (error) {
295
- if (controller?.signal.aborted) return false;
296
- this.state.connection = "reconnecting";
297
- this.state.status = t("status.connectionLost", { error: errorText(error) });
298
- this.state.statusKind = "error";
299
- this.touch();
300
- return false;
301
- } finally {
302
- if (this.pollAbort === controller) this.pollAbort = null;
303
- }
304
- }
305
-
306
- startPolling() {
307
- const token = ++this.pollToken;
308
- let delay = 0;
309
- const step = async () => {
310
- if (this.closed || token !== this.pollToken || !this.state.joined) return;
311
- const ok = await this.pollOnce();
312
- if (this.closed || token !== this.pollToken || !this.state.joined) return;
313
- delay = ok ? 0 : Math.min(delay ? delay * 2 : BACKOFF_MS[0], BACKOFF_MS.at(-1));
314
- this.later(step, delay);
315
- };
316
- step();
317
- }
318
-
319
- stopPolling() {
320
- this.pollToken += 1;
321
- this.pollAbort?.abort();
322
- }
323
-
324
- notJoined(roomID, message) {
325
- if (!this.isCurrent(roomID)) return;
326
- this.state.joined = false;
327
- const summary = this.state.rooms.find((room) => room.id === roomID);
328
- if (summary) summary.joined = false;
329
- this.setStatus(message, "error");
330
- }
331
-
332
- markRead() {
333
- const room = this.state.current;
334
- const newest = this.lastTs();
335
- if (!room || !newest) return;
336
- try {
337
- const result = this.api.markRead?.(room.id, this.sessionID, newest);
338
- if (result && typeof result.catch === "function") result.catch(() => {});
339
- } catch {
340
- // A read receipt failure must not interrupt the UI.
341
- }
342
- }
343
-
344
- async send() {
345
- const raw = String(this.state.draft ?? "").trim();
346
- if (!raw) return;
347
- const room = this.state.current;
348
- if (!room || !this.state.joined) {
349
- this.setStatus(t("status.joinBeforeSend"), "error");
350
- return;
351
- }
352
- const text = canonicalizeMentions(raw, room.participants);
353
- // Reuse the attempt's id when the same failed text is sent again, so a lost
354
- // response cannot produce two messages.
355
- const attempt = this.pendingSend && this.pendingSend.text === raw
356
- ? this.pendingSend
357
- : { text: raw, clientMessageID: globalThis.crypto.randomUUID() };
358
- this.pendingSend = attempt;
359
- this.state.draft = "";
360
- this.touch();
361
- try {
362
- const result = await this.api.send(room.id, this.sessionID, text, { clientMessageID: attempt.clientMessageID });
363
- if (!this.isCurrent(room.id)) return;
364
- this.pendingSend = null;
365
- if (Array.isArray(result?.messages)) this.merge(result.messages);
366
- else if (result?.id) this.merge([result]);
367
- this.state.highlight = null;
368
- this.state.connection = "online";
369
- this.setStatus(t("status.sent"), "success");
370
- this.markRead();
371
- } catch (error) {
372
- // Keep text typed while the request was in flight; dropping it loses work.
373
- this.state.draft = this.state.draft ? `${raw}\n${this.state.draft}` : raw;
374
- this.setStatus(t("status.sendFailed", { error: errorText(error) }), "error");
375
- }
376
- }
377
-
378
- setDraft(text) {
379
- this.state.draft = String(text ?? "");
380
- }
381
-
382
- appendDraft(text) {
383
- this.state.draft += String(text ?? "");
384
- this.state.focus = "composer";
385
- this.state.help = false;
386
- this.touch();
387
- }
388
-
389
- moveSelection(delta) {
390
- if (!this.state.rooms.length) return;
391
- this.state.selected = Math.min(
392
- this.state.rooms.length - 1,
393
- Math.max(0, this.state.selected + delta),
394
- );
395
- this.state.highlight = null;
396
- this.touch();
397
- }
398
-
399
- selectRoom(index) {
400
- if (!this.state.rooms[index]) return;
401
- this.state.selected = index;
402
- this.state.highlight = null;
403
- this.touch();
404
- }
405
-
406
- toggleFocus() {
407
- this.state.focus = this.state.focus === "rooms" ? "composer" : "rooms";
408
- if (this.state.focus === "composer") this.state.help = false;
409
- this.touch();
410
- }
411
-
412
- toggleHelp() {
413
- this.state.help = !this.state.help;
414
- this.touch();
415
- }
416
-
417
- clearOrBlur() {
418
- this.state.draft = "";
419
- this.state.focus = "rooms";
420
- this.state.highlight = null;
421
- this.touch();
422
- }
423
-
424
- clearHighlight() {
425
- if (!this.state.highlight) return;
426
- this.state.highlight = null;
427
- this.touch();
428
- }
429
-
430
- quit() {
431
- this.state.quit = true;
432
- this.close();
433
- this.touch();
434
- }
435
-
436
- close() {
437
- this.closed = true;
438
- this.pollToken += 1;
439
- this.pollAbort?.abort();
440
- for (const timer of this.timers) clearTimeout(timer);
441
- this.timers.clear();
442
- }
256
+ if (typeof room.hasMore === "boolean")
257
+ this.historyMore.set(roomID, room.hasMore);
258
+ const oldest = oldestSeq(cache);
259
+ if (oldest !== undefined)
260
+ this.historyCursor.set(roomID, oldest);
261
+ this.touch();
262
+ this.markRead();
263
+ if (this.autoPoll)
264
+ this.startPolling();
265
+ }
266
+ historyList(roomID) {
267
+ let list = this.cache.get(roomID);
268
+ if (!list) {
269
+ list = [];
270
+ this.cache.set(roomID, list);
271
+ }
272
+ return list;
273
+ }
274
+ merge(items) {
275
+ mergeMessages(this.state.messages, items);
276
+ }
277
+ lastTs() {
278
+ return this.state.messages.reduce((max, message) => Math.max(max, messageStamp(message)), 0);
279
+ }
280
+ async pollOnce() {
281
+ const room = this.state.current;
282
+ if (!room || !this.state.joined)
283
+ return false;
284
+ const roomID = room.id;
285
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
286
+ this.pollAbort = controller;
287
+ try {
288
+ const result = await this.api.poll(roomID, this.sessionID, this.lastTs(), controller ? { signal: controller.signal } : undefined);
289
+ if (!this.isCurrent(roomID))
290
+ return false;
291
+ if (result === null)
292
+ throw new Error("Invalid inbox response");
293
+ if (result.member === false) {
294
+ this.notJoined(roomID, t("status.memberLost"));
295
+ return false;
296
+ }
297
+ const wasOffline = this.state.connection !== "online";
298
+ this.merge(result.items);
299
+ this.state.connection = "online";
300
+ if (wasOffline) {
301
+ this.state.status = t("status.reconnected");
302
+ this.state.statusKind = "success";
303
+ }
304
+ this.touch();
305
+ this.markRead();
306
+ return true;
307
+ }
308
+ catch (error) {
309
+ if (controller?.signal.aborted)
310
+ return false;
311
+ this.state.connection = "reconnecting";
312
+ this.state.status = t("status.connectionLost", { error: errorText(error) });
313
+ this.state.statusKind = "error";
314
+ this.touch();
315
+ return false;
316
+ }
317
+ finally {
318
+ if (this.pollAbort === controller)
319
+ this.pollAbort = null;
320
+ }
321
+ }
322
+ startPolling() {
323
+ const token = ++this.pollToken;
324
+ let delay = 0;
325
+ const step = async () => {
326
+ if (this.closed || token !== this.pollToken || !this.state.joined)
327
+ return;
328
+ const ok = await this.pollOnce();
329
+ if (this.closed || token !== this.pollToken || !this.state.joined)
330
+ return;
331
+ delay = ok ? 0 : Math.min(delay ? delay * 2 : FIRST_BACKOFF, MAX_BACKOFF);
332
+ this.later(step, delay);
333
+ };
334
+ void step();
335
+ }
336
+ stopPolling() {
337
+ this.pollToken += 1;
338
+ this.pollAbort?.abort();
339
+ }
340
+ notJoined(roomID, message) {
341
+ if (!this.isCurrent(roomID))
342
+ return;
343
+ this.state.joined = false;
344
+ const summary = this.state.rooms.find((room) => room.id === roomID);
345
+ if (summary)
346
+ summary.joined = false;
347
+ this.setStatus(message, "error");
348
+ }
349
+ markRead() {
350
+ const room = this.state.current;
351
+ const newest = this.lastTs();
352
+ if (!room || !newest)
353
+ return;
354
+ try {
355
+ const result = this.api.markRead?.(room.id, this.sessionID, newest);
356
+ if (result && typeof result.catch === "function")
357
+ result.catch(() => { });
358
+ }
359
+ catch {
360
+ // A read receipt failure must not interrupt the UI.
361
+ }
362
+ }
363
+ async send() {
364
+ const raw = String(this.state.draft ?? "").trim();
365
+ if (!raw)
366
+ return;
367
+ const room = this.state.current;
368
+ if (!room || !this.state.joined) {
369
+ this.setStatus(t("status.joinBeforeSend"), "error");
370
+ return;
371
+ }
372
+ // One unresolved send per room: a second trigger must leave its draft alone.
373
+ if (this.inflightSends.has(room.id))
374
+ return;
375
+ const text = canonicalizeMentions(raw, room.participants);
376
+ // Reuse the attempt's id when the same failed text is sent again, so a lost
377
+ // response cannot produce two messages. Attempts are keyed by room so a
378
+ // failure in one room cannot seed an id in another.
379
+ const attempt = this.pendingSends.get(room.id);
380
+ const pending = attempt && attempt.text === raw
381
+ ? attempt
382
+ : { text: raw, clientMessageID: globalThis.crypto.randomUUID() };
383
+ this.pendingSends.set(room.id, pending);
384
+ this.inflightSends.add(room.id);
385
+ this.state.draft = "";
386
+ this.drafts.set(room.id, "");
387
+ this.touch();
388
+ try {
389
+ const result = await this.api.send(room.id, this.sessionID, text, { clientMessageID: pending.clientMessageID });
390
+ // The room may have been deleted while the request was in flight.
391
+ if (this.pendingSends.get(room.id) !== pending)
392
+ return;
393
+ this.pendingSends.delete(room.id);
394
+ if (!this.isCurrent(room.id)) {
395
+ // A late success belongs to its room's cache, not the visible room.
396
+ const cache = this.historyList(room.id);
397
+ if (Array.isArray(result?.messages))
398
+ mergeMessages(cache, result.messages);
399
+ else if (result?.id)
400
+ mergeMessages(cache, [result]);
401
+ return;
402
+ }
403
+ if (Array.isArray(result?.messages))
404
+ this.merge(result.messages);
405
+ else if (result?.id)
406
+ this.merge([result]);
407
+ this.state.highlight = null;
408
+ this.state.connection = "online";
409
+ this.setStatus(t("status.sent"), "success");
410
+ this.markRead();
411
+ }
412
+ catch (error) {
413
+ // The room may have been deleted while the request was in flight.
414
+ if (this.pendingSends.get(room.id) !== pending)
415
+ return;
416
+ // Keep text typed while the request was in flight; it belongs to the
417
+ // sending room, so a late failure cannot edit another room's draft.
418
+ const typed = this.drafts.get(room.id) ?? "";
419
+ const restored = typed ? `${raw}\n${typed}` : raw;
420
+ this.drafts.set(room.id, restored);
421
+ if (this.isCurrent(room.id)) {
422
+ this.state.draft = restored;
423
+ this.setStatus(t("status.sendFailed", { error: errorText(error) }), "error");
424
+ }
425
+ }
426
+ finally {
427
+ this.inflightSends.delete(room.id);
428
+ }
429
+ }
430
+ rememberDraft() {
431
+ if (this.state.current)
432
+ this.drafts.set(this.state.current.id, this.state.draft);
433
+ }
434
+ setDraft(text) {
435
+ this.state.draft = String(text ?? "");
436
+ this.rememberDraft();
437
+ }
438
+ appendDraft(text) {
439
+ this.state.draft += String(text ?? "");
440
+ this.rememberDraft();
441
+ this.state.focus = "composer";
442
+ this.state.help = false;
443
+ this.touch();
444
+ }
445
+ moveSelection(delta) {
446
+ if (!this.state.rooms.length)
447
+ return;
448
+ this.state.selected = Math.min(this.state.rooms.length - 1, Math.max(0, this.state.selected + delta));
449
+ this.state.highlight = null;
450
+ this.touch();
451
+ }
452
+ selectRoom(index) {
453
+ if (!this.state.rooms[index])
454
+ return;
455
+ this.state.selected = index;
456
+ this.state.highlight = null;
457
+ this.touch();
458
+ }
459
+ toggleFocus() {
460
+ this.state.focus = this.state.focus === "rooms" ? "composer" : "rooms";
461
+ if (this.state.focus === "composer")
462
+ this.state.help = false;
463
+ this.touch();
464
+ }
465
+ toggleHelp() {
466
+ this.state.help = !this.state.help;
467
+ this.touch();
468
+ }
469
+ clearOrBlur() {
470
+ this.state.draft = "";
471
+ this.rememberDraft();
472
+ this.state.focus = "rooms";
473
+ this.state.highlight = null;
474
+ this.touch();
475
+ }
476
+ clearHighlight() {
477
+ if (!this.state.highlight)
478
+ return;
479
+ this.state.highlight = null;
480
+ this.touch();
481
+ }
482
+ quit() {
483
+ this.state.quit = true;
484
+ this.close();
485
+ this.touch();
486
+ }
487
+ close() {
488
+ this.closed = true;
489
+ this.pollToken += 1;
490
+ this.pollAbort?.abort();
491
+ for (const timer of this.timers)
492
+ clearTimeout(timer);
493
+ this.timers.clear();
494
+ }
443
495
  }
444
-
445
496
  attachPalette(ChatApp);
446
497
  attachInfo(ChatApp);
447
498
  attachSettings(ChatApp);
@@ -449,7 +500,6 @@ attachReminders(ChatApp);
449
500
  attachRoomSettings(ChatApp);
450
501
  attachMessageActions(ChatApp);
451
502
  attachJoinRequests(ChatApp);
452
-
453
503
  export function createApp(options) {
454
- return new ChatApp(options);
455
- }
504
+ return new ChatApp(options);
505
+ }