@alexsun-top/opencode-chat-room 0.7.2 → 0.7.4

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 (77) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +11 -4
  3. package/README.zh-CN.md +11 -4
  4. package/cli.ts +26 -6
  5. package/dist/cli.js +7804 -0
  6. package/package.json +19 -6
  7. package/plugin.ts +7 -4
  8. package/server/admin-auth.ts +1 -1
  9. package/server/admin-routes.ts +2 -2
  10. package/server/admin-state.ts +2 -1
  11. package/server/assets/chat/admin.js +43 -3
  12. package/server/assets/chat/announcements.js +5 -3
  13. package/server/assets/chat/confirm-dialog.js +12 -2
  14. package/server/assets/chat/create-room-dialog.js +5 -3
  15. package/server/assets/chat/events.js +32 -7
  16. package/server/assets/chat/files.js +368 -0
  17. package/server/assets/chat/index.js +6 -0
  18. package/server/assets/chat/locales/de.js +17 -1
  19. package/server/assets/chat/locales/es.js +17 -1
  20. package/server/assets/chat/locales/fr.js +17 -1
  21. package/server/assets/chat/locales/it.js +17 -1
  22. package/server/assets/chat/locales/ja.js +17 -1
  23. package/server/assets/chat/locales/ko.js +17 -1
  24. package/server/assets/chat/markdown.js +10 -3
  25. package/server/assets/chat/message-polling.js +61 -6
  26. package/server/assets/chat/message-window.js +28 -0
  27. package/server/assets/chat/messages.js +29 -4
  28. package/server/assets/chat/palette.js +384 -0
  29. package/server/assets/chat/rooms.js +8 -3
  30. package/server/assets/chat/search.js +137 -0
  31. package/server/assets/chat/settings.js +11 -5
  32. package/server/assets/chat/state.js +34 -2
  33. package/server/assets/code-highlight.css +2 -5
  34. package/server/assets/edit-room.css +77 -0
  35. package/server/assets/files.css +237 -0
  36. package/server/assets/palette.css +277 -0
  37. package/server/assets/responsive.css +3 -2
  38. package/server/assets/room-create.css +42 -43
  39. package/server/assets/settings.css +6 -3
  40. package/server/chat-server.ts +46 -29
  41. package/server/chat.html +129 -33
  42. package/server/http-server.ts +182 -0
  43. package/server/join-requests.ts +5 -4
  44. package/server/manifest.webmanifest +1 -1
  45. package/server/member-routes.ts +3 -3
  46. package/server/message-recall-routes.ts +1 -1
  47. package/server/newrooms.ts +4 -4
  48. package/server/resource-routes.ts +19 -4
  49. package/server/room-join.ts +8 -3
  50. package/server/room-payload.ts +1 -1
  51. package/server/sw.js +3 -0
  52. package/server/wake.ts +1 -1
  53. package/skills/chatroom/SKILL.md +1 -1
  54. package/src/README.md +4 -2
  55. package/src/config/file-config.ts +294 -0
  56. package/src/rooms/resource-read.ts +2 -1
  57. package/src/rooms/resource-upload.ts +6 -3
  58. package/src/rooms/resources.ts +7 -2
  59. package/src/runtime/v2-plugin.ts +2 -2
  60. package/src/runtime/watch.ts +13 -8
  61. package/src/state/receiver-state.ts +3 -5
  62. package/src/state/sqlite-state.ts +11 -7
  63. package/src/state/sqlite.ts +80 -0
  64. package/src/state/store.ts +1 -0
  65. package/src/tui/app.mjs +417 -0
  66. package/src/tui/config.mjs +194 -0
  67. package/src/tui/http.mjs +103 -0
  68. package/src/tui/main.mjs +176 -0
  69. package/src/tui/messages.mjs +67 -0
  70. package/src/tui/palette-app.mjs +265 -0
  71. package/src/tui/palette.mjs +101 -0
  72. package/src/tui/session.mjs +40 -0
  73. package/src/tui/ui-content.mjs +426 -0
  74. package/src/tui/ui-theme.mjs +60 -0
  75. package/src/tui/ui-view.mjs +452 -0
  76. package/src/tui/ui.mjs +262 -0
  77. package/src/tests/announcement-board.ts +0 -186
@@ -27,7 +27,7 @@ export const ko = {
27
27
  tokenPlaceholder: "서버에서 요구하는 경우 입력", save: "저장",
28
28
  tokenHint: "서버가 액세스 토큰을 요구하면(401) 모든 요청에 포함됩니다.",
29
29
  existingRooms: "방", noRooms: "아직 방이 없습니다. 하나 만들어 보세요.", copyRoomId: "방 ID 복사", loadingHistory: "이전 메시지 불러오는 중",
30
- editRoom: "방 편집", roomOwnerOnlyTitle: "소유자 또는 관리자만", roomOwnerOnlyNote: ({ owner }) => `이 설정은 방 소유자나 방 관리자만 변경할 수 있습니다. 이 방의 소유자는 ${owner} 님입니다.`, roomNameLabel: "방 이름", roomDescriptionLabel: "설명", adminAgentLabel: "관리자 Agent", roomOwnerBadge: "소유자", roomAdminBadge: "관리자",
30
+ editRoom: "방 편집", editRoomSections: "방 편집 섹션", editRoomDetails: "방 정보", editRoomJoining: "참여 및 승인", editRoomMembers: "멤버 및 역할", editRoomOwnership: "소유권", roomOwnerOnlyTitle: "소유자 또는 관리자만", roomOwnerOnlyNote: ({ owner }) => `이 설정은 방 소유자나 방 관리자만 변경할 수 있습니다. 이 방의 소유자는 ${owner} 님입니다.`, roomNameLabel: "방 이름", roomDescriptionLabel: "설명", adminAgentLabel: "관리자 Agent", roomOwnerBadge: "소유자", roomAdminBadge: "관리자",
31
31
  adminIdsLabel: "사람 관리자", adminIdsHint: "이 멤버들은 방 정보 편집, 멤버 관리, 파일 삭제, 후임자 지정을 할 수 있습니다. 소유자는 항상 같은 권한을 가집니다.", adminIdsEmpty: "이 방에는 아직 다른 멤버가 없습니다.", newOwnerLabel: "새 소유자", newOwnerHint: "방을 참여 중인 다른 사람에게 넘깁니다. 소유자만 할 수 있으며 Agent는 소유자가 될 수 없습니다.",
32
32
  successorLabel: "소유자가 나갈 때의 후임자", successorNone: "가장 오래 참여한 멤버", successorHint: "소유자가 나가면 이 사람이 소유자가 됩니다. 관리자가 나가면 이 사람이 그 역할을 이어받습니다. 비워 두면 가장 오래 참여한 멤버가 됩니다.", ownerOnlySettingsNote: "관리자 Agent 변경과 방 넘기기는 소유자만 할 수 있습니다.", adminAgentHint: "지정된 Agent는 관리 도구로 이 방과 기록을 확인할 수 있습니다. 소유자만 변경할 수 있으며 비워 두면 없음입니다.",
33
33
  noAdminAgent: "없음", roomNameRequired: "방 이름을 입력하세요", openQuestions: ({ count }) => `답변 없는 질문 ${count}개`,
@@ -82,6 +82,21 @@ export const ko = {
82
82
  shortcutsSwitchRoom: "이전 또는 다음 방으로 전환", shortcutsNumberRoom: "번호로 참여 중인 방으로 전환", shortcutsReading: "읽기",
83
83
  shortcutsScroll: "입력 중에 메시지 스크롤", shortcutsJump: "대화의 시작이나 끝으로 이동", shortcutsMenus: "메뉴 및 대화 상자",
84
84
  shortcutsClose: "열린 메뉴, 패널 또는 대화 상자 닫기",
85
+ paletteTitle: "검색 및 명령", paletteSearchLabel: "메시지 검색",
86
+ palettePlaceholder: "메시지를 검색하거나 > 로 명령 사용", paletteScopeRoom: "이 방", paletteScopeAll: "모든 방",
87
+ paletteScopeHint: "Tab 키로 이 방과 참여 중인 모든 방을 전환합니다", paletteSearchMode: "검색", paletteCommandMode: "명령",
88
+ paletteSearching: "검색 중…", paletteNoResults: "메시지를 찾지 못했습니다.", paletteNoCommands: "일치하는 명령이 없습니다.",
89
+ paletteResults: ({ count }) => `결과 ${count}개`, paletteCommandsHint: "자주 쓰는 명령",
90
+ paletteHint: "↑↓ 선택 · Enter 열기 · Tab 범위 전환 · Esc 닫기", paletteSearchFailed: "검색에 실패했습니다. 다시 시도해 주세요.",
91
+ paletteLeaveRoom: "방 나가기", paletteJumpLatest: "최신으로 이동",
92
+ filesTitle: "파일", filesEyebrow: "방 파일", filesFilter: "업로더", filesEveryone: "모두",
93
+ filesUnknownUploader: "알 수 없는 업로더", filesSummary: ({ count, size }) => `${count}개 파일 · ${size}`,
94
+ filesLoading: "파일을 불러오는 중…", filesLoadFailed: "파일을 불러오지 못했습니다. 다시 시도해 주세요.", filesEmpty: "이 방에는 아직 파일이 없습니다.",
95
+ filesEmptyFiltered: "이 업로더의 파일이 없습니다.", filesLoadMore: "더 불러오기",
96
+ filesHint: "이미지, 오디오, 동영상을 미리 볼 수 있습니다. 모든 파일을 다운로드할 수 있습니다.",
97
+ filesPreviewFailed: "미리보기를 불러오지 못했습니다.", filesDownloadFailed: "이 파일을 다운로드하지 못했습니다.",
98
+ filesPreviewLabel: ({ name }) => `${name} 미리보기`, filesDownloadLabel: ({ name }) => `${name} 다운로드`,
99
+ filesDeleteLabel: ({ name }) => `${name} 삭제`, filesRefresh: "파일 새로고침",
85
100
  earlierMessages: "이전 메시지는 생략됨", messagesBetweenOmitted: "이 읽기 지점과 최신 메시지 사이는 생략되었습니다.", you: "나", saved: "저장됨",
86
101
  savedMemory: "이 탭에만 저장됨", copyFailed: ({ id }) => `복사하지 못했습니다. 직접 복사하세요: ${id}`,
87
102
  copyMessage: "복사", copiedMessage: "복사됨", copyMessageFailed: "복사하지 못했습니다. 메시지를 선택해 직접 복사하세요.", wrapCode: "코드 줄 바꿈",
@@ -103,6 +118,7 @@ export const ko = {
103
118
  roomsMenu: "방 목록 열기", closeRoomList: "방 목록 닫기",
104
119
  direct: "다이렉트", messagePrivately: "비공개 메시지", removeMember: "추방",
105
120
  kickConfirm: ({ name }) => `${name} 님을 이 방에서 추방할까요? 방 ID로 다시 참여할 수 있습니다.`,
121
+ leaveRoomConfirm: ({ name }) => `“${name}” 방에서 나갈까요? 이 방을 나가게 되며, 나중에 방 ID로 다시 참여할 수 있습니다.`,
106
122
  deleteRoom: "방 삭제", deleteConfirm: ({ name }) => `“${name}” 방과 모든 메시지를 삭제할까요? 되돌릴 수 없습니다.`,
107
123
  allMembers: "모두", messageCount: ({ count }) => `${count} / 5000`,
108
124
  pasteAsFile: ({ count }) => `붙여넣은 ${count}자를 텍스트 파일로 저장했습니다`,
@@ -56,6 +56,13 @@ function decorateCodeBlock(code, app) {
56
56
  block.className = "code-block";
57
57
  pre.replaceWith(block);
58
58
  block.append(pre, codeToolbar(code, pre, block, app));
59
+ // Touch screens have no hover: a tapped code block keeps focus so its toolbar stays reachable.
60
+ if (window.matchMedia("(pointer: coarse)").matches) {
61
+ block.tabIndex = 0;
62
+ block.addEventListener("pointerdown", (event) => {
63
+ if (!event.target.closest?.(".code-tool-button")) block.focus({ preventScroll: true });
64
+ });
65
+ }
59
66
  }
60
67
 
61
68
  function highlightCode(code) {
@@ -76,8 +83,8 @@ function codeToolbar(code, pre, block, app) {
76
83
  wrap.setAttribute("aria-pressed", "false");
77
84
  wrap.addEventListener("click", (event) => {
78
85
  event.stopPropagation();
79
- // A pointer click should not pin the toolbar open; hovering is enough.
80
- if (event.detail > 0) wrap.blur();
86
+ // A pointer click should not pin the toolbar open; hovering is enough on desktop, focus on touch.
87
+ if (event.detail > 0 && !matchMedia("(pointer: coarse)").matches) wrap.blur();
81
88
  const wrapped = !block.classList.contains("is-wrapped");
82
89
  if (wrapped) block._codeScrollLeft = pre.scrollLeft;
83
90
  block.classList.toggle("is-wrapped", wrapped);
@@ -87,7 +94,7 @@ function codeToolbar(code, pre, block, app) {
87
94
  const copy = codeToolButton("code-copy-button", "copyMessage", app, copyIcon(), checkIcon());
88
95
  copy.addEventListener("click", (event) => {
89
96
  event.stopPropagation();
90
- if (event.detail > 0) copy.blur();
97
+ if (event.detail > 0 && !matchMedia("(pointer: coarse)").matches) copy.blur();
91
98
  void copyCode(copy, code, app);
92
99
  });
93
100
  toolbar.append(wrap, copy);
@@ -5,14 +5,63 @@ import { setRoomPreview } from "./system-messages.js";
5
5
  export function initMessagePolling(app, isUnreadMessage) {
6
6
  const $ = app.$;
7
7
  let pollDelay = 2000;
8
+ let recoveryTimer = null;
9
+ let recoveryRoom = null;
10
+ let recoveryGeneration = 0;
8
11
 
9
- // A restarted network can leave the browser's old request hanging. Retry at
12
+ // A hung long-poll cannot notice that the network came back. Probe separately
13
+ // so the connection bar clears as soon as any authenticated request succeeds.
14
+ function stopRecovery() {
15
+ if (recoveryTimer) clearTimeout(recoveryTimer);
16
+ recoveryTimer = null;
17
+ recoveryRoom = null;
18
+ recoveryGeneration = 0;
19
+ }
20
+ function scheduleRecovery(immediate = false) {
21
+ const roomId = app.state.room?.id;
22
+ if (!app.state.polling || !roomId) return;
23
+ if (recoveryTimer && recoveryRoom === roomId) {
24
+ if (!immediate) return;
25
+ clearTimeout(recoveryTimer);
26
+ } else stopRecovery();
27
+ recoveryRoom = roomId;
28
+ recoveryGeneration = app.state.pollGeneration;
29
+ recoveryTimer = setTimeout(() => { void probeRecovery(roomId, recoveryGeneration); }, immediate ? 0 : 2000);
30
+ }
31
+ async function probeRecovery(roomId, generation) {
32
+ recoveryTimer = null;
33
+ if (!app.state.polling || app.state.room?.id !== roomId || app.state.pollGeneration !== generation) { stopRecovery(); return; }
34
+ const controller = new AbortController();
35
+ const timer = setTimeout(() => controller.abort(), 3000);
36
+ try {
37
+ await app.api(`/rooms/${encodeURIComponent(roomId)}`, { signal: controller.signal });
38
+ if (!app.state.polling || app.state.room?.id !== roomId || app.state.pollGeneration !== generation) { stopRecovery(); return; }
39
+ app.setOnline(true);
40
+ stopRecovery();
41
+ pollDelay = 2000;
42
+ app.startPolling();
43
+ } catch (error) {
44
+ if (!app.state.polling || app.state.room?.id !== roomId || app.state.pollGeneration !== generation) { stopRecovery(); return; }
45
+ if (error.status === 404) {
46
+ stopRecovery();
47
+ void app.removeJoinedRoom(roomId, { reason: true });
48
+ return;
49
+ }
50
+ if (error.status === 401) {
51
+ stopRecovery();
52
+ app.setOnline(false);
53
+ if (!app.settingsOpen()) app.openChatSettings();
54
+ return;
55
+ }
56
+ recoveryTimer = setTimeout(() => { void probeRecovery(roomId, generation); }, 2000);
57
+ } finally {
58
+ clearTimeout(timer);
59
+ }
60
+ }
61
+
62
+ // A restarted network can leave the browser's old request hanging. Probe at
10
63
  // once instead of waiting for the long-poll timeout.
11
- window.addEventListener("online", () => {
12
- if (!app.state.polling || !app.state.room) return;
13
- pollDelay = 2000;
14
- app.startPolling();
15
- });
64
+ window.addEventListener("online", () => scheduleRecovery(true));
16
65
 
17
66
  function isCurrentPoll(roomId, generation) {
18
67
  return app.state.polling && app.state.pollGeneration === generation && app.state.room?.id === roomId;
@@ -32,6 +81,7 @@ export function initMessagePolling(app, isUnreadMessage) {
32
81
  app.state.pollGeneration++;
33
82
  app.state.pollController?.abort();
34
83
  app.state.pollController = null;
84
+ stopRecovery();
35
85
  };
36
86
 
37
87
  async function pollLoop(generation, signal) {
@@ -121,10 +171,12 @@ export function initMessagePolling(app, isUnreadMessage) {
121
171
  void app.reconcileRoom(roomId, generation);
122
172
  }
123
173
  app.setOnline(true);
174
+ stopRecovery();
124
175
  pollDelay = data.hasMore && (entry?.receivedTs || 0) > previousReceivedTs ? 0 : 2000;
125
176
  } catch (error) {
126
177
  if (!isCurrentPoll(roomId, generation)) return;
127
178
  if (error.status === 401) {
179
+ stopRecovery();
128
180
  app.setOnline(false);
129
181
  if (!app.settingsOpen()) app.openChatSettings();
130
182
  pollDelay = Math.min(pollDelay * 2, 30000);
@@ -133,6 +185,7 @@ export function initMessagePolling(app, isUnreadMessage) {
133
185
  } else {
134
186
  app.setOnline(false);
135
187
  pollDelay = 2000;
188
+ if (error.network || error.name === "AbortError" || error.name === "TimeoutError") scheduleRecovery();
136
189
  }
137
190
  }
138
191
  }
@@ -142,6 +195,7 @@ export function initMessagePolling(app, isUnreadMessage) {
142
195
  try {
143
196
  const room = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
144
197
  if (!isCurrentPoll(roomId, generation)) return;
198
+ app.setOnline(true);
145
199
  const before = JSON.stringify([app.state.room.ownerId, app.state.room.adminIds ?? [], app.state.room.successorId ?? null, app.state.room.adminSessionID ?? null]);
146
200
  const openQuestions = Number(room.openQuestions);
147
201
  Object.assign(app.state.room, { participants: room.participants, ownerId: room.ownerId ?? app.state.room.ownerId, adminIds: room.adminIds ?? [], successorId: room.successorId ?? null, adminSessionID: room.adminSessionID ?? null, openQuestions: Number.isFinite(openQuestions) ? Math.max(0, openQuestions) : app.state.room.openQuestions });
@@ -156,6 +210,7 @@ export function initMessagePolling(app, isUnreadMessage) {
156
210
  try {
157
211
  const room = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
158
212
  if (!isCurrentPoll(roomId, generation)) return;
213
+ app.setOnline(true);
159
214
  if (entry && Number.isFinite(Number(room.recallVersion))) entry.recallVersion = Number(room.recallVersion);
160
215
  const current = app.state.room.messages;
161
216
  const ids = new Set(current.map((message) => message.id));
@@ -26,8 +26,36 @@ export function followsBottom(app, threshold = -1) {
26
26
  return Boolean(app.state.followBottom || (thread && thread.scrollHeight - thread.scrollTop - thread.clientHeight <= threshold));
27
27
  }
28
28
 
29
+ // A search jump parks one row near the top of the thread and flashes it briefly.
30
+ export function flashMessageRow(app, row) {
31
+ const thread = document.querySelector("#thread");
32
+ thread.scrollTop += row.getBoundingClientRect().top - (thread.getBoundingClientRect().top + thread.clientTop) - 12;
33
+ app.state.followBottom = false;
34
+ // Keep a programmatic search jump from being mistaken for the reader returning to the tail.
35
+ app.state.focusHoldUntil = performance.now() + 900;
36
+ clearTimeout(row._jumpFlashTimer);
37
+ row.classList.remove("jump-flash");
38
+ void row.offsetWidth;
39
+ row.classList.add("jump-flash");
40
+ row._jumpFlashTimer = setTimeout(() => row.classList.remove("jump-flash"), 900);
41
+ app.updateJump?.();
42
+ }
43
+
44
+ // Resolve app.state.focusMessageId against the loaded state and rendered rows.
45
+ export function focusedMessage(app, list, messages) {
46
+ const id = app.state.focusMessageId;
47
+ if (!id) return null;
48
+ const index = messages.findIndex((message) => message.id === id);
49
+ if (index < 0) { app.state.focusMessageId = null; return null; }
50
+ return { id, index, existing: list.querySelector(`[data-msg-id="${CSS.escape(id)}"]`) };
51
+ }
52
+
29
53
  export function trimMessages(list, app) {
30
54
  if (list.children.length <= 400 || hasMessageSelection(list)) return;
55
+ // Trimming removes content above the reader. While they are browsing older
56
+ // history that would shift the viewport, so only trim near the newest tail.
57
+ const thread = document.querySelector("#thread");
58
+ if (thread && thread.scrollHeight - thread.scrollTop - thread.clientHeight > 80) return;
31
59
  const saved = app.state.positions.get(app.state.room?.id), rows = [...list.querySelectorAll("[data-msg-id]")];
32
60
  const anchor = saved?.messageId && rows.find((row) => row.dataset.msgId === saved.messageId);
33
61
  if (anchor && rows.indexOf(anchor) < rows.length - 280) {
@@ -1,6 +1,6 @@
1
1
  import { createRandomId, LS, LOADED_MESSAGE_LIMIT } from "./state.js";
2
2
  import { renderMarkdown } from "./markdown.js";
3
- import { hasMessageSelection, pruneMessageRows, trimMessages } from "./message-window.js";
3
+ import { hasMessageSelection, pruneMessageRows, trimMessages, focusedMessage } from "./message-window.js";
4
4
  import { formatSystemMessage, setRoomPreview } from "./system-messages.js";
5
5
  import { installEditor } from "./editor.js";
6
6
  import { adminAgentBadge, isAdminAgent } from "./admin-badge.js";
@@ -102,6 +102,10 @@ export function initMessages(app) {
102
102
  app.jumpToBottom = () => {
103
103
  app.state.readAnchorGuard = null;
104
104
  app.state.followBottom = true;
105
+ if (app.state.focusMessageId) {
106
+ app.state.focusMessageId = null;
107
+ app.rerenderMessages();
108
+ }
105
109
  $("#thread").scrollTop = $("#thread").scrollHeight;
106
110
  const entry = app.state.room && app.state.rooms.get(app.state.room.id);
107
111
  app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
@@ -188,6 +192,11 @@ export function initMessages(app) {
188
192
  }
189
193
  };
190
194
 
195
+ // Today keeps the compact clock; older messages carry the date because the
196
+ // day separator scrolls away or gets trimmed.
197
+ app.messageTime = (timestamp) => new Date(timestamp).toDateString() === new Date().toDateString()
198
+ ? app.timeHM(timestamp) : app.fmtTime(timestamp);
199
+
191
200
  app.renderMessage = (message, live) => {
192
201
  const row = document.createElement("li");
193
202
  row.dataset.sender = message.senderId;
@@ -210,7 +219,7 @@ export function initMessages(app) {
210
219
  name.className = "msg-name";
211
220
  name.textContent = own ? app.t("you") : sender;
212
221
  time.className = "msg-time";
213
- time.textContent = app.timeHM(message.createdAt);
222
+ time.textContent = app.messageTime(message.createdAt);
214
223
  meta.append(name);
215
224
  if (isAdminAgent(app, message.senderSessionID || message.senderId)) meta.append(adminAgentBadge(app));
216
225
  meta.append(time);
@@ -253,20 +262,33 @@ export function initMessages(app) {
253
262
 
254
263
  app.renderMessages = (live = false) => {
255
264
  const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
256
- const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 80;
265
+ // A palette jump renders a window around the target instead of the newest
266
+ // tail. While that window is up, live appends stay off screen so the target
267
+ // is not trimmed away.
268
+ const focus = focusedMessage(app, list, messages);
269
+ if (focus?.existing) { app.updateJump(); return { skipped: 0 }; }
270
+ const nearBottom = !focus && thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 80;
257
271
  let skipped = 0;
258
272
  let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
259
273
  const viewport = thread.getBoundingClientRect();
260
274
  const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
261
275
  anchorId = firstVisible?.dataset.msgId || null;
262
276
  anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
277
+ if (focus) {
278
+ // Start a fresh window containing the target, wherever it sits in the
279
+ // loaded state (which can hold up to LOADED_MESSAGE_LIMIT messages).
280
+ list.textContent = "";
281
+ app.rendered = 0;
282
+ }
263
283
  pruneMessageRows(list, messages);
264
284
  let last = list.lastElementChild;
265
285
  const renderedIds = new Set([...list.querySelectorAll("[data-msg-id]")].map((node) => node.dataset.msgId));
266
286
  let startIndex = 0;
267
287
  const lastId = [...list.querySelectorAll("[data-msg-id]")].at(-1)?.dataset.msgId;
268
288
  if (lastId) for (let index = messages.length - 1; index >= 0; index--) if (messages[index].id === lastId) { startIndex = index + 1; break; }
269
- for (let index = startIndex; index < messages.length; index++) {
289
+ const renderStart = focus ? Math.max(0, focus.index - 120) : startIndex;
290
+ const renderEnd = focus ? Math.min(messages.length, focus.index + 120) : messages.length;
291
+ for (let index = renderStart; index < renderEnd; index++) {
270
292
  const message = messages[index];
271
293
  if (renderedIds.has(message.id) || app.failedRenderIds.has(message.id)) continue;
272
294
  try {
@@ -378,6 +400,9 @@ export function initMessages(app) {
378
400
  else updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
379
401
  method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text, ...(replyTarget ? { replyToMessageID: replyTarget.id } : {}) }),
380
402
  });
403
+ // A successful request proves the connection is usable, even if a stale
404
+ // long-poll is still waiting to time out.
405
+ app.setOnline(true);
381
406
  app.completeAttachments?.(room.id, message.ids);
382
407
  const pendingIndex = room.messages.findIndex((item) => item.id === pending.id);
383
408
  if (pendingIndex >= 0) room.messages.splice(pendingIndex, 1);