@alexsun-top/opencode-chat-room 0.5.1 → 0.5.3

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 (49) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +28 -207
  3. package/README.zh-CN.md +27 -201
  4. package/docs/administrator-rooms.md +6 -22
  5. package/package.json +4 -5
  6. package/plugin.ts +19 -4
  7. package/server/admin-routes.ts +2 -11
  8. package/server/admin-state.ts +15 -4
  9. package/server/assets/base.css +10 -0
  10. package/server/assets/chat/admin.js +67 -128
  11. package/server/assets/chat/attachments.js +1 -1
  12. package/server/assets/chat/editor.js +248 -0
  13. package/server/assets/chat/events.js +13 -11
  14. package/server/assets/chat/index.js +4 -0
  15. package/server/assets/chat/mentions.js +38 -28
  16. package/server/assets/chat/message-window.js +18 -0
  17. package/server/assets/chat/messages.js +49 -57
  18. package/server/assets/chat/questions.js +115 -43
  19. package/server/assets/chat/receipts.js +0 -1
  20. package/server/assets/chat/reminders.js +102 -0
  21. package/server/assets/chat/replies.js +150 -0
  22. package/server/assets/chat/room-watcher.js +37 -0
  23. package/server/assets/chat/rooms.js +59 -70
  24. package/server/assets/chat/state.js +29 -9
  25. package/server/assets/conversation.css +33 -9
  26. package/server/assets/responsive.css +15 -16
  27. package/server/chat-server.ts +21 -2
  28. package/server/chat.html +23 -13
  29. package/server/inbox.ts +5 -1
  30. package/server/room-reminders.ts +222 -0
  31. package/server/wake.ts +6 -3
  32. package/skills/chatroom/SKILL.md +11 -7
  33. package/src/admin-client.ts +6 -43
  34. package/src/admin-credentials.ts +0 -19
  35. package/src/agent-receipts.ts +13 -18
  36. package/src/mentions.ts +2 -1
  37. package/src/plugin-notifications.ts +4 -0
  38. package/src/queue.ts +7 -2
  39. package/src/reminder-client.ts +50 -0
  40. package/src/resource-read.ts +118 -0
  41. package/src/resource-upload.ts +1 -1
  42. package/src/resources.ts +1 -1
  43. package/src/sqlite-state.ts +43 -3
  44. package/src/store.ts +22 -8
  45. package/src/supervision-inbox.ts +6 -18
  46. package/src/v2-plugin.ts +11 -5
  47. package/server/admin-plan-routes.ts +0 -79
  48. package/server/admin-scheduler.ts +0 -42
  49. package/server/admin-task-routes.ts +0 -182
@@ -34,18 +34,25 @@
34
34
 
35
35
  .chat-head-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
36
36
  .chat-head .action-icon { width: 19px; height: 19px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.8; }
37
- .question-panel { width: min(390px, calc(100vw - 32px)); max-height: min(70vh, 620px); overflow: auto; }
37
+ .panel.question-panel { width: min(720px, calc(100vw - 32px)); max-height: min(86vh, 820px); overflow: auto; }
38
38
  .questions-trigger { position: relative; }
39
39
  .question-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
40
40
  .question-panel-head h3 { margin-bottom: 0; }
41
41
  .question-refresh { border: 0; padding: 4px 7px; color: var(--accent); background: transparent; font: inherit; font-size: 12px; cursor: pointer; }
42
- .question-list { list-style: none; max-height: 260px; overflow: auto; margin: 10px 0 0; padding: 0; }
43
- .question-item { width: 100%; padding: 9px 10px; border: 1px solid transparent; border-radius: 9px; color: var(--ink); background: transparent; font: inherit; font-size: 13px; line-height: 1.5; text-align: left; overflow-wrap: anywhere; cursor: pointer; }
44
- .question-item:hover, .question-item[aria-pressed="true"] { border-color: color-mix(in srgb, var(--accent) 30%, var(--line)); background: var(--accent-soft); }
42
+ .question-list { list-style: none; max-height: 40vh; overflow: auto; margin: 10px 0 0; padding: 0; }
43
+ .question-item { display: grid; gap: 8px; padding: 11px 12px; border: 1px solid var(--line); border-radius: 12px; color: var(--ink); background: var(--surface-2); font-size: 15px; line-height: 1.6; overflow-wrap: anywhere; cursor: pointer; }
44
+ .question-item-body { min-width: 0; }
45
+ .question-item:hover, .question-item.selected { border-color: color-mix(in srgb, var(--accent) 30%, var(--line)); background: var(--accent-soft); }
46
+ .question-select { justify-self: end; border: 0; padding: 3px 5px; color: var(--accent); background: transparent; font: inherit; font-size: 12px; font-weight: 650; cursor: pointer; }
47
+ .question-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
45
48
  .question-reply { margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
46
- .question-reply-quote { max-height: 72px; overflow: auto; margin: 0 0 8px; padding: 8px 10px; border-left: 3px solid var(--accent); border-radius: 4px; background: var(--surface-2); font-size: 12px; overflow-wrap: anywhere; }
49
+ .question-copy { margin-bottom: 4px; }
50
+ .question-copy-feedback { min-height: 1.4em; margin: 0 0 6px; color: var(--ink-2); font-size: 12px; }
51
+ .question-panel p, .question-panel ul, .question-panel ol, .question-panel pre, .question-panel blockquote, .question-panel table { margin-top: 0; margin-bottom: 6px; }
52
+ .question-panel pre { max-width: 100%; overflow-x: auto; }
53
+ .question-panel table { display: block; max-width: 100%; overflow-x: auto; }
47
54
  .question-reply-form { display: grid; gap: 8px; }
48
- .question-reply-form textarea { min-height: 62px; resize: vertical; }
55
+ .question-reply-form .message-editor { position: relative; min-height: 62px; resize: vertical; }
49
56
  .question-reply-form .btn { justify-self: end; }
50
57
  .question-badge { display: inline-grid; place-items: center; min-width: 18px; height: 18px; margin-left: 5px; padding: 0 4px; border-radius: 99px; background: var(--accent); color: var(--accent-ink); font-size: 10px; }
51
58
  .chip {
@@ -240,8 +247,21 @@
240
247
  .message-copy:hover, .message-copy:focus-visible, .message-copy.is-flashing { color: var(--accent); background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 24%, var(--line)); }
241
248
  .message-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
242
249
  .message-copy-feedback { position: absolute; z-index: 25; left: 0; bottom: calc(100% + 5px); width: max-content; max-width: min(260px, calc(100vw - 32px)); padding: 6px 9px; border: 1px solid var(--line); border-radius: 8px; color: var(--ink); background: var(--surface); box-shadow: var(--shadow); font-size: 11px; font-weight: 500; line-height: 1.4; text-align: left; white-space: normal; overflow-wrap: anywhere; }
250
+ .message-actions { display: flex; align-items: center; gap: 2px; }
251
+ .message-reply { display: grid; place-items: center; width: 32px; height: 32px; padding: 0; border: 1px solid transparent; border-radius: 8px; color: var(--ink-3); background: transparent; cursor: pointer; }
252
+ .message-reply-icon { display: block; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.7; }
253
+ .message-reply:hover, .message-reply:focus-visible { border-color: var(--line); color: var(--accent); background: var(--accent-soft); }
254
+ .reply-preview { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: min(940px, 100%); min-width: 0; margin: 0 auto; padding: 8px 12px; border-left: 3px solid var(--accent); border-radius: 6px; background: var(--accent-soft); }
255
+ .reply-preview > div { min-width: 0; flex: 1; }
256
+ .reply-preview strong { font-size: 12px; color: var(--accent); }
257
+ .reply-preview p { display: -webkit-box; overflow: hidden; margin: 2px 0 0; color: var(--ink-2); font-size: 12px; line-height: 1.4; overflow-wrap: anywhere; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
258
+ .reply-cancel { flex: none; min-height: 32px; padding: 0 9px; border: 1px solid var(--line); border-radius: 8px; color: var(--ink-2); background: var(--surface); font: inherit; font-size: 11px; font-weight: 600; white-space: nowrap; cursor: pointer; }
259
+ .reply-cancel:hover, .reply-cancel:focus-visible { border-color: var(--danger); color: var(--danger); background: var(--surface); }
260
+ .reply-cancel:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
261
+ .reply-quote { display: block; max-width: min(82%, 500px); overflow: hidden; margin: 0 0 5px; padding: 5px 10px; border: 0; border-left: 2px solid var(--accent); border-radius: 0 6px 6px 0; color: var(--ink-2); background: var(--surface-2); font: inherit; font-size: 12px; text-align: left; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
262
+ .reply-quote:hover:not(:disabled) { color: var(--accent); background: var(--accent-soft); }
263
+ .reply-quote:disabled { cursor: default; opacity: .7; }
243
264
  .msg.own .message-copy-feedback { left: auto; right: 0; }
244
- .sys .message-copy-feedback { left: 50%; right: auto; transform: translateX(-50%); }
245
265
  .message-readers { flex: 0 0 24px; align-self: flex-end; margin: 0 0 4px; padding: 0; width: 24px; height: 24px; border: 1px solid var(--line); border-radius: 50%; color: var(--ink-3); background: var(--surface); font: inherit; font-size: 10px; cursor: pointer; box-shadow: 0 1px 3px rgb(20 40 32 / .06); }
246
266
  .message-readers[data-reader-state="empty"], .message-readers[data-reader-state="unknown"] { background: var(--surface-2); }
247
267
  .message-readers:hover, .message-readers[aria-expanded="true"] { border-color: var(--accent); color: var(--accent); }
@@ -255,7 +275,6 @@
255
275
  .reader-panel-head h2 { margin: 0; font-family: var(--font-sans); font-size: 18px; font-weight: 650; letter-spacing: -.01em; }
256
276
  .reader-panel-head .hint { margin: 0 0 4px; }
257
277
  .reader-close { flex: none; width: 32px; height: 32px; border: 1px solid var(--line); border-radius: 50%; color: var(--ink-2); background: var(--surface); font: inherit; font-size: 21px; cursor: pointer; }
258
- .reader-excerpt { max-height: 110px; overflow: auto; margin: 16px 0; padding: 10px 12px; border-left: 3px solid var(--accent); background: var(--surface-2); font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; }
259
278
  .reader-panel .receipt-reader-list li { display: grid; gap: 3px; padding: 10px 0; border-top: 1px solid var(--line); overflow-wrap: anywhere; }
260
279
  .chat-resource { display: grid; gap: 9px; min-width: 0; margin: 10px 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: color-mix(in srgb, var(--surface-2) 76%, var(--surface)); }
261
280
  .resource-info, .resource-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
@@ -386,7 +405,6 @@
386
405
  }
387
406
  .sys::before { content: ""; position: absolute; top: 9px; left: 0; right: 0; height: 1px; background: var(--line); }
388
407
  .sys span { position: relative; padding: 0 10px; background: var(--surface); }
389
- .sys .message-copy { align-self: center; margin: -8px 0 0; }
390
408
 
391
409
  .day-sep {
392
410
  display: flex;
@@ -430,6 +448,7 @@
430
448
  .composer .input { flex: 1; }
431
449
  .composer .input:disabled { opacity: .5; }
432
450
  #msgInput {
451
+ position: relative;
433
452
  min-height: 0;
434
453
  padding: 12px 13px;
435
454
  line-height: 1.5;
@@ -438,6 +457,10 @@
438
457
  resize: none;
439
458
  overflow-y: hidden;
440
459
  }
460
+ #msgInput:empty, #msgInput:has(> br:only-child), #msgInput:has(> div:only-child > br:only-child) { height: 50px !important; }
461
+ .message-editor { white-space: pre-wrap; overflow-wrap: anywhere; outline: none; }
462
+ .message-editor:empty::before, .message-editor:has(> br:only-child)::before, .message-editor:has(> div:only-child > br:only-child)::before { content: attr(aria-placeholder); position: absolute; inset: 12px 13px auto; overflow: hidden; color: var(--ink-3); pointer-events: none; text-overflow: ellipsis; white-space: nowrap; }
463
+ .editor-mention { display: inline-block; padding: 1px 7px; border: 1px solid color-mix(in srgb, var(--mention-blue) 32%, transparent); border-radius: 999px; color: var(--mention-blue); background: color-mix(in srgb, var(--mention-blue) 14%, transparent); font-size: .92em; font-weight: 600; vertical-align: baseline; white-space: nowrap; }
441
464
  #btnSend { padding: 12px 22px; }
442
465
  .send-error { margin: 0; font-size: 12.5px; color: var(--danger); }
443
466
  .draft-count { flex: none; margin: 0; color: var(--ink-3); text-align: right; font-size: 11px; font-variant-numeric: tabular-nums; }
@@ -445,6 +468,7 @@
445
468
  .failed-messages h3 { margin: 0 0 5px; color: var(--danger); font-size: 12px; }
446
469
  .failed-message { display: flex; align-items: center; gap: 8px; padding: 5px 0; border-top: 1px solid var(--line); }
447
470
  .failed-message p { flex: 1; min-width: 0; max-height: 48px; overflow: auto; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
471
+ .failed-reply-context { flex: 0 0 100%; overflow: hidden; color: var(--accent); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
448
472
  .failed-message button { flex: none; border: 1px solid var(--line); border-radius: 7px; padding: 4px 8px; background: var(--surface); color: var(--ink-2); font: inherit; font-size: 12px; cursor: pointer; }
449
473
  .failed-message button:disabled { opacity: .5; cursor: default; }
450
474
  .attachment-button { flex: none; display: grid; place-items: center; width: 44px; height: 44px; padding: 0; border: 1px solid var(--line); border-radius: 12px; color: var(--ink-2); background: var(--surface); font: inherit; font-size: 24px; cursor: pointer; }
@@ -73,23 +73,22 @@
73
73
  @keyframes spin { to { transform: rotate(360deg); } }
74
74
  .admin-access { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); }
75
75
  .admin-access summary { margin: 0 0 8px; font-size: 13px; font-weight: 600; cursor: pointer; }
76
- .admin-dialog { width: min(1020px, calc(100vw - 32px)); max-width: none; max-height: 90dvh; overflow: auto; padding: 24px; color: var(--ink); background: linear-gradient(145deg, var(--surface), color-mix(in srgb, var(--accent-soft) 16%, var(--surface))); border: 1px solid color-mix(in srgb, var(--accent) 18%, var(--line)); border-radius: 20px; box-shadow: 0 24px 80px rgb(10 25 20 / .2); }
76
+ .admin-badge, .room-admin-badge { display: inline-flex; align-items: center; width: fit-content; border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--line)); border-radius: 999px; color: var(--accent); background: var(--accent-soft); font-size: 10px; font-weight: 700; letter-spacing: .04em; line-height: 1.4; }
77
+ .admin-badge { padding: 3px 8px; }
78
+ .room-admin-badge { padding: 1px 6px; vertical-align: middle; }
79
+ .admin-scope-note { margin: 0 0 14px; padding: 10px 11px; border-left: 2px solid var(--accent); border-radius: 0 8px 8px 0; background: color-mix(in srgb, var(--accent-soft) 58%, transparent); line-height: 1.5; }
80
+ .admin-dialog { width: min(560px, calc(100vw - 32px)); max-width: none; max-height: 90dvh; overflow: auto; padding: 24px; color: var(--ink); background: linear-gradient(145deg, var(--surface), color-mix(in srgb, var(--accent-soft) 16%, var(--surface))); border: 1px solid color-mix(in srgb, var(--accent) 18%, var(--line)); border-radius: 20px; box-shadow: 0 24px 80px rgb(10 25 20 / .2); }
77
81
  .admin-dialog::backdrop { background: rgb(9 22 18 / .52); backdrop-filter: blur(4px); }
78
82
  .admin-dialog-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
83
+ .admin-dialog-actions { display: flex; align-items: center; gap: 10px; }
84
+ .admin-dialog #btnCloseAdmin { width: 36px; height: 36px; margin: 0; }
79
85
  .admin-dialog-head h2 { margin: 0; font-family: var(--font-display); font-size: 25px; font-weight: 600; letter-spacing: -.02em; }
80
86
  .admin-dialog h3 { margin: 20px 0 9px; font-size: 14px; font-weight: 700; letter-spacing: .01em; }
81
- .admin-columns { display: grid; grid-template-columns: minmax(230px, .8fr) minmax(0, 1.2fr); gap: 26px; }
82
- .admin-columns > section { min-width: 0; padding: 14px; border: 1px solid color-mix(in srgb, var(--line) 82%, transparent); border-radius: 14px; background: color-mix(in srgb, var(--surface) 84%, var(--accent-soft)); }
83
- .admin-columns > section > h3:first-child { margin-top: 0; }
84
- .admin-columns .field { margin-bottom: 10px; }
85
- .admin-dialog .admin-select { width: 100%; min-height: 40px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: var(--surface); font: inherit; }
86
- .admin-overview, .admin-list { margin: 0; padding: 0; list-style: none; }
87
- .admin-overview p, .admin-list li { margin: 6px 0; padding: 9px; border: 1px solid var(--line); border-radius: 9px; overflow-wrap: anywhere; }
88
- .admin-list li { display: grid; gap: 7px; }
89
- .admin-plan-form { display: grid; gap: 8px; }
90
- .admin-enrollment { display: grid; gap: 8px; margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--accent-soft); overflow-wrap: anywhere; }
91
- .admin-enrollment code { user-select: all; }
92
- @media (max-width: 620px) { .admin-dialog { padding: 15px; } .admin-columns { grid-template-columns: minmax(0, 1fr); gap: 0; } }
87
+ .admin-guide { padding: 16px; border: 1px solid color-mix(in srgb, var(--line) 82%, transparent); border-radius: 14px; background: color-mix(in srgb, var(--surface) 84%, var(--accent-soft)); }
88
+ .admin-guide .field { margin-bottom: 12px; }
89
+ .admin-dialog .admin-select { display: block; box-sizing: border-box; width: 100%; min-width: 0; min-height: 40px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: var(--surface); font: inherit; }
90
+ .admin-enrollment { display: grid; gap: 8px; margin-top: 12px; padding: 12px; border-radius: 10px; background: var(--accent-soft); }
91
+ @media (max-width: 620px) { .admin-dialog { padding: 15px; } }
93
92
  .rail-avatar { display: grid; place-items: center; width: 25px; height: 25px; border-radius: 50%; color: var(--accent); background: var(--accent-soft); }
94
93
  .online-dot { width: 7px; height: 7px; border-radius: 50%; background: #609773; box-shadow: 0 0 0 3px color-mix(in srgb, #609773 16%, transparent); }
95
94
  #chatView > .chat-head { grid-column: 2; grid-row: 1; min-width: 0; }
@@ -149,7 +148,6 @@
149
148
  #chatView > .conn-bar { grid-column: 1; grid-row: 2; }
150
149
  #chatView > .msg-scroll { grid-column: 1; grid-row: 3; }
151
150
  #chatView > .composer { grid-column: 1; grid-row: 4; }
152
- .reader-excerpt { max-height: 46px; margin: 8px 0; padding: 6px 9px; }
153
151
  .chat-head-actions { flex: none; flex-wrap: nowrap; gap: 4px; }
154
152
  .chat-head-actions > .locale-control { display: none; }
155
153
  .chat-head-main { flex: 1; min-width: 0; }
@@ -159,6 +157,7 @@
159
157
  #chatView > .chat-head .action-icon { display: block; }
160
158
  .rooms-drawer-trigger { display: grid; flex: none; }
161
159
  #btnQuestions .question-badge { position: absolute; top: -5px; right: -5px; margin: 0; font-size: 10px; }
160
+ #questionPanel, #announcementPanel { position: fixed; top: 70px; left: 12px; right: 12px; width: auto; max-height: calc(100dvh - 92px); }
162
161
  .room-options-panel { right: 0; left: auto; }
163
162
  .thread { padding: 14px 12px 6px; }
164
163
  .msg-text { max-width: 92%; font-size: 15px; }
@@ -176,6 +175,8 @@
176
175
  .room-meta { max-width: 100px; overflow: hidden; }
177
176
  }
178
177
  @media (max-width: 300px) {
178
+ #chatView > .chat-head { padding: 8px; gap: 0; }
179
+ .chat-head-actions { gap: 0; }
179
180
  .chat-head .chip { width: 36px; height: 36px; }
180
181
  #btnRoomsDrawer { width: 36px; height: 36px; }
181
182
  }
@@ -184,8 +185,6 @@
184
185
  .composer-meta { min-height: 3.6em; }
185
186
  }
186
187
  @media (max-width: 220px) {
187
- #chatView > .chat-head { padding: 8px; gap: 3px; }
188
- .chat-head-actions { gap: 1px; }
189
188
  .chat-head .chip { width: 28px; height: 28px; }
190
189
  #btnRoomsDrawer { width: 28px; height: 28px; }
191
190
  .room-title-row { gap: 3px; }
@@ -8,7 +8,7 @@ import RoomService, {
8
8
  type Message,
9
9
  type Room,
10
10
  } from "../src/room-service";
11
- import { answerQuestion, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/store";
11
+ import { answerQuestion, sendReply, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/store";
12
12
  import {
13
13
  admissionMatches,
14
14
  clearPendingAdmission,
@@ -22,6 +22,7 @@ import { memberRoutes } from "./member-routes";
22
22
  import { resourceRoutes } from "./resource-routes";
23
23
  import { maxResourceBytes } from "../src/resources";
24
24
  import { adminRoutes } from "./admin-routes";
25
+ import { roomReminderRoutes, startRoomReminderScheduler } from "./room-reminders";
25
26
 
26
27
  function parsePort(value: string): number {
27
28
  const port = Number(value);
@@ -109,7 +110,7 @@ async function handle(req: Request): Promise<Response> {
109
110
  // ponytail: F1 — reject non-JSON POSTs; a text/plain simple request from a
110
111
  // malicious page would otherwise mutate rooms cross-origin (no preflight)
111
112
  if (
112
- ["POST", "PUT", "DELETE"].includes(req.method) &&
113
+ ["POST", "PUT", "PATCH", "DELETE"].includes(req.method) &&
113
114
  !req.headers.get("content-type")?.includes("application/json") &&
114
115
  !(/^\/rooms\/[^/]+\/resources$/.test(p) && req.method === "POST")
115
116
  ) {
@@ -119,6 +120,8 @@ async function handle(req: Request): Promise<Response> {
119
120
  return json({ error: "unauthorized" }, 401);
120
121
  }
121
122
  try {
123
+ const reminders = await roomReminderRoutes(req, url);
124
+ if (reminders) return reminders;
122
125
  const admin = await adminRoutes(req, url); if (admin) return admin;
123
126
  const resource = await resourceRoutes(req, url);
124
127
  if (resource) return resource;
@@ -384,6 +387,21 @@ async function handle(req: Request): Promise<Response> {
384
387
  if (text.length > 2000) {
385
388
  return json({ error: "text too long (max 2000)" }, 400);
386
389
  }
390
+ const replyTo = (body as Record<string, unknown>).replyToMessageID;
391
+ if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "replyToMessageID must be a non-empty message ID" }, 400);
392
+ if (replyTo !== undefined) {
393
+ const result = await sendReply(roomId, replyTo, sessionID, text);
394
+ if (result.status !== "ok") {
395
+ if (result.status === "missing") return json({ error: "room not found" }, 404);
396
+ if (result.status === "target") return json({ error: "reply target not found in room" }, 404);
397
+ if (result.status === "question") return json({ error: "use the question answers endpoint to reply to a question" }, 409);
398
+ return json({ error: "session is not a room member" }, 409);
399
+ }
400
+ touchActive(sessionID);
401
+ const room = await read((svc) => svc.getRoom(roomId));
402
+ void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
403
+ return json(serializeRoom(room), 201);
404
+ }
387
405
  const room = await mutate((svc, reg) => {
388
406
  const senderEntry = reg[roomId]?.[sessionID];
389
407
  if (!senderEntry) throw new RoomError("NOT_JOINED", "session is not a room member");
@@ -491,6 +509,7 @@ export default {
491
509
  console.log(
492
510
  `chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`,
493
511
  );
512
+ startRoomReminderScheduler((roomId, roomName, text, message) => wakeMentionedSessions(serveWakeUrl, roomId, roomName, text, "", message));
494
513
  if (!token) {
495
514
  console.warn(
496
515
  "chat-room center has NO token auth — set CHAT_ROOM_SERVER_TOKEN if this port is reachable from other hosts",
package/server/chat.html CHANGED
@@ -111,25 +111,18 @@
111
111
  </div>
112
112
  </aside>
113
113
  <dialog id="adminDialog" class="admin-dialog" aria-labelledby="adminHeading">
114
- <header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></header>
114
+ <header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><div class="admin-dialog-actions"><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></div></header>
115
115
  <p id="adminStatus" class="hint" role="status" aria-live="polite"></p>
116
- <div class="admin-columns">
117
- <section><h3 data-i18n="designations">Designations</h3><label class="field"><span class="field-label" data-i18n="adminRoom">Admin room</span><select id="adminRoomSelect" class="admin-select"></select></label>
118
- <label class="field"><span class="field-label" data-i18n="targetRoom">Agent room</span><select id="adminTargetRoom" class="admin-select"></select></label>
116
+ <div class="admin-guide"><p class="hint admin-scope-note" data-i18n="adminBindingGuide">Choose a room, then select a registered member. They must privately accept the invitation to finish setup.</p><label class="field"><span class="field-label" data-i18n="adminRoomLabel">Room to administer</span><select id="adminRoomSelect" class="admin-select"></select></label>
119
117
  <label class="field"><span class="field-label" data-i18n="targetAgent">Registered agent</span><select id="adminTargetAgent" class="admin-select"></select></label>
120
- <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="designate">Designate and issue enrollment</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
118
+ <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="adminDesignateAgent">Designate agent</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
121
119
  <button id="btnRevokeAdmin" class="btn ghost small danger-text" type="button" data-i18n="revokeDesignation">Revoke designation</button>
122
- </section>
123
- <section><h3 data-i18n="globalStatus">Global status</h3><div id="adminOverview" class="admin-overview"></div><h3 data-i18n="adminTasks">Tasks</h3>
124
- <form id="adminTaskForm"><label class="field"><span class="field-label" data-i18n="taskTargetRoom">Target room</span><select id="adminTaskRoom" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskTargetAgent">Target agent</span><select id="adminTaskAgent" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskText">Task</span><textarea id="adminTaskText" class="input" rows="2" maxlength="2000" required></textarea></label><button class="btn primary small" type="submit" data-i18n="dispatchTask">Dispatch task</button></form><ul id="adminTaskList" class="admin-list"></ul>
125
- <h3 data-i18n="timers">Timers</h3><form id="adminPlanForm" class="admin-plan-form"><input id="adminPlanName" class="input" maxlength="64" required data-i18n-placeholder="planName" placeholder="Timer name"><input id="adminPlanInterval" class="input" type="number" min="60" max="2592000" value="3600" required><textarea id="adminPlanText" class="input" rows="2" maxlength="2000" required></textarea><button class="btn primary small" type="submit" data-i18n="createTimer">Create timer</button></form><ul id="adminPlanList" class="admin-list"></ul>
126
- </section>
127
120
  </div>
128
121
  </dialog>
129
122
  <button id="roomDrawerBackdrop" class="room-drawer-backdrop" type="button" aria-label="Close room list" data-i18n-aria-label="closeRoomList" hidden></button>
130
123
  <header class="chat-head">
131
124
  <div class="chat-head-main">
132
- <div class="room-title-row"><h1 id="roomName"></h1><button id="btnRoomsDrawer" class="chip rooms-drawer-trigger" type="button" aria-label="Open room list" data-i18n-aria-label="roomsMenu" aria-controls="roomRail" aria-expanded="false"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/></svg><span class="action-label">Rooms</span></button></div>
125
+ <div class="room-title-row"><h1 id="roomName"></h1><span id="activeAdminBadge" class="admin-badge" data-i18n="adminRoomBadge" hidden>Admin</span><button id="btnRoomsDrawer" class="chip rooms-drawer-trigger" type="button" aria-label="Open room list" data-i18n-aria-label="roomsMenu" aria-controls="roomRail" aria-expanded="false"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/></svg><span class="action-label">Rooms</span></button></div>
133
126
  <p class="room-meta">
134
127
  <button type="button" id="btnCopyId" class="copy-id" aria-label="Copy room ID" data-i18n-aria-label="copyRoomId" title="Click to copy the full room ID" data-i18n-title="copyRoomIdTitle">
135
128
  <span class="mono" id="roomIdShort"></span><span class="copy-ok" data-i18n="copied">Copied</span>
@@ -149,6 +142,23 @@
149
142
  <div id="questionReply" class="question-reply" hidden></div>
150
143
  </section>
151
144
  </div>
145
+ <div class="anchor">
146
+ <button class="chip" type="button" id="btnReminders" aria-haspopup="true" aria-expanded="false" aria-controls="reminderPanel"><span class="action-label" data-i18n="reminders">Reminders</span></button>
147
+ <section class="panel reminder-panel" id="reminderPanel" aria-labelledby="reminderHeading" hidden>
148
+ <div class="announcement-head"><h3 id="reminderHeading" tabindex="-1" data-i18n="reminders">Reminders</h3><button type="button" id="btnRefreshReminders" class="question-refresh" data-i18n="refreshQuestions">Refresh</button></div>
149
+ <p id="reminderStatus" class="hint" role="status" aria-live="polite"></p><ul id="reminderList" class="reminder-list"></ul>
150
+ <form id="reminderForm" class="reminder-form">
151
+ <label class="field"><span class="field-label" data-i18n="reminderSchedule">Schedule</span><select id="reminderType" class="input"><option value="once" data-i18n="reminderOnce">One time</option><option value="cron">CRON</option></select></label>
152
+ <label class="field" id="reminderOnceField"><span class="field-label" data-i18n="reminderDate">Date and time</span><input id="reminderAt" class="input" type="datetime-local" required></label>
153
+ <div id="reminderCronFields" hidden><label class="field"><span class="field-label" data-i18n="reminderCron">5-field CRON expression</span><input id="reminderCron" class="input" placeholder="0 9 * * 1-5" autocomplete="off"></label></div>
154
+ <label class="field"><span class="field-label" data-i18n="reminderTimezone">Timezone override (optional)</span><input id="reminderTimezone" class="input" autocomplete="off"></label>
155
+ <p class="hint" data-i18n="reminderTimezoneHint">Leave blank to use the server timezone. Enter an IANA timezone to override it.</p>
156
+ <label class="field"><span class="field-label" data-i18n="reminderText">Reminder text</span><textarea id="reminderText" class="input" rows="3" maxlength="1000" required></textarea></label>
157
+ <p id="reminderTemplateHint" class="hint" data-i18n="reminderTemplateHint">Use {{time}}, {{initiator}}, and {{room}} in your message.</p>
158
+ <button class="btn primary small" type="submit" data-i18n="reminderCreate">Create reminder</button>
159
+ </form>
160
+ </section>
161
+ </div>
152
162
  <div class="anchor">
153
163
  <button class="chip" type="button" id="btnAnnouncements" aria-haspopup="true" aria-expanded="false" aria-controls="announcementPanel"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M5 4h14v16H5zM8 8h8M8 12h8M8 16h5"/></svg><span class="action-label" data-i18n="announcements">Announcements</span></button>
154
164
  <section class="panel announcement-panel" id="announcementPanel" aria-labelledby="announcementHeading" hidden>
@@ -201,12 +211,12 @@
201
211
  <div><p id="readerCount" class="hint"></p><h2 id="readerHeading" tabindex="-1" data-i18n="readerPanelTitle">Message readers</h2></div>
202
212
  <button type="button" id="btnCloseReaders" class="reader-close" data-i18n-aria-label="close" aria-label="Close">×</button>
203
213
  </div>
204
- <blockquote id="readerExcerpt" class="reader-excerpt"></blockquote>
205
214
  <ul id="readerList" class="receipt-reader-list" aria-label="Message readers" data-i18n-aria-label="readerPanelTitle"></ul>
206
215
  </aside>
207
216
 
208
217
  <footer class="composer">
209
218
  <p id="sendError" class="send-error" role="alert" hidden></p>
219
+ <section id="replyPreview" class="reply-preview" aria-label="Replying to" data-i18n-aria-label="replyingTo" hidden><div><span data-i18n="replyingTo">Replying to</span> <strong id="replyPreviewName"></strong><p id="replyPreviewText"></p></div><button id="replyCancel" type="button" class="reply-cancel" aria-label="Cancel reply" data-i18n-aria-label="cancelReply">×</button></section>
210
220
  <div id="mentionPicker" class="mention-picker" role="listbox" aria-label="Choose a member to mention" data-i18n-aria-label="mentionMembers" hidden></div>
211
221
  <section id="attachmentTray" class="attachment-tray" aria-label="Attachments" data-i18n-aria-label="attachments" hidden>
212
222
  <p id="attachmentVolatile" class="attachment-volatile" data-i18n="attachmentVolatile" hidden></p>
@@ -216,7 +226,7 @@
216
226
  <div class="composer-row">
217
227
  <button class="attachment-button" type="button" id="btnAddAttachments" aria-label="Add files" data-i18n-aria-label="addFiles" aria-controls="attachmentPicker" disabled><svg aria-hidden="true" viewBox="0 0 24 24"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.82-2.83l8.49-8.48"/></svg></button>
218
228
  <input id="attachmentPicker" type="file" multiple hidden>
219
- <textarea id="msgInput" class="input" rows="1" maxlength="2000" placeholder="Type a message, Enter to send, Shift+Enter for a new line" data-i18n-placeholder="messagePlaceholder" autocomplete="off" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" disabled></textarea>
229
+ <div id="msgInput" class="input message-editor" role="textbox" aria-multiline="true" aria-label="Message" data-i18n-aria-label="messagePlaceholder" aria-placeholder="Type a message, Enter to send, Shift+Enter for a new line" data-i18n-aria-placeholder="messagePlaceholder" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" contenteditable="false" aria-disabled="true" tabindex="-1"></div>
220
230
  <button class="btn primary" type="button" id="btnSend" data-i18n="send" disabled>Send</button>
221
231
  </div>
222
232
  <div class="composer-meta">
package/server/inbox.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  import { readInboxMessages } from "../src/store";
2
2
  import type { Message } from "../src/room-service";
3
3
 
4
- export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "senderSessionID" | "text" | "createdAt"> & { roomName: string; roomKind?: "group" | "direct" };
4
+ export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "senderSessionID" | "text" | "createdAt"> & {
5
+ roomName: string;
6
+ roomKind?: "group" | "direct";
7
+ answerQuestionExcerpt?: string;
8
+ };
5
9
  export type InboxResult = { member: boolean; items: InboxItem[]; queuedTs: Record<string, number>; hasMore: boolean };
6
10
 
7
11
  export async function readInbox(sessionID: string, roomFilter: string | null, excludeSelf: boolean, afterTs?: number): Promise<InboxResult> {
@@ -0,0 +1,222 @@
1
+ import { Cron } from "croner";
2
+ import { randomUUID } from "node:crypto";
3
+ import { databasePath } from "../src/store";
4
+ import { initializeReminderSchema, withStateTransaction } from "../src/sqlite-state";
5
+ import type { Message } from "../src/room-service";
6
+
7
+ type Schedule = { type: "once"; at: string; timezone?: string } | { type: "cron"; expression: string; timezone: string };
8
+ type Row = { id: string; room_id: string; creator_session_id: string; initiator: string; text: string; schedule_type: string; at: string | null; expression: string | null; timezone: string | null; paused: number; next_run_at: number; created_at: number; last_error: string | null };
9
+ const json = (body: unknown, status = 200) => Response.json(body, { status });
10
+ const dbFile = () => databasePath();
11
+
12
+ function zone(): string { return Intl.DateTimeFormat().resolvedOptions().timeZone; }
13
+ function zonedParts(ms: number, timezone: string): number[] {
14
+ const fields = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })
15
+ .formatToParts(ms).map(part => [part.type, part.value]));
16
+ return ["year", "month", "day", "hour", "minute", "second"].map(key => Number(fields[key]));
17
+ }
18
+ function normalizeOnce(input: string, timezone: string): string {
19
+ const match = input.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/i);
20
+ if (!match) throw new Error("once schedule at must be an ISO timestamp");
21
+ const [, ys, mos, ds, hs, mins, secs = "00", fraction = "", offset] = match;
22
+ const parts = [Number(ys), Number(mos), Number(ds), Number(hs), Number(mins), Number(secs)];
23
+ const [y, mo, d, h, mi, s] = parts;
24
+ const check = new Date(Date.UTC(y!, mo! - 1, d!, h!, mi!, s!));
25
+ if (check.getUTCFullYear() !== y || check.getUTCMonth() !== mo! - 1 || check.getUTCDate() !== d || h! > 23 || mi! > 59 || s! > 59) throw new Error("once schedule at is not a valid date/time");
26
+ let ms: number;
27
+ if (offset) {
28
+ ms = Date.parse(input);
29
+ } else {
30
+ const local = Date.UTC(y!, mo! - 1, d!, h!, mi!, s!, Number((fraction.slice(1) + "000").slice(0, 3)));
31
+ const offsets = new Set<number>();
32
+ for (let delta = -36; delta <= 36; delta += 6) {
33
+ const probe = local + delta * 3_600_000;
34
+ const [py, pm, pd, ph, pmin, ps] = zonedParts(probe, timezone);
35
+ offsets.add(Date.UTC(py!, pm! - 1, pd!, ph!, pmin!, ps!) - Math.floor(probe / 1000) * 1000);
36
+ }
37
+ const candidates = [...offsets].map(value => local - value).filter(candidate => {
38
+ const target = zonedParts(candidate, timezone);
39
+ return target.every((value, index) => value === parts[index]);
40
+ });
41
+ if (candidates.length !== 1) throw new Error("once schedule local time is ambiguous or does not exist in the server timezone; include an explicit offset");
42
+ ms = candidates[0]!;
43
+ }
44
+ if (!Number.isFinite(ms)) throw new Error("once schedule at is not a valid ISO timestamp");
45
+ return new Date(ms).toISOString();
46
+ }
47
+ function validTimezone(value: unknown): string {
48
+ if (typeof value !== "string" || !value || value.length > 128) throw new Error("timezone must be an IANA timezone string");
49
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
50
+ return value;
51
+ }
52
+ function normalizeSchedule(value: unknown): Schedule {
53
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("schedule must be an object");
54
+ const input = value as Record<string, unknown>;
55
+ if (input.type === "once") {
56
+ if (typeof input.at !== "string") throw new Error("once schedule at must be an ISO timestamp string");
57
+ const explicitOffset = /(?:Z|[+-]\d{2}:\d{2})$/i.test(input.at);
58
+ if (input.timezone !== undefined && typeof input.timezone !== "string") throw new Error("timezone must be an IANA timezone string");
59
+ if (explicitOffset) {
60
+ const at = normalizeOnce(input.at, zone());
61
+ if (input.timezone === undefined) return { type: "once", at };
62
+ const timezone = validTimezone(input.timezone);
63
+ // An explicit offset fixes the instant; timezone is only its display zone.
64
+ return { type: "once", at, timezone };
65
+ }
66
+ const timezone = input.timezone === undefined ? zone() : validTimezone(input.timezone);
67
+ return { type: "once", at: normalizeOnce(input.at, timezone), timezone };
68
+ }
69
+ if (input.type === "cron") {
70
+ if (typeof input.expression !== "string" || !input.expression.trim() || input.expression.length > 128) throw new Error("cron expression must be a non-empty string");
71
+ const timezone = input.timezone === undefined ? zone() : validTimezone(input.timezone);
72
+ return { type: "cron", expression: input.expression, timezone };
73
+ }
74
+ throw new Error("schedule type must be once or cron");
75
+ }
76
+
77
+ function next(schedule: Schedule, from: number): number {
78
+ if (schedule.type === "once") {
79
+ const at = Date.parse(schedule.at);
80
+ if (!Number.isFinite(at) || at <= from) throw new Error("once schedule at must be a future ISO timestamp");
81
+ return at;
82
+ }
83
+ if (typeof schedule.expression !== "string" || schedule.expression.trim().split(/\s+/).length !== 5) throw new Error("cron schedule requires a 5-field expression");
84
+ const timezone = validTimezone(schedule.timezone);
85
+ const cron = new Cron(schedule.expression, { timezone, paused: true });
86
+ let first: number | undefined, second: number | undefined;
87
+ try {
88
+ first = cron.nextRun(new Date(from))?.getTime();
89
+ second = first === undefined ? undefined : cron.nextRun(new Date(first + 1000))?.getTime();
90
+ } finally { cron.stop(); }
91
+ if (!first || !second || second - first < 60_000) throw new Error("cron occurrences must be at least 60 seconds apart");
92
+ return first;
93
+ }
94
+
95
+ function output(r: Row) {
96
+ return { id: r.id, roomId: r.room_id, creatorSessionID: r.creator_session_id, text: r.text,
97
+ schedule: r.schedule_type === "once" ? { type: "once", at: r.at, ...(r.timezone ? { timezone: r.timezone } : {}) } : { type: "cron", expression: r.expression, timezone: r.timezone },
98
+ paused: Boolean(r.paused), nextRunAt: new Date(r.next_run_at).toISOString(), createdAt: new Date(r.created_at).toISOString(),
99
+ ...(r.last_error ? { lastError: r.last_error } : {}) };
100
+ }
101
+ function member(db: any, room: string, session: string): { name: string } | null {
102
+ return db.query(`SELECT g.name FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN (SELECT kind FROM rooms WHERE id=g.room_id)='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?`).get(room, session) as { name: string } | null;
103
+ }
104
+ function template(text: string, at: number, initiator: string, room: string, timezone?: string) {
105
+ const time = timezone ? (() => {
106
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "longOffset" }).formatToParts(at).map(part => [part.type, part.value]));
107
+ return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second} ${parts.timeZoneName} [${timezone}]`;
108
+ })() : new Date(at).toISOString();
109
+ const result = text.replace(/\{\{(time|initiator|room)\}\}/g, (_m, key: string) =>
110
+ key === "time" ? time : key === "initiator" ? initiator : room);
111
+ if (result.length > 2000) throw new Error("rendered reminder text exceeds 2000 characters");
112
+ return result;
113
+ }
114
+
115
+ export async function roomReminderRoutes(req: Request, url: URL): Promise<Response | undefined> {
116
+ const match = url.pathname.match(/^\/rooms\/([^/]+)\/reminders(?:\/([^/]+))?$/);
117
+ if (!match) return undefined;
118
+ await initializeReminderSchema(dbFile());
119
+ const room = decodeURIComponent(match[1]!);
120
+ const id = match[2];
121
+ if (req.method === "GET" && !id) {
122
+ const session = url.searchParams.get("sessionID") ?? "";
123
+ const items = await withStateTransaction(dbFile(), db => {
124
+ if (!member(db, room, session)) return null;
125
+ return db.query("SELECT * FROM room_reminders WHERE room_id=? ORDER BY created_at,id").all(room) as Row[];
126
+ });
127
+ return items ? json({ reminders: items.map(output) }) : json({ error: "room not found or session is not a current member" }, 404);
128
+ }
129
+ if (req.method !== "POST" && req.method !== "PATCH" && req.method !== "DELETE") return json({ error: "method not allowed" }, 405);
130
+ const body: unknown = await req.json();
131
+ if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "JSON object body is required" }, 400);
132
+ const input = body as Record<string, unknown>, session = input.sessionID;
133
+ if (typeof session !== "string" || !session || session.length > 128) return json({ error: "sessionID is required" }, 400);
134
+ const result = await withStateTransaction(dbFile(), db => {
135
+ const who = member(db, room, session);
136
+ if (!who) return { error: "room not found or session is not a current member", status: 404 };
137
+ if (req.method === "POST") {
138
+ const text = input.text;
139
+ if (typeof text !== "string" || !text.trim() || text.length > 2000 || input.schedule === undefined) return { error: "text (max 2000) and valid schedule are required", status: 400 };
140
+ try {
141
+ const schedule = normalizeSchedule(input.schedule), at = next(schedule, Date.now()), created = Date.now(), rid = randomUUID();
142
+ const roomName = (db.query("SELECT name FROM rooms WHERE id=?").get(room) as { name: string } | null)?.name;
143
+ if (roomName === undefined) return { error: "room not found", status: 404 };
144
+ template(text.trim(), at, who.name, roomName, schedule.timezone);
145
+ db.query("INSERT INTO room_reminders(id,room_id,creator_session_id,initiator,text,schedule_type,at,expression,timezone,paused,next_run_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,0,?,?)")
146
+ .run(rid, room, session, who.name, text.trim(), schedule.type, schedule.type === "once" ? schedule.at : null, schedule.type === "cron" ? schedule.expression : null, schedule.timezone ?? null, at, created);
147
+ return { reminder: output(db.query("SELECT * FROM room_reminders WHERE id=?").get(rid) as Row), status: 201 };
148
+ } catch (e) { return { error: e instanceof Error ? e.message : "invalid schedule", status: 400 }; }
149
+ }
150
+ if (!id) return { error: "reminder id is required", status: 400 };
151
+ const row = db.query("SELECT * FROM room_reminders WHERE room_id=? AND id=?").get(room, id) as Row | null;
152
+ if (!row) return { error: "reminder not found", status: 404 };
153
+ if (req.method === "DELETE") { db.query("DELETE FROM room_reminders WHERE id=?").run(id); return { ok: true, status: 200 }; }
154
+ const text = input.text;
155
+ if (text !== undefined && (typeof text !== "string" || !text.trim() || text.length > 2000)) return { error: "text must be non-empty and at most 2000 characters", status: 400 };
156
+ if (input.paused !== undefined && typeof input.paused !== "boolean") return { error: "paused must be a boolean", status: 400 };
157
+ const schedule = input.schedule;
158
+ if (row.last_error && input.paused === false && schedule === undefined) return { error: "replace the invalid schedule before resuming this reminder", status: 409 };
159
+ try {
160
+ const normalized = schedule !== undefined ? normalizeSchedule(schedule) : undefined;
161
+ const n = normalized ? next(normalized, Date.now()) : row.next_run_at;
162
+ const roomName = (db.query("SELECT name FROM rooms WHERE id=?").get(room) as { name: string } | null)?.name;
163
+ if (roomName === undefined) return { error: "room not found", status: 404 };
164
+ template(typeof text === "string" ? text.trim() : row.text, n, row.initiator, roomName, normalized ? normalized.timezone : row.timezone ?? undefined);
165
+ db.query("UPDATE room_reminders SET text=?,paused=?,schedule_type=?,at=?,expression=?,timezone=?,next_run_at=?,last_error=? WHERE id=?")
166
+ .run(typeof text === "string" ? text.trim() : row.text, input.paused === undefined ? row.paused : input.paused ? 1 : 0,
167
+ normalized?.type ?? row.schedule_type, normalized?.type === "once" ? normalized.at : normalized ? null : row.at,
168
+ normalized?.type === "cron" ? normalized.expression : normalized ? null : row.expression, normalized ? normalized.timezone ?? null : row.timezone, n, normalized ? null : row.last_error, id);
169
+ return { reminder: output(db.query("SELECT * FROM room_reminders WHERE id=?").get(id) as Row), status: 200 };
170
+ } catch (e) { return { error: e instanceof Error ? e.message : "invalid schedule", status: 400 }; }
171
+ });
172
+ const { status, ...bodyOut } = result;
173
+ return json(bodyOut, status);
174
+ }
175
+
176
+ export type ReminderWake = (roomId: string, roomName: string, text: string, message: Message) => void | Promise<void>;
177
+
178
+ export async function tickRoomReminders(now = Date.now(), wake?: ReminderWake): Promise<void> {
179
+ await initializeReminderSchema(dbFile());
180
+ const ids = await withStateTransaction(dbFile(), db => (db.query("SELECT id FROM room_reminders WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100").all(now) as Array<{ id: string }>).map(row => row.id));
181
+ const failures: Array<{ id: string; error: string }> = [];
182
+ for (const id of ids) {
183
+ let delivered: { roomName: string; message: Message } | undefined;
184
+ const failure = await withStateTransaction(dbFile(), db => {
185
+ const r = db.query("SELECT * FROM room_reminders WHERE id=? AND paused=0 AND next_run_at<=?").get(id, now) as Row | null;
186
+ if (!r) return null;
187
+ try {
188
+ db.transaction(() => {
189
+ const room = db.query("SELECT name FROM rooms WHERE id=?").get(r.room_id) as { name: string } | null;
190
+ if (!room) throw new Error("reminder room no longer exists");
191
+ const upcoming = r.schedule_type === "once" ? undefined : r.schedule_type === "cron"
192
+ ? next(normalizeSchedule({ type: "cron", expression: r.expression, timezone: r.timezone }), now)
193
+ : (() => { throw new Error(`unsupported reminder schedule type: ${r.schedule_type}`); })();
194
+ const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(r.room_id) as { created_at: number } | null;
195
+ const sentAt = Math.max(now, (tail?.created_at ?? 0) + 1), text = template(r.text, sentAt, r.initiator, room.name, r.timezone ?? undefined);
196
+ const message: Message = { id: `reminder:${randomUUID()}`, roomId: r.room_id, senderId: "system", text, createdAt: sentAt };
197
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?, 'system',NULL,?,?,0)").run(message.id, r.room_id, text, sentAt);
198
+ delivered = { roomName: room.name, message };
199
+ if (upcoming === undefined) db.query("DELETE FROM room_reminders WHERE id=?").run(r.id);
200
+ else db.query("UPDATE room_reminders SET next_run_at=?,last_error=NULL WHERE id=?").run(upcoming, r.id);
201
+ })();
202
+ return null;
203
+ } catch (error) {
204
+ const message = (error instanceof Error ? error.message : String(error)).slice(0, 500);
205
+ db.query("UPDATE room_reminders SET paused=1,last_error=? WHERE id=? AND paused=0 AND next_run_at<=?").run(message, id, now);
206
+ return { id, error: message };
207
+ }
208
+ });
209
+ if (failure) failures.push(failure);
210
+ else if (delivered && wake) {
211
+ try { await wake(delivered.message.roomId, delivered.roomName, delivered.message.text, delivered.message); } catch { /* Inbox polling remains the fallback. */ }
212
+ }
213
+ }
214
+ for (const failure of failures) console.error(`room reminder ${failure.id} paused after delivery error: ${failure.error}`);
215
+ }
216
+
217
+ let timer: ReturnType<typeof setInterval> | undefined;
218
+ export function startRoomReminderScheduler(wake?: ReminderWake): void {
219
+ if (timer) return;
220
+ timer = setInterval(() => { void tickRoomReminders(Date.now(), wake).catch(() => {}); }, 1000);
221
+ timer.unref?.();
222
+ }
package/server/wake.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import os from "node:os";
2
2
  import type { Message } from "../src/room-service";
3
- import { formatNotificationLines, formatServeWakePrompt, readState, writeState, type RegistryEntry } from "../src/store";
3
+ import { formatNotificationLines, formatServeWakePrompt, readQuestionExcerpt, readState, writeState, type RegistryEntry } from "../src/store";
4
4
  import { clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueItem } from "../src/queue";
5
5
  import { sendAsyncNotification } from "../src/queue-transport";
6
6
  import { readInbox, type InboxItem } from "./inbox";
@@ -46,8 +46,11 @@ async function deliverWake(
46
46
  const queued = Math.max(current.lastQueuedTs ?? 0, inbox.queuedTs[roomId] ?? 0);
47
47
  if (triggering.createdAt <= (current.lastReadTs ?? 0) || triggering.createdAt <= queued) return;
48
48
  const queuedItems = inbox.items.filter((item) => item.createdAt > queued);
49
- const trigger: InboxItem = { id: triggering.id, roomId, roomName, roomKind, senderId: triggering.senderId, text: triggering.text, createdAt: triggering.createdAt };
50
- const items = queuedItems.some((item) => item.id === trigger.id) ? queuedItems : [...queuedItems, trigger].sort((a, b) => a.createdAt - b.createdAt);
49
+ const trigger: InboxItem = { id: triggering.id, roomId, roomName, roomKind, senderId: triggering.senderId, text: triggering.text, createdAt: triggering.createdAt,
50
+ ...(triggering.answerToMessageID ? { answerQuestionExcerpt: await readQuestionExcerpt(roomId, triggering.answerToMessageID) } : {}) };
51
+ const items = queuedItems.some((item) => item.id === trigger.id)
52
+ ? queuedItems.map((item) => item.id === trigger.id ? { ...trigger, ...item, answerQuestionExcerpt: item.answerQuestionExcerpt ?? trigger.answerQuestionExcerpt } : item)
53
+ : [...queuedItems, trigger].sort((a, b) => a.createdAt - b.createdAt);
51
54
  const maxTs = items.reduce((max, item) => Math.max(max, item.createdAt), 0);
52
55
  const existing = pendingAdmission(sid, roomId);
53
56
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs ? items.filter((item) => item.createdAt > existing.maxTs) : items;