@alexsun-top/opencode-chat-room 0.7.7 → 0.8.0

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 (97) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE +21 -0
  3. package/README.md +45 -36
  4. package/README.zh-CN.md +50 -41
  5. package/dist/cli.js +2696 -365
  6. package/package.json +14 -4
  7. package/packages/chat-room-channeld/README.md +242 -0
  8. package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
  9. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  10. package/packages/chat-room-channeld/src/adapter.ts +475 -0
  11. package/packages/chat-room-channeld/src/cli.ts +124 -0
  12. package/packages/chat-room-channeld/src/config.ts +207 -0
  13. package/packages/chat-room-channeld/src/delivery.ts +158 -0
  14. package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
  15. package/packages/chat-room-channeld/src/framing.ts +128 -0
  16. package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
  17. package/packages/chat-room-channeld/src/host.ts +509 -0
  18. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  19. package/packages/chat-room-channeld/src/log.ts +26 -0
  20. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  21. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  22. package/packages/chat-room-channeld/src/published.ts +37 -0
  23. package/packages/chat-room-channeld/src/rules.ts +127 -0
  24. package/packages/chat-room-channeld/src/state.ts +485 -0
  25. package/packages/chat-room-channeld/src/stats.ts +167 -0
  26. package/plugin.ts +22 -5
  27. package/server/addressing-routes.ts +130 -0
  28. package/server/assets/NOTICE.txt +2 -2
  29. package/server/assets/SHIKI-LICENSE +22 -0
  30. package/server/assets/base.css +9 -1
  31. package/server/assets/chat/announcements.js +5 -2
  32. package/server/assets/chat/clipboard.js +30 -0
  33. package/server/assets/chat/copy-action.js +48 -0
  34. package/server/assets/chat/diagram-viewer.js +253 -0
  35. package/server/assets/chat/doc-preview.js +149 -12
  36. package/server/assets/chat/events.js +25 -4
  37. package/server/assets/chat/files.js +26 -5
  38. package/server/assets/chat/forward.js +69 -0
  39. package/server/assets/chat/history-loader.js +3 -1
  40. package/server/assets/chat/index.js +11 -1
  41. package/server/assets/chat/join-requests.js +6 -3
  42. package/server/assets/chat/locales/de.js +7 -2
  43. package/server/assets/chat/locales/es.js +7 -2
  44. package/server/assets/chat/locales/fr.js +7 -2
  45. package/server/assets/chat/locales/it.js +7 -2
  46. package/server/assets/chat/locales/ja.js +7 -2
  47. package/server/assets/chat/locales/ko.js +7 -2
  48. package/server/assets/chat/markdown-footnotes.js +115 -0
  49. package/server/assets/chat/markdown.js +65 -113
  50. package/server/assets/chat/messages.js +6 -3
  51. package/server/assets/chat/palette.js +33 -16
  52. package/server/assets/chat/pwa.js +2 -0
  53. package/server/assets/chat/questions.js +5 -0
  54. package/server/assets/chat/replies.js +7 -1
  55. package/server/assets/chat/resource-format.js +74 -0
  56. package/server/assets/chat/rooms.js +3 -0
  57. package/server/assets/chat/shiki.js +87 -0
  58. package/server/assets/chat/side-pane.js +143 -0
  59. package/server/assets/chat/state.js +63 -9
  60. package/server/assets/chat/system-messages.js +2 -0
  61. package/server/assets/chat/task-row.js +2 -1
  62. package/server/assets/chat/tasks.js +29 -2
  63. package/server/assets/chat/viewport.js +5 -0
  64. package/server/assets/code-highlight.css +20 -31
  65. package/server/assets/conversation.css +27 -2
  66. package/server/assets/diagram-viewer.css +141 -0
  67. package/server/assets/doc-preview.css +26 -6
  68. package/server/assets/responsive.css +87 -13
  69. package/server/assets/shiki.bundle.js +152 -0
  70. package/server/assets/tasks.css +1 -4
  71. package/server/channels.ts +314 -0
  72. package/server/chat-server.ts +36 -8
  73. package/server/chat.html +33 -5
  74. package/server/resource-routes.ts +3 -1
  75. package/server/sw.js +236 -4
  76. package/skills/chatroom/SKILL.md +1 -1
  77. package/src/agent/chatroom-skill.ts +8 -2
  78. package/src/center/center-client.ts +79 -1
  79. package/src/config/file-config.ts +34 -0
  80. package/src/rooms/resources.ts +2 -2
  81. package/src/runtime/v2-plugin.ts +8 -2
  82. package/src/runtime/watch.ts +41 -7
  83. package/src/state/sqlite-state.ts +67 -18
  84. package/src/state/store.ts +11 -5
  85. package/src/tui/app.mjs +10 -2
  86. package/src/tui/http.mjs +16 -2
  87. package/src/tui/info-app.mjs +24 -15
  88. package/src/tui/join-app.mjs +3 -3
  89. package/src/tui/main.mjs +1 -1
  90. package/src/tui/markdown.mjs +5 -3
  91. package/src/tui/mentions.mjs +3 -3
  92. package/src/tui/message-app.mjs +14 -11
  93. package/src/tui/palette-app.mjs +10 -7
  94. package/src/tui/reminder-app.mjs +14 -10
  95. package/src/tui/ui-content.mjs +3 -1
  96. package/server/assets/HIGHLIGHT-LICENSE +0 -29
  97. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -70,6 +70,8 @@ export function initMessages(app) {
70
70
  app.saveFailedMessages(roomId, (app.state.failedMessages.get(roomId) || []).filter((item) => item.id !== failedId));
71
71
  app.renderFailedMessages();
72
72
  };
73
+ // A retry reuses the first attempt's clientMessageID so a lost response
74
+ // cannot create a twin.
73
75
  app.retryFailedMessage = async (roomId, failedId) => {
74
76
  const item = app.state.failedMessages.get(roomId)?.find((message) => message.id === failedId);
75
77
  if (!item || app.state.retryingFailedIds.has(failedId)) return;
@@ -78,7 +80,7 @@ export function initMessages(app) {
78
80
  try {
79
81
  const questionTarget = item.replyTarget?.isQuestion, entry = app.state.rooms.get(roomId);
80
82
  const updated = questionTarget ? (await app.answerQuestionFromReply(roomId, item.replyToMessageID, item.text), entry?.room)
81
- : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
83
+ : await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, { method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text, isQuestion: Boolean(item.isQuestion), ...(item.clientMessageID ? { clientMessageID: item.clientMessageID } : {}), ...(item.replyToMessageID ? { replyToMessageID: item.replyToMessageID } : {}) }) });
82
84
  app.completeAttachmentsFromText?.(roomId, item.text);
83
85
  if (entry) {
84
86
  if (!questionTarget) entry.room = mergeRoom(entry.room, updated);
@@ -370,6 +372,7 @@ export function initMessages(app) {
370
372
  // keep the caret in the composer or the next keystrokes go nowhere.
371
373
  input.focus({ preventScroll: true });
372
374
  const text = message.text;
375
+ const clientMessageID = createRandomId();
373
376
  const thread = $("#thread"), followedBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
374
377
  const revision = app.state.draftRevision.get(room.id) || 0;
375
378
  app.state.sendingRooms ||= new Set(); app.state.sendingRooms.add(room.id);
@@ -394,7 +397,7 @@ export function initMessages(app) {
394
397
  let updated;
395
398
  if (replyTarget?.isQuestion) { await app.answerQuestionFromReply(room.id, replyTarget.id, text); updated = app.state.rooms.get(room.id)?.room || room; }
396
399
  else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
397
- method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
400
+ method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
398
401
  });
399
402
  // A successful request proves the connection is usable, even if a stale
400
403
  // long-poll is still waiting to time out.
@@ -441,7 +444,7 @@ export function initMessages(app) {
441
444
  if (staleReply) app.saveDraft(room.id, text);
442
445
  else {
443
446
  const failures = app.state.failedMessages.get(room.id) || [];
444
- app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
447
+ app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text, clientMessageID, ...(replyTarget ? { replyToMessageID: replyTarget.id, replyTarget } : {}) }]);
445
448
  app.renderFailedMessages();
446
449
  }
447
450
  app.completeAttachments?.(room.id, message.ids);
@@ -2,7 +2,7 @@ import { icon } from "./icons.js";
2
2
 
3
3
  // Alt+Space or Ctrl+P opens one keyboard-first surface: message search plus common room commands.
4
4
 
5
- const SEARCH_DEBOUNCE_MS = 220;
5
+ const SEARCH_DEBOUNCE_MS = 120;
6
6
 
7
7
  export function initPalette(app) {
8
8
  const dialog = app.$("#paletteDialog");
@@ -20,19 +20,19 @@ export function initPalette(app) {
20
20
 
21
21
  const commands = () => {
22
22
  const available = [
23
- { id: "refresh", label: t("refreshRooms"), icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
24
- { id: "create", label: t("createRoom"), icon: "add", keywords: "new room", focusComposer: false,
23
+ { id: "refresh", label: t("refreshRooms"), en: "Refresh rooms", icon: "arrow_sync", keywords: "reload rooms", run: () => void app.refreshRoomList?.() },
24
+ { id: "create", label: t("createRoom"), en: "New room", icon: "add", keywords: "new room", focusComposer: false,
25
25
  run: () => room() ? app.openCreateRoomDialog?.() : app.$("#inRoomName")?.focus({ preventScroll: true }) },
26
- { id: "settings", label: t("settings"), icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
26
+ { id: "settings", label: t("settings"), en: "Settings", icon: "options", keywords: "preferences theme language", focusComposer: false, run: () => app.openSettings?.() },
27
27
  ];
28
28
  if (room()) available.push(
29
- { id: "members", label: t("members"), icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() },
30
- { id: "questions", label: t("questions"), icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() },
31
- { id: "announcements", label: t("announcements"), icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() },
32
- ...(room().kind === "direct" ? [] : [{ id: "tasks", label: t("tasksTitle"), icon: "checkmark", keywords: "todo checklist work", focusComposer: false, run: () => app.openTasksDialog?.() }]),
33
- { id: "reminders", label: t("reminders"), icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() },
34
- { id: "leave", label: t("paletteLeaveRoom"), icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) },
35
- { id: "latest", label: t("paletteJumpLatest"), icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() },
29
+ { id: "members", label: t("members"), en: "Members", icon: "people", keywords: "people roster", focusComposer: false, run: () => app.$("#btnMembers")?.click() },
30
+ { id: "questions", label: t("questions"), en: "Questions", icon: "question_circle", keywords: "answers", focusComposer: false, run: () => app.$("#btnQuestions")?.click() },
31
+ { id: "announcements", label: t("announcements"), en: "Announcements", icon: "megaphone", keywords: "notice board", focusComposer: false, run: () => app.$("#btnAnnouncements")?.click() },
32
+ ...(room().kind === "direct" ? [] : [{ id: "tasks", label: t("tasksTitle"), en: "Tasks", icon: "checkmark", keywords: "todo checklist work", focusComposer: false, run: () => app.openTasksDialog?.() }]),
33
+ { id: "reminders", label: t("reminders"), en: "Reminders", icon: "alert", keywords: "schedule alarm", focusComposer: false, run: () => app.$("#btnReminders")?.click() },
34
+ { id: "leave", label: t("paletteLeaveRoom"), en: "Leave room", icon: "arrow_exit", keywords: "exit quit", focusComposer: false, run: () => app.leaveRoom?.(false) },
35
+ { id: "latest", label: t("paletteJumpLatest"), en: "Jump to latest", icon: "arrow_down", keywords: "bottom newest", run: () => app.jumpToBottom?.() },
36
36
  );
37
37
  return available;
38
38
  };
@@ -133,12 +133,24 @@ export function initPalette(app) {
133
133
  syncSelection();
134
134
  };
135
135
 
136
+ // Empty input is search, not a command wall: commands appear only after "/".
137
+ const showIdle = () => {
138
+ clearTimeout(searchTimer);
139
+ sequence++;
140
+ dialog.dataset.mode = "search";
141
+ dialog.dataset.state = "ready";
142
+ modeLabel.textContent = t("paletteSearchMode");
143
+ list.setAttribute("aria-busy", "false");
144
+ render([], null);
145
+ status.textContent = t("palettePlaceholder");
146
+ };
147
+
136
148
  const showCommands = (fragment = "") => {
137
149
  clearTimeout(searchTimer);
138
150
  sequence++;
139
151
  const needle = fragment.trim().toLowerCase();
140
152
  const available = commands()
141
- .filter((command) => !needle || `${command.label} ${command.keywords || ""}`.toLowerCase().includes(needle))
153
+ .filter((command) => !needle || `${command.label} ${command.en || ""} ${command.keywords || ""} ${command.id}`.toLowerCase().includes(needle))
142
154
  .map((command) => ({ kind: "command", ...command }));
143
155
  dialog.dataset.mode = "commands";
144
156
  dialog.dataset.state = "ready";
@@ -232,7 +244,7 @@ export function initPalette(app) {
232
244
  clearTimeout(searchTimer);
233
245
  const token = ++sequence;
234
246
  const value = input.value;
235
- if (!value.trim()) { showCommands(""); return; }
247
+ if (!value.trim()) { showIdle(); return; }
236
248
  if (value.startsWith("/")) { showCommands(value.slice(1)); return; }
237
249
  const wasSearch = dialog.dataset.mode === "search";
238
250
  dialog.dataset.mode = "search";
@@ -242,6 +254,7 @@ export function initPalette(app) {
242
254
  // Keep the previous hits visible while typing. Clearing them on every
243
255
  // keystroke is what makes the result list flicker.
244
256
  if (!wasSearch || !items.length) render([], null);
257
+ else { selected = -1; syncSelection(); }
245
258
  status.textContent = t("paletteSearching");
246
259
  const text = value.trim();
247
260
  searchTimer = setTimeout(() => { void executeSearch(text, token); }, SEARCH_DEBOUNCE_MS);
@@ -293,7 +306,7 @@ export function initPalette(app) {
293
306
  scope = scope === "room" ? "all" : "room";
294
307
  syncScope();
295
308
  const value = input.value;
296
- if (!value.trim()) showCommands("");
309
+ if (!value.trim()) showIdle();
297
310
  else if (value.startsWith("/")) showCommands(value.slice(1));
298
311
  else scheduleSearch();
299
312
  };
@@ -311,13 +324,16 @@ export function initPalette(app) {
311
324
  input.value = "";
312
325
  scope = "room";
313
326
  syncScope();
314
- showCommands("");
327
+ showIdle();
315
328
  dialog.showModal();
316
329
  input.focus();
317
330
  };
318
331
  app.openPalette = openPalette;
319
332
 
320
333
  input.addEventListener("input", (event) => { if (!event.isComposing) scheduleSearch(); });
334
+ // IME commits (Chinese, Japanese, Korean) may fire no plain input event after
335
+ // composition ends, so filter the committed text here as well.
336
+ input.addEventListener("compositionend", () => scheduleSearch());
321
337
  scopeButton.addEventListener("click", () => { toggleScope(); input.focus(); });
322
338
  app.$("#btnClosePalette")?.addEventListener("click", () => closePalette());
323
339
  dialog.addEventListener("click", (event) => { if (event.target === dialog) closePalette(); });
@@ -399,7 +415,8 @@ export function initPalette(app) {
399
415
  syncScope();
400
416
  if (!dialog.open) return;
401
417
  const value = input.value;
402
- if (!value.trim() || value.startsWith("/")) showCommands(value.startsWith("/") ? value.slice(1) : "");
418
+ if (!value.trim()) showIdle();
419
+ else if (value.startsWith("/")) showCommands(value.slice(1));
403
420
  else scheduleSearch();
404
421
  };
405
422
  }
@@ -52,6 +52,8 @@ export function initPwa(app) {
52
52
  // next open; otherwise this page keeps running without interruption.
53
53
  later.addEventListener("click", hide);
54
54
  navigator.serviceWorker.addEventListener("controllerchange", () => {
55
+ // A new worker lost the in-memory identity; the cache partition must follow this page.
56
+ void app.postMediaIdentity?.();
55
57
  if (reloading && !reloaded) {
56
58
  reloaded = true;
57
59
  location.reload();
@@ -301,6 +301,11 @@ export function initQuestions(app) {
301
301
  const activateRoom = app.activateRoom;
302
302
  app.activateRoom = (roomId, preserveRoomListGeneration = false) => {
303
303
  activateRoom(roomId, preserveRoomListGeneration);
304
+ // Error and too-long banners belong to the room that produced them.
305
+ delete status.dataset.error;
306
+ delete status.dataset.tooLong;
307
+ status.hidden = true;
308
+ status.textContent = "";
304
309
  void load(roomId);
305
310
  };
306
311
  const applyLocale = app.applyLocale;
@@ -33,7 +33,7 @@ function bindMessageActions(app) {
33
33
  const render = app.renderMessage;
34
34
  app.renderMessage = (message, live) => {
35
35
  const row = render(message, live);
36
- if (message.senderId === "system" || message.pending) return row;
36
+ if (message.senderId === "system" || message.pending || message.recalledAt) return row;
37
37
  if (message.answerToMessageID) row.querySelector(".msg-meta")?.after(quoteButton(message, app));
38
38
  const copy = row.querySelector("[data-copy-message]");
39
39
  if (copy) {
@@ -42,6 +42,12 @@ function bindMessageActions(app) {
42
42
  reply.type = "button"; reply.className = "message-reply"; reply.innerHTML = icon("arrow_reply", "message-reply-icon");
43
43
  reply.setAttribute("aria-label", app.t("replyMessage")); reply.dataset.i18nAriaLabel = "replyMessage"; reply.dataset.replyMessage = message.id;
44
44
  copy.before(actions); actions.append(copy, reply);
45
+ if (document.body.dataset.channeld === "on") {
46
+ const forward = document.createElement("button");
47
+ forward.type = "button"; forward.className = "message-reply message-forward"; forward.innerHTML = icon("arrow_right", "message-reply-icon");
48
+ forward.setAttribute("aria-label", app.t("forwardMessage")); forward.dataset.i18nAriaLabel = "forwardMessage"; forward.dataset.forwardMessage = message.id;
49
+ actions.append(forward);
50
+ }
45
51
  }
46
52
  return row;
47
53
  };
@@ -0,0 +1,74 @@
1
+ // Shared classification for resources that open in the reading pane. The server
2
+ // sniffs text and PDF uploads as application/octet-stream, so the filename
3
+ // extension is a first-class signal alongside the MIME type.
4
+ export const TEXT_PREVIEW_LIMIT = 2 * 1024 * 1024;
5
+
6
+ const MIME_LANGUAGES = {
7
+ "application/json": "json", "application/ld+json": "json",
8
+ "application/xml": "xml", "text/xml": "xml",
9
+ "application/javascript": "javascript", "application/x-javascript": "javascript",
10
+ "application/typescript": "typescript",
11
+ "application/x-yaml": "yaml", "application/yaml": "yaml",
12
+ "application/toml": "ini",
13
+ "text/html": "xml", "text/css": "css",
14
+ };
15
+
16
+ const EXTENSION_LANGUAGES = {
17
+ txt: "", log: "", csv: "", tsv: "",
18
+ json: "json", jsonc: "json", yaml: "yaml", yml: "yaml",
19
+ toml: "ini", ini: "ini", conf: "ini", env: "ini", properties: "properties",
20
+ sh: "bash", bash: "bash", zsh: "bash", fish: "bash",
21
+ ps1: "powershell", bat: "dos", cmd: "dos",
22
+ js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "javascript",
23
+ ts: "typescript", tsx: "typescript",
24
+ py: "python", rb: "ruby", go: "go", rs: "rust", java: "java",
25
+ kt: "kotlin", kts: "kotlin", c: "c", h: "c", cpp: "cpp", hpp: "cpp", cc: "cpp",
26
+ cs: "csharp", php: "php", swift: "swift", sql: "sql",
27
+ html: "xml", htm: "xml", css: "css", scss: "scss", less: "less",
28
+ xml: "xml", svg: "xml", vue: "xml", svelte: "xml",
29
+ lua: "lua", r: "r", pl: "perl", pm: "perl", dart: "dart",
30
+ gradle: "groovy", dockerfile: "dockerfile", makefile: "makefile", mk: "makefile",
31
+ };
32
+
33
+ const LANGUAGE_NAMES = {
34
+ typescript: "TypeScript", javascript: "JavaScript", python: "Python", ruby: "Ruby",
35
+ bash: "Shell", yaml: "YAML", json: "JSON", xml: "XML", c: "C", cpp: "C++",
36
+ csharp: "C#", kotlin: "Kotlin", rust: "Rust", go: "Go", java: "Java",
37
+ php: "PHP", swift: "Swift", sql: "SQL", css: "CSS", scss: "SCSS", less: "Less",
38
+ ini: "Config", properties: "Properties", powershell: "PowerShell", dos: "Batch",
39
+ dockerfile: "Dockerfile", makefile: "Makefile", lua: "Lua", r: "R", perl: "Perl",
40
+ dart: "Dart", groovy: "Gradle",
41
+ };
42
+
43
+ const TEXT_MIMES = new Set([
44
+ "application/json", "application/ld+json", "application/xml", "application/x-yaml",
45
+ "application/yaml", "application/toml", "application/javascript",
46
+ "application/x-javascript", "application/typescript",
47
+ ]);
48
+
49
+ function fileExtension(name) {
50
+ const base = String(name || "").toLowerCase().split(/[\\/]/).pop() || "";
51
+ if (base === "dockerfile" || base === "makefile") return base;
52
+ return /\.([a-z0-9]+)$/.exec(base)?.[1] || "";
53
+ }
54
+
55
+ function isTextMime(mime) {
56
+ if (mime === "text/markdown" || mime === "text/x-markdown") return false;
57
+ return mime.startsWith("text/") || TEXT_MIMES.has(mime);
58
+ }
59
+
60
+ export function docPreviewFormat(resource) {
61
+ const mime = String(resource?.mimeType || "").split(";")[0].trim().toLowerCase();
62
+ const name = String(resource?.name || "");
63
+ const ext = fileExtension(name);
64
+ if (mime === "application/pdf" || ext === "pdf") return { kind: "pdf", language: "", label: "PDF" };
65
+ if (mime === "text/markdown" || mime === "text/x-markdown" || ext === "md" || ext === "markdown") {
66
+ return { kind: "markdown", language: "", label: "" };
67
+ }
68
+ const knownExtension = Object.hasOwn(EXTENSION_LANGUAGES, ext);
69
+ if (!knownExtension && !isTextMime(mime)) return null;
70
+ const language = knownExtension ? EXTENSION_LANGUAGES[ext] : MIME_LANGUAGES[mime] || "";
71
+ return { kind: "text", language, label: LANGUAGE_NAMES[language] || (ext ? ext.toUpperCase() : "Text") };
72
+ }
73
+
74
+ export const isDocPreviewResource = (resource) => docPreviewFormat(resource) !== null;
@@ -322,6 +322,9 @@ export function initRooms(app) {
322
322
  clearTimeout(app.state.watcherTimer);
323
323
  if (!app.state.rooms.size && !app.state.restorePending?.size && !app.state.restoreRetry) return;
324
324
  app.state.watcherTimer = setTimeout(async () => {
325
+ // A hidden tab has no reader; skip background room polling until it is
326
+ // visible again (the next timer tick after visibility resumes).
327
+ if (typeof document !== "undefined" && document.hidden) { app.startRoomWatcher(); return; }
325
328
  const inactive = [...app.state.rooms.keys()].filter((id) => id !== app.state.room?.id);
326
329
  await bounded(inactive, 3, (roomId) => watchRoom(roomId, app));
327
330
  if (app.state.restorePending?.size || app.state.restoreRetry) void app.refreshRoomList(true);
@@ -0,0 +1,87 @@
1
+ // Lazy Shiki highlighting. The bundle is fetched on the first fenced code block,
2
+ // so a conversation without code never downloads or parses it.
3
+
4
+ const LANGUAGE_ALIASES = new Map([
5
+ ["ts", "typescript"], ["typescript", "typescript"],
6
+ ["tsx", "tsx"],
7
+ ["js", "javascript"], ["javascript", "javascript"], ["mjs", "javascript"], ["cjs", "javascript"], ["node", "javascript"],
8
+ ["jsx", "jsx"],
9
+ ["json", "json"], ["jsonc", "json"],
10
+ ["bash", "shellscript"], ["sh", "shellscript"], ["zsh", "shellscript"],
11
+ ["shell", "shellscript"], ["shellscript", "shellscript"], ["console", "shellscript"],
12
+ ["yml", "yaml"], ["yaml", "yaml"],
13
+ ["md", "markdown"], ["markdown", "markdown"],
14
+ ["py", "python"], ["python", "python"],
15
+ ["rs", "rust"], ["rust", "rust"],
16
+ ["go", "go"], ["golang", "go"],
17
+ ["java", "java"],
18
+ ["sql", "sql"],
19
+ ["html", "html"], ["htm", "html"],
20
+ ["xml", "xml"], ["svg", "xml"], ["xsl", "xml"],
21
+ ["css", "css"],
22
+ ]);
23
+
24
+ const pending = new Set();
25
+ let highlighterPromise;
26
+ let failed = false;
27
+ let warned = false;
28
+
29
+ function warnOnce(error) {
30
+ if (warned) return;
31
+ warned = true;
32
+ console.warn("Syntax highlighting unavailable; showing plain code.", error);
33
+ }
34
+
35
+ function getHighlighter() {
36
+ if (failed) return null;
37
+ highlighterPromise ??= import("/assets/shiki.bundle.js")
38
+ .then((module) => module.createHighlighter())
39
+ .catch((error) => {
40
+ failed = true;
41
+ warnOnce(error);
42
+ return null;
43
+ });
44
+ return highlighterPromise;
45
+ }
46
+
47
+ function languageOf(code) {
48
+ return (/language-(\S+)/.exec(code.className) || [])[1]?.toLowerCase() || "";
49
+ }
50
+
51
+ // Returns Shiki's HTML (it escapes the code text) or null for an unknown or failed language.
52
+ export async function highlightToHtml(code, lang) {
53
+ const language = LANGUAGE_ALIASES.get(String(lang || "").toLowerCase());
54
+ if (!language) return null;
55
+ try {
56
+ const highlighter = await getHighlighter();
57
+ if (!highlighter) return null;
58
+ return highlighter.codeToHtml(code, { lang: language, theme: "chatroom" });
59
+ } catch (error) {
60
+ warnOnce(error);
61
+ return null;
62
+ }
63
+ }
64
+
65
+ export function whenShikiIdle() {
66
+ return Promise.allSettled([...pending]);
67
+ }
68
+
69
+ // Replaces the escaped text inside one code element, leaving the surrounding
70
+ // pre, toolbar, wrap state, and copy button alone.
71
+ export function enhanceCodeElement(code) {
72
+ const task = embed(code).catch(() => {}).finally(() => pending.delete(task));
73
+ pending.add(task);
74
+ return task;
75
+ }
76
+
77
+ async function embed(code) {
78
+ if (!LANGUAGE_ALIASES.has(languageOf(code))) return;
79
+ const markup = await highlightToHtml(code.textContent || "", languageOf(code));
80
+ if (!markup || !code.isConnected) return;
81
+ const template = document.createElement("template");
82
+ template.innerHTML = markup;
83
+ const rendered = template.content.querySelector("code");
84
+ if (!rendered) return;
85
+ code.replaceChildren(...rendered.childNodes);
86
+ code.classList.add("shiki");
87
+ }
@@ -0,0 +1,143 @@
1
+ // Resizes the right-hand pane (Markdown preview or task board) on wide windows.
2
+ // --side-pane-width holds the only width; the rail keeps its 252px column and the
3
+ // chat column never shrinks below MIN_CHAT.
4
+ const STORAGE_KEY = "chat.sidePaneWidth";
5
+ const MIN_WIDTH = 360;
6
+ const MIN_CHAT = 420;
7
+ const WIDE_TASKS_MIN_CHAT = 700;
8
+ const RAIL_WIDTH = 252;
9
+ const GUTTER = 8;
10
+ const MAX_WIDTH = 960;
11
+
12
+ export function initSidePaneSplitter(app) {
13
+ const view = app.$("#chatView");
14
+ const handle = app.$("#sidePaneHandle");
15
+ const preview = app.$("#docPreview");
16
+ const tasks = app.$("#tasksDialog");
17
+ if (!view || !handle) return;
18
+
19
+ let stored = readStored();
20
+ let applied = 0;
21
+ let frame = 0;
22
+ let pending = 0;
23
+ let drag = null;
24
+
25
+ const activePane = () => view.classList.contains("has-doc") ? preview
26
+ : view.classList.contains("has-tasks") ? tasks : null;
27
+
28
+ // A wide task board must leave the conversation a full working column; the
29
+ // Markdown preview keeps the normal minimum.
30
+ const wideTasks = () => view.classList.contains("has-tasks") && !view.classList.contains("has-doc")
31
+ && window.matchMedia("(min-width: 1500px) and (min-height: 900px)").matches;
32
+ const minChat = () => wideTasks() ? WIDE_TASKS_MIN_CHAT : MIN_CHAT;
33
+
34
+ const maxWidth = () => {
35
+ const available = view.clientWidth - RAIL_WIDTH - GUTTER - minChat();
36
+ return Math.max(MIN_WIDTH, Math.min(window.innerWidth * 0.7, MAX_WIDTH, available));
37
+ };
38
+ const clamp = (width) => Math.max(MIN_WIDTH, Math.min(width, maxWidth()));
39
+
40
+ const syncAria = () => {
41
+ handle.setAttribute("aria-valuemin", String(MIN_WIDTH));
42
+ handle.setAttribute("aria-valuemax", String(Math.round(maxWidth())));
43
+ const pane = activePane();
44
+ if (pane?.open) {
45
+ handle.setAttribute("aria-valuenow", String(Math.round(pane.getBoundingClientRect().width)));
46
+ }
47
+ };
48
+
49
+ const apply = (width) => {
50
+ applied = Math.round(width);
51
+ view.style.setProperty("--side-pane-width", `${applied}px`);
52
+ syncAria();
53
+ };
54
+
55
+ // Pane classes change on open, close, and breakpoint switches; the hidden
56
+ // attribute changes when the workspace first appears.
57
+ const reflow = () => {
58
+ if (!view.clientWidth) return;
59
+ if (stored == null) syncAria();
60
+ else apply(clamp(stored));
61
+ };
62
+
63
+ const setWidth = (width) => {
64
+ const next = clamp(width);
65
+ apply(next);
66
+ return next;
67
+ };
68
+
69
+ const persist = (width) => {
70
+ stored = Math.round(width);
71
+ try { localStorage.setItem(STORAGE_KEY, String(stored)); } catch { /* The width still applies for this page. */ }
72
+ };
73
+
74
+ handle.addEventListener("pointerdown", (event) => {
75
+ const pane = activePane();
76
+ if (event.button !== 0 || !pane?.open) return;
77
+ drag = { pointerId: event.pointerId, x: event.clientX, width: pane.getBoundingClientRect().width };
78
+ applied = Math.round(drag.width);
79
+ pending = drag.width;
80
+ handle.setPointerCapture(event.pointerId);
81
+ handle.classList.add("is-dragging");
82
+ document.body.classList.add("is-resizing-pane");
83
+ handle.focus({ preventScroll: true });
84
+ });
85
+
86
+ handle.addEventListener("pointermove", (event) => {
87
+ if (!drag || event.pointerId !== drag.pointerId) return;
88
+ // Dragging left widens the right-hand pane; the divider follows the pointer.
89
+ pending = clamp(drag.width - (event.clientX - drag.x));
90
+ if (frame) return;
91
+ frame = requestAnimationFrame(() => {
92
+ frame = 0;
93
+ apply(pending);
94
+ });
95
+ });
96
+
97
+ const endDrag = (event) => {
98
+ if (!drag || event.pointerId !== drag.pointerId) return;
99
+ if (frame) { cancelAnimationFrame(frame); frame = 0; }
100
+ apply(pending);
101
+ persist(applied);
102
+ drag = null;
103
+ handle.classList.remove("is-dragging");
104
+ document.body.classList.remove("is-resizing-pane");
105
+ if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId);
106
+ };
107
+ handle.addEventListener("pointerup", endDrag);
108
+ handle.addEventListener("pointercancel", endDrag);
109
+
110
+ handle.addEventListener("keydown", (event) => {
111
+ if (!activePane()?.open) return;
112
+ const current = activePane().getBoundingClientRect().width;
113
+ const step = event.shiftKey ? 64 : 16;
114
+ let next;
115
+ if (event.key === "ArrowRight") next = current - step;
116
+ else if (event.key === "ArrowLeft") next = current + step;
117
+ else if (event.key === "Home") next = MIN_WIDTH;
118
+ else if (event.key === "End") next = maxWidth();
119
+ else return;
120
+ event.preventDefault();
121
+ persist(setWidth(next));
122
+ });
123
+
124
+ handle.addEventListener("dblclick", () => {
125
+ stored = null;
126
+ try { localStorage.removeItem(STORAGE_KEY); } catch { /* Ignore unavailable storage. */ }
127
+ view.style.removeProperty("--side-pane-width");
128
+ syncAria();
129
+ });
130
+
131
+ window.addEventListener("resize", reflow);
132
+ new MutationObserver(reflow).observe(view, { attributes: true, attributeFilter: ["class", "hidden"] });
133
+ reflow();
134
+ }
135
+
136
+ function readStored() {
137
+ try {
138
+ const width = Number(localStorage.getItem(STORAGE_KEY));
139
+ return Number.isFinite(width) && width > 0 ? width : null;
140
+ } catch {
141
+ return null;
142
+ }
143
+ }