@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
@@ -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();
@@ -541,6 +541,8 @@ export function initEvents(app) {
541
541
  app.closePanels();
542
542
  });
543
543
  let lastEscapeAt = -Infinity;
544
+ // A panel that closes on Escape can count as the first press; the next one focuses.
545
+ document.addEventListener("chat-overlay-escaped", () => { lastEscapeAt = performance.now(); });
544
546
  document.addEventListener("keydown", (event) => {
545
547
  if (event.key === "Escape" && !event.repeat && !event.defaultPrevented
546
548
  && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
@@ -591,7 +593,10 @@ export function initEvents(app) {
591
593
  // Same switch as a rail row click on a joined room, in the order the rail renders.
592
594
  const joined = (app.state.availableRooms || []).filter((room) => app.state.rooms.has(room.id));
593
595
  const index = joined.findIndex((room) => room.id === app.state.room?.id);
594
- if (event.defaultPrevented || joined.length < 2 || index < 0 || document.querySelector("dialog[open]"))
596
+ // The read-only announcements list must not eat room switching; editors,
597
+ // confirmations, and prompts still do.
598
+ const blocking = Array.from(document.querySelectorAll("dialog[open]")).some((dialog) => dialog.id !== "announcementsDialog");
599
+ if (event.defaultPrevented || joined.length < 2 || index < 0 || blocking)
595
600
  return;
596
601
  event.preventDefault();
597
602
  const step = event.key === "ArrowDown" ? 1 : -1;
@@ -663,7 +668,9 @@ function handleMessageKey(event, app) {
663
668
  if (event.key === "Enter" || event.key === "Tab") {
664
669
  if (app.mention?.items.length) {
665
670
  event.preventDefault();
666
- app.insertMention(app.mention.items[app.mention.index]);
671
+ const item = app.mention.items[app.mention.index];
672
+ if (item)
673
+ app.insertMention(item);
667
674
  return;
668
675
  }
669
676
  app.closeMention();
@@ -3,6 +3,8 @@ 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";
7
+ import { waitForRefresh } from "./refresh-timing.js";
6
8
  const PAGE_SIZE = 500;
7
9
  const UNKNOWN_UPLOADER = "__unknown_uploader__";
8
10
  const ICONS = {
@@ -281,12 +283,14 @@ export function initFiles(app) {
281
283
  closePreview();
282
284
  rebuildUploaders();
283
285
  const visible = visibleItems();
284
- list.textContent = "";
286
+ const fragment = document.createDocumentFragment();
285
287
  visible.forEach((resource, index) => {
286
288
  const row = buildRow(resource);
287
289
  row.style.setProperty("--file-i", String(Math.min(index, 9)));
288
- list.append(row);
290
+ fragment.append(row);
289
291
  });
292
+ // One atomic commit: a refresh swaps the whole list in a single reflow.
293
+ list.replaceChildren(fragment);
290
294
  empty.hidden = visible.length > 0;
291
295
  if (!visible.length)
292
296
  app.setText(empty, items.length ? "filesEmptyFiltered" : "filesEmpty");
@@ -298,53 +302,62 @@ export function initFiles(app) {
298
302
  loading = busy;
299
303
  dialog.setAttribute("aria-busy", String(busy));
300
304
  const refresh = $("#btnRefreshFiles");
301
- if (refresh)
305
+ // A same-room refresh spins the reload glyph in place; nothing else moves.
306
+ if (refresh) {
302
307
  refresh.disabled = busy;
308
+ refresh.classList.toggle("is-refreshing", busy);
309
+ }
303
310
  more.disabled = busy;
304
311
  };
305
312
  const load = async (reset) => {
306
313
  const room = app.state.room;
307
314
  if (!room || loading)
308
315
  return;
309
- if (reset) {
316
+ if (reset)
310
317
  generation++;
311
- items = [];
312
- total = 0;
313
- hiddenState();
314
- closePreview();
315
- list.textContent = "";
316
- hideError();
317
- }
318
318
  const request = generation;
319
319
  setBusy(true);
320
+ // A same-room refresh keeps the rows, preview and scroll position in place;
321
+ // only the spinner moves until the new set lands in one commit.
320
322
  if (!items.length)
321
323
  summary.textContent = app.t("filesLoading");
324
+ const started = performance.now();
322
325
  try {
323
326
  const offset = reset ? 0 : items.length;
324
- const before = !reset && items.length ? `&before=${encodeURIComponent(items[items.length - 1].id)}` : "";
327
+ const lastItem = items.at(-1);
328
+ const before = !reset && lastItem ? `&before=${encodeURIComponent(lastItem.id)}` : "";
325
329
  const page = await app.api(`/rooms/${encodeURIComponent(room.id)}/resources?limit=${PAGE_SIZE}&offset=${offset}${before}`, {
326
330
  headers: { "x-session-id": LS.sessionID },
327
331
  });
332
+ await waitForRefresh(started);
328
333
  if (request !== generation || app.state.room?.id !== room.id)
329
334
  return;
330
335
  const payload = isRecord(page) ? page : {};
331
- const seen = new Set(items.map((item) => item.id));
336
+ const next = reset ? [] : items;
337
+ const seen = new Set(next.map((item) => item.id));
332
338
  for (const value of Array.isArray(payload.resources) ? payload.resources : []) {
333
339
  const resource = readResource(value);
334
340
  if (!resource || seen.has(resource.id))
335
341
  continue;
336
342
  seen.add(resource.id);
337
- items.push(resource);
343
+ next.push(resource);
338
344
  }
345
+ items = next;
339
346
  total = Number(payload.total) || items.length;
347
+ // A retry clears an earlier error at the same moment the rows swap.
348
+ hideError();
340
349
  render();
341
350
  }
342
351
  catch {
343
- if (request !== generation)
352
+ await waitForRefresh(started);
353
+ if (request !== generation || app.state.room?.id !== room.id)
344
354
  return;
345
355
  showError("filesLoadFailed");
346
- summary.textContent = "";
347
- empty.hidden = true;
356
+ // Keep the visible rows instead of blanking the browser behind an error.
357
+ if (!items.length) {
358
+ summary.textContent = "";
359
+ empty.hidden = true;
360
+ }
348
361
  }
349
362
  finally {
350
363
  if (request === generation)
@@ -411,8 +424,7 @@ export function initFiles(app) {
411
424
  roomName.textContent = app.state.room.name ? ` · ${app.state.room.name}` : "";
412
425
  show();
413
426
  heading.focus();
414
- Promise.resolve(app.loadManageableMembers?.()).then(() => { if (dialog.open && items.length)
415
- render(); });
427
+ void app.loadManageableMembers?.();
416
428
  void load(true);
417
429
  };
418
430
  app.openFilesDialog = open;
@@ -423,14 +435,8 @@ export function initFiles(app) {
423
435
  };
424
436
  trigger?.addEventListener("click", () => { app.closePanels(); open(); });
425
437
  $("#btnCloseFiles")?.addEventListener("click", () => close());
426
- document.addEventListener("keydown", (event) => {
427
- if (event.key !== "Escape" || event.altKey || !dialog.open || !dialog.classList.contains("is-pane"))
428
- return;
429
- if (!dialog.contains(document.activeElement))
430
- return;
431
- event.preventDefault();
432
- close();
433
- });
438
+ // The file browser is a list, so a backdrop click dismisses it; pane mode has no backdrop.
439
+ closeOnBackdrop(dialog, () => close());
434
440
  app.registerPanelSurface?.("files", { element: dialog, close: (restore = true) => close(restore) });
435
441
  app.watchPanel?.("files", syncMode);
436
442
  $("#btnRefreshFiles")?.addEventListener("click", () => void load(true));
@@ -1,12 +1,19 @@
1
1
  import { LOADED_MESSAGE_LIMIT } from "./state.js";
2
+ import { waitForRefresh } from "./refresh-timing.js";
2
3
  // IM-style upward pagination: near the top of the thread, fetch the previous
3
4
  // history page and prepend it without moving the reader's viewport.
4
5
  export function initHistoryLoader(app) {
5
6
  const $ = app.$;
6
7
  let loading = false;
7
- const spinner = document.createElement("li");
8
+ // A zero-height sticky anchor holds the pill over the first rows instead of
9
+ // being a list row, so showing or hiding it never moves the messages.
10
+ const anchor = document.createElement("li");
11
+ anchor.className = "history-anchor";
12
+ anchor.style.cssText = "position:sticky;top:0;height:0;overflow:visible;z-index:2;pointer-events:none;";
13
+ const spinner = document.createElement("div");
8
14
  spinner.className = "history-loading";
9
15
  spinner.setAttribute("role", "status");
16
+ spinner.style.cssText = "position:absolute;top:0;left:0;right:0;padding:9px 0 16px;background:linear-gradient(to bottom,var(--surface) 0 58%,color-mix(in srgb,var(--surface) 0%,transparent) 100%);";
10
17
  const wheel = document.createElement("span");
11
18
  wheel.className = "history-spinner";
12
19
  wheel.setAttribute("aria-hidden", "true");
@@ -14,8 +21,9 @@ export function initHistoryLoader(app) {
14
21
  label.dataset.i18n = "loadingHistory";
15
22
  label.textContent = app.t("loadingHistory");
16
23
  spinner.append(wheel, label);
24
+ anchor.append(spinner);
17
25
  const prependOlder = (older, thread, list) => {
18
- // The loading spinner can be the first child; only a day separator at the
26
+ // Callers drop the loading anchor first; only a day separator at the
19
27
  // boundary is a duplicate to drop.
20
28
  const first = list.firstElementChild;
21
29
  const tailSep = first instanceof HTMLElement && first.classList.contains("day-sep") ? first : null;
@@ -49,25 +57,32 @@ export function initHistoryLoader(app) {
49
57
  const thread = $("#thread"), list = $("#msgList");
50
58
  if (!room || !entry || !thread || !list || loading)
51
59
  return;
60
+ // Rows already in memory prepend in the same frame with the scroll
61
+ // compensation below, so there is no loading state to show or flash.
62
+ const firstRow = list.querySelector("[data-msg-id]");
63
+ const cachedIndex = firstRow ? entry.room.messages.findIndex((message) => message.id === firstRow.dataset.msgId) : -1;
64
+ if (cachedIndex > 0) {
65
+ prependOlder(entry.room.messages.slice(Math.max(0, cachedIndex - 100), cachedIndex), thread, list);
66
+ return;
67
+ }
68
+ if (entry.historyComplete || entry.historyBeforeSeq == null)
69
+ return;
52
70
  loading = true;
53
- const generation = app.state.pollGeneration;
71
+ const startedAt = performance.now(), generation = app.state.pollGeneration;
72
+ const stale = () => app.state.room?.id !== room.id || app.state.pollGeneration !== generation;
54
73
  try {
55
- const firstRow = list.querySelector("[data-msg-id]");
56
- const cachedIndex = firstRow ? entry.room.messages.findIndex((message) => message.id === firstRow.dataset.msgId) : -1;
57
- if (cachedIndex > 0) {
58
- prependOlder(entry.room.messages.slice(Math.max(0, cachedIndex - 100), cachedIndex), thread, list);
59
- return;
60
- }
61
- if (entry.historyComplete || entry.historyBeforeSeq == null)
62
- return;
63
- list.prepend(spinner);
74
+ list.prepend(anchor);
64
75
  const page = await app.api(`/rooms/${encodeURIComponent(room.id)}/history?beforeSeq=${entry.historyBeforeSeq}&limit=100`);
65
- if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation)
76
+ if (stale())
77
+ return;
78
+ // Hold the pill for the minimum so a fast page cannot flash it in and out.
79
+ await waitForRefresh(startedAt);
80
+ if (stale())
66
81
  return;
67
82
  const known = new Set(entry.room.messages.map((message) => message.id));
68
83
  const older = (page.messages || []).filter((message) => !known.has(message.id));
69
84
  entry.historyComplete = !page.hasMore;
70
- spinner.remove();
85
+ anchor.remove();
71
86
  if (older.length) {
72
87
  prependOlder(older, thread, list);
73
88
  entry.room.messages = [...older, ...entry.room.messages].sort((left, right) => left.createdAt - right.createdAt);
@@ -79,8 +94,9 @@ export function initHistoryLoader(app) {
79
94
  }
80
95
  catch { /* the next scroll toward the top retries */ }
81
96
  finally {
97
+ await waitForRefresh(startedAt);
98
+ anchor.remove();
82
99
  loading = false;
83
- spinner.remove();
84
100
  }
85
101
  };
86
102
  }
@@ -30,6 +30,26 @@ export function initIntegrationEditor(app, options) {
30
30
  const errorList = app.$(options.errors);
31
31
  const formatGroup = app.$(options.formats);
32
32
  let controller = null, loading = null, failed = false, editable = true;
33
+ let baseline = { text: textarea?.value || "", json: "", valid: false };
34
+ // Baseline is the authoritative source the last refresh or creation rendered.
35
+ // Valid values compare semantically, so a view-only format switch is not a
36
+ // draft; invalid text has no value, so its raw source is the evidence.
37
+ const capture = () => {
38
+ if (!controller) {
39
+ baseline = { text: textarea?.value || "", json: "", valid: false };
40
+ return;
41
+ }
42
+ const now = controller.validate();
43
+ baseline = { text: now.text, json: now.valid ? JSON.stringify(now.value ?? null) : "", valid: now.valid === true };
44
+ };
45
+ const hasChanges = () => {
46
+ if (!controller)
47
+ return (textarea?.value || "") !== baseline.text;
48
+ const now = controller.validate();
49
+ if (now.valid === true && baseline.valid)
50
+ return JSON.stringify(now.value ?? null) !== baseline.json;
51
+ return now.text !== baseline.text;
52
+ };
33
53
  if (formatGroup)
34
54
  formatGroup.hidden = true;
35
55
  const applyEditable = () => {
@@ -61,6 +81,8 @@ export function initIntegrationEditor(app, options) {
61
81
  return;
62
82
  }
63
83
  const first = result.errors[0];
84
+ if (!first)
85
+ return;
64
86
  error.textContent = app.t("integrationsRulesErrors", {
65
87
  count: result.errors.length,
66
88
  first: `Line ${first.line}: ${first.message}`,
@@ -110,12 +132,14 @@ export function initIntegrationEditor(app, options) {
110
132
  formatGroup.hidden = false;
111
133
  applyEditable();
112
134
  render(controller.validate());
135
+ capture();
113
136
  }).catch(() => {
114
137
  failed = true;
115
138
  if (fallback) {
116
139
  fallback.textContent = app.t("integrationsEditorUnavailable");
117
140
  fallback.hidden = false;
118
141
  }
142
+ capture();
119
143
  }).finally(() => { loading = null; });
120
144
  return loading;
121
145
  };
@@ -124,8 +148,9 @@ export function initIntegrationEditor(app, options) {
124
148
  clearErrors();
125
149
  if (controller)
126
150
  controller.setValue(value);
127
- else if (textarea)
151
+ if (!controller && textarea)
128
152
  textarea.value = JSON.stringify(value, null, 2);
153
+ capture();
129
154
  };
130
155
  const current = () => {
131
156
  if (controller) {
@@ -148,6 +173,7 @@ export function initIntegrationEditor(app, options) {
148
173
  ensure,
149
174
  refresh,
150
175
  current,
176
+ hasChanges,
151
177
  showMessage: (message) => {
152
178
  if (!error)
153
179
  return;
@@ -3,6 +3,8 @@ import { iconNode } from "./icons.js";
3
3
  import { readAccountSchema, renderAccountSchema } from "./integration-account-schema.js";
4
4
  import { checkInbound, checkRules, knownPlugins, normalizeAccount, parseInbound, parseRules } from "./integration-values.js";
5
5
  import { accountBody, cleanError, stateLabel } from "./integration-values.js";
6
+ import { closeOnBackdrop } from "./panels.js";
7
+ import { waitForRefresh } from "./refresh-timing.js";
6
8
  const MAX_SOURCE = 256 * 1024;
7
9
  const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
8
10
  const PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs|ts)$/;
@@ -60,6 +62,7 @@ export function initIntegrations(app) {
60
62
  const accountsEmpty = $("#integrationAccountsEmpty"), pluginsList = $("#integrationPlugins");
61
63
  const pluginsEmpty = $("#integrationPluginsEmpty");
62
64
  const rulesError = $("#integrationRulesError"), saveButton = $("#btnSaveIntegrations");
65
+ const refreshButton = $("#btnRefreshIntegrations");
63
66
  const accountDialog = $("#integrationAccountDialog"), accountForm = $("#integrationAccountForm");
64
67
  const accountError = $("#integrationAccountError"), accountId = $("#integrationAccountId");
65
68
  const accountPlugin = $("#integrationAccountPlugin");
@@ -77,14 +80,35 @@ export function initIntegrations(app) {
77
80
  const api = (url, options) => app.api(url, options);
78
81
  let data = { enabled: false, source: "managed", editable: true, accounts: [], rules: [], inbound: [], plugins: [] };
79
82
  let initialInbound = "[]";
80
- let loaded = false, loading = false, saving = false, clearEnv = false;
83
+ let loaded = false, saving = false, clearEnv = false;
84
+ let editEpoch = 0, saveEpoch = 0;
81
85
  let accountDraft = null;
86
+ let accountDirty = false, pluginUploading = false;
87
+ let savedAccounts = data.accounts;
82
88
  let pluginUploadSource = "", pluginUploadName = "";
83
89
  const text = (key, values) => app.t(key, values);
84
90
  const clean = (error) => String(cleanError(error, text("integrationsLoadFailed")));
85
91
  const showPanelError = (error) => { panelError.textContent = clean(error); panelError.hidden = false; };
86
92
  const hidePanelError = () => { panelError.hidden = true; };
87
93
  const showStatus = (value) => { statusText.textContent = value; };
94
+ // The newest read owns the spinner; a stale answer cannot hide a newer load.
95
+ let busyToken = 0;
96
+ const startBusy = () => {
97
+ const token = ++busyToken;
98
+ refreshButton?.setAttribute("aria-busy", "true");
99
+ if (refreshButton)
100
+ refreshButton.disabled = true;
101
+ integrationBody.setAttribute("aria-busy", "true");
102
+ return token;
103
+ };
104
+ const endBusy = (token) => {
105
+ if (token !== busyToken)
106
+ return;
107
+ refreshButton?.removeAttribute("aria-busy");
108
+ if (refreshButton)
109
+ refreshButton.disabled = false;
110
+ integrationBody.removeAttribute("aria-busy");
111
+ };
88
112
  const showAccountError = (error) => { accountError.textContent = clean(error); accountError.hidden = false; };
89
113
  const hideAccountError = () => { accountError.hidden = true; };
90
114
  const showPluginError = (error) => { pluginError.textContent = clean(error); pluginError.hidden = false; };
@@ -145,6 +169,9 @@ export function initIntegrations(app) {
145
169
  : data.plugins,
146
170
  };
147
171
  initialInbound = JSON.stringify(data.inbound);
172
+ // Account rows are replaced, never mutated in place, so the reference itself
173
+ // is the saved/staged evidence without copying secret env values.
174
+ savedAccounts = data.accounts;
148
175
  loaded = true;
149
176
  }
150
177
  const renderAccounts = () => {
@@ -271,28 +298,63 @@ export function initIntegrations(app) {
271
298
  applyEnabledState();
272
299
  applyEditableState();
273
300
  };
274
- async function load(force = false) {
275
- if (loading || loaded && !force)
301
+ let readChain = Promise.resolve(), writeInFlight = false;
302
+ function load(force = false, timed = false) {
303
+ // A save owns the authoritative read; a click during it is covered by the post-save read.
304
+ if (saving)
305
+ return Promise.resolve();
306
+ const run = readChain.then(() => readSnapshot(force, timed));
307
+ readChain = run.catch(() => undefined);
308
+ return run;
309
+ }
310
+ async function readSnapshot(force, timed) {
311
+ if (loaded && !force)
276
312
  return;
277
- loading = true;
313
+ const token = startBusy(), started = performance.now(), edits = editEpoch, saves = saveEpoch, first = !loaded;
314
+ // A read that starts during a save only sees pre-save data, even if it settles later.
315
+ const duringSave = writeInFlight;
316
+ const stale = () => duringSave || writeInFlight || edits !== editEpoch || saves !== saveEpoch;
278
317
  void rulesSection.ensure();
279
318
  void inboundSection.ensure();
280
319
  hidePanelError();
281
- showStatus(text("integrationsLoading"));
320
+ if (first)
321
+ showStatus(text("integrationsLoading"));
282
322
  try {
283
- adopt(await api("/channeld/integration", { cache: "no-store" }));
323
+ const snapshot = await api("/channeld/integration", { cache: "no-store" });
324
+ // A slow answer lands as soon as it arrives; only a fast one waits out the spinner.
325
+ if (timed)
326
+ await waitForRefresh(started);
327
+ // Never let an older snapshot overwrite edits or a save the user started meanwhile.
328
+ if (stale()) {
329
+ if (first)
330
+ showStatus("");
331
+ return;
332
+ }
333
+ adopt(snapshot);
284
334
  renderAll();
285
335
  showStatus("");
286
336
  }
287
337
  catch (error) {
338
+ if (stale()) {
339
+ if (first)
340
+ showStatus("");
341
+ return;
342
+ }
288
343
  showStatus("");
289
344
  showPanelError(error);
290
345
  }
291
346
  finally {
292
- loading = false;
347
+ endBusy(token);
293
348
  }
294
349
  }
295
- app.loadIntegrations = () => { void load(true); };
350
+ app.loadIntegrations = () => { void load(true, true); };
351
+ // A staged draft keeps the outer Settings backdrop from closing: reopening the
352
+ // Integrations tab force-refreshes and would discard it.
353
+ app.hasIntegrationDraft = () => saving || writeInFlight || enabledInput.checked !== data.enabled ||
354
+ data.accounts !== savedAccounts || rulesSection.hasChanges() || inboundSection.hasChanges();
355
+ // A form change during a load makes that snapshot stale.
356
+ panel.addEventListener("input", () => { editEpoch++; });
357
+ panel.addEventListener("change", () => { editEpoch++; });
296
358
  const setSaving = (busy) => {
297
359
  saving = busy;
298
360
  saveButton.disabled = busy || data.editable === false;
@@ -347,6 +409,7 @@ export function initIntegrations(app) {
347
409
  };
348
410
  const choose = (option) => {
349
411
  key.value = option.dataset.key ?? "";
412
+ accountDirty = true;
350
413
  hide();
351
414
  value.focus();
352
415
  };
@@ -438,6 +501,7 @@ export function initIntegrations(app) {
438
501
  remove.addEventListener("click", () => {
439
502
  const currentKey = key.value.trim();
440
503
  row.remove();
504
+ accountDirty = true;
441
505
  onRemove?.(currentKey, existing);
442
506
  });
443
507
  row.append(keyControl, value, remove);
@@ -513,7 +577,7 @@ export function initIntegrations(app) {
513
577
  accountSchemaField.hidden = accountSchema.hidden;
514
578
  // Without a declared schema the raw env rows are the only way to configure
515
579
  // the account, so keep them open; schema-backed plugins can collapse them.
516
- accountAdvanced.open = accountSchema.hidden;
580
+ accountAdvanced.open = Boolean(accountSchema.hidden);
517
581
  };
518
582
  const openAccount = (account = null, presetPlugin = "") => {
519
583
  if (data.editable === false)
@@ -540,6 +604,7 @@ export function initIntegrations(app) {
540
604
  if (!keys.length)
541
605
  addEnvRow(accountEnv);
542
606
  setClearEnv(Boolean(account?.envClear));
607
+ accountDirty = false;
543
608
  accountDialog.showModal();
544
609
  accountPlugin.focus();
545
610
  };
@@ -665,9 +730,13 @@ export function initIntegrations(app) {
665
730
  }
666
731
  }
667
732
  const inboundChanged = JSON.stringify(inbound) !== initialInbound;
733
+ saveEpoch++;
734
+ const stamp = saveEpoch;
668
735
  setSaving(true);
736
+ writeInFlight = true;
737
+ let saved = null, failed = false;
669
738
  try {
670
- adopt(await api("/channeld/integration", {
739
+ saved = await api("/channeld/integration", {
671
740
  method: "PUT",
672
741
  body: JSON.stringify({
673
742
  enabled: enabledInput.checked,
@@ -675,18 +744,25 @@ export function initIntegrations(app) {
675
744
  rules,
676
745
  ...(inboundChanged ? { inbound } : {}),
677
746
  }),
678
- }));
679
- const enabled = data.enabled;
680
- await load(true);
681
- if (panelError.hidden)
682
- showStatus(text(enabled ? "integrationsSavedEnabled" : "integrationsSavedDisabled"));
747
+ });
683
748
  }
684
749
  catch (error) {
750
+ failed = true;
685
751
  showPanelError(error);
686
752
  }
687
753
  finally {
754
+ writeInFlight = false;
688
755
  setSaving(false);
689
756
  }
757
+ if (failed)
758
+ return;
759
+ adopt(saved);
760
+ const enabled = data.enabled;
761
+ // Read after the save lock lifts: the queued read cannot be skipped by an older request.
762
+ await load(true);
763
+ // A newer save owns the status line now.
764
+ if (saveEpoch === stamp && panelError.hidden)
765
+ showStatus(text(enabled ? "integrationsSavedEnabled" : "integrationsSavedDisabled"));
690
766
  };
691
767
  const openUpload = () => {
692
768
  if (data.editable === false)
@@ -729,6 +805,7 @@ export function initIntegrations(app) {
729
805
  if (!submit)
730
806
  return;
731
807
  submit.disabled = true;
808
+ pluginUploading = true;
732
809
  try {
733
810
  const result = await api("/channeld/plugins", {
734
811
  method: "POST",
@@ -752,6 +829,7 @@ export function initIntegrations(app) {
752
829
  showPluginError(error);
753
830
  }
754
831
  finally {
832
+ pluginUploading = false;
755
833
  submit.disabled = false;
756
834
  }
757
835
  });
@@ -761,7 +839,7 @@ export function initIntegrations(app) {
761
839
  enabledInput.addEventListener("change", applyEnabledState);
762
840
  addAccountButton?.addEventListener("click", () => openAccount(null));
763
841
  uploadPluginButton?.addEventListener("click", openUpload);
764
- $("#btnRefreshIntegrations")?.addEventListener("click", () => void load(true));
842
+ $("#btnRefreshIntegrations")?.addEventListener("click", () => void load(true, true));
765
843
  saveButton.addEventListener("click", () => void save());
766
844
  $("#btnCloseIntegrationAccount")?.addEventListener("click", closeAccount);
767
845
  $("#btnCancelIntegrationAccount")?.addEventListener("click", closeAccount);
@@ -769,4 +847,18 @@ export function initIntegrations(app) {
769
847
  $("#btnCloseIntegrationPlugin")?.addEventListener("click", () => pluginDialog.close());
770
848
  $("#btnCancelIntegrationPlugin")?.addEventListener("click", () => pluginDialog.close());
771
849
  pluginDialog.addEventListener("cancel", (event) => { event.preventDefault(); pluginDialog.close(); });
850
+ // A backdrop click closes an untouched form; typed secrets, env rows and a
851
+ // chosen file stay until the user cancels or finishes. Add, remove and clear
852
+ // are marked where they mutate the draft; harmless buttons are not.
853
+ const markAccountDirty = () => { accountDirty = true; };
854
+ accountForm.addEventListener("input", markAccountDirty);
855
+ accountForm.addEventListener("change", markAccountDirty);
856
+ accountAddEnv.addEventListener("click", markAccountDirty);
857
+ accountClear.addEventListener("click", markAccountDirty);
858
+ closeOnBackdrop(accountDialog, () => { if (!accountDirty)
859
+ closeAccount(); });
860
+ closeOnBackdrop(pluginDialog, () => {
861
+ if (!pluginUploading && !pluginFile.files?.length)
862
+ pluginDialog.close();
863
+ });
772
864
  }