@open-workspace/email 0.4.1 → 0.5.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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -1,39 +1,78 @@
1
1
  import { ApiError } from "@open-workspace/core/ui";
2
2
  import { useEffect, useRef } from "react";
3
- import type { RefObject } from "react";
4
3
 
5
4
  const READ_VISIBILITY_DELAY_MS = 400;
6
5
  const READ_RETRY_DELAY_MS = 2000;
7
6
  const MAX_READ_ATTEMPTS = 2;
8
7
  const MIN_VISIBLE_HEIGHT_PX = 120;
9
8
 
10
- /** Marks a message only after a meaningful part of it remains on screen. */
9
+ /**
10
+ * Marks an unread message read only after a meaningful part of it remains
11
+ * on screen, once: a message this mount saw read (as it arrived, or once
12
+ * reported) and then marked unread was marked so on purpose, and stays.
13
+ * The report shows as read at once (`read` turns true while it is in
14
+ * flight); a failed one shows unread again and is retried here.
15
+ */
11
16
  export function useVisibleMessageRead({
12
17
  enabled,
18
+ read,
13
19
  messageId,
14
20
  onVisible,
15
21
  }: {
22
+ /** Whether reading this message is reported at all. */
16
23
  enabled: boolean;
24
+ read: boolean;
17
25
  messageId: string;
18
26
  onVisible: () => Promise<void>;
19
- }): RefObject<HTMLElement | null> {
27
+ }) {
20
28
  const element = useRef<HTMLElement>(null);
21
29
  const onVisibleRef = useRef(onVisible);
22
- const reportedMessageId = useRef<string | null>(null);
30
+ const readMessageId = useRef<string | null>(null);
31
+
32
+ // The report of this message, across the effect's runs: its own optimistic
33
+ // change of `read` runs the effect again while the report is in flight.
34
+ const report = useRef({
35
+ messageId,
36
+ inFlight: false,
37
+ attempts: 0,
38
+ retryAt: 0,
39
+ gaveUp: false,
40
+ });
23
41
 
24
42
  useEffect(() => {
25
43
  onVisibleRef.current = onVisible;
26
44
  }, [onVisible]);
27
45
 
28
46
  useEffect(() => {
29
- if (!enabled || reportedMessageId.current === messageId) return;
47
+ if (report.current.messageId !== messageId) {
48
+ report.current = {
49
+ messageId,
50
+ inFlight: false,
51
+ attempts: 0,
52
+ retryAt: 0,
53
+ gaveUp: false,
54
+ };
55
+ }
56
+
57
+ const state = report.current;
58
+
59
+ // Read as it arrived, not by this mount's report in flight.
60
+ if (read && !state.inFlight) readMessageId.current = messageId;
61
+
62
+ if (
63
+ !enabled ||
64
+ read ||
65
+ state.gaveUp ||
66
+ readMessageId.current === messageId
67
+ ) {
68
+ return;
69
+ }
70
+
30
71
  const target = element.current;
31
72
 
32
73
  if (!target) return;
33
74
 
34
75
  let intersecting = false;
35
- let pending = false;
36
- let attempts = 0;
37
76
  let stopped = false;
38
77
  let visibleTimer: ReturnType<typeof setTimeout> | undefined;
39
78
 
@@ -43,82 +82,107 @@ export function useVisibleMessageRead({
43
82
  const scheduleRead = (delay: number) => {
44
83
  clearTimeout(visibleTimer);
45
84
 
46
- if (!isVisible() || pending || stopped) return;
47
- visibleTimer = setTimeout(async () => {
48
- visibleTimer = undefined;
85
+ if (!isVisible() || stopped) return;
86
+ visibleTimer = setTimeout(
87
+ async () => {
88
+ visibleTimer = undefined;
49
89
 
50
- if (!isVisible() || stopped) return;
51
- pending = true;
52
- attempts += 1;
53
-
54
- try {
55
- await onVisibleRef.current();
56
-
57
- if (stopped) return;
58
- reportedMessageId.current = messageId;
59
- observer.disconnect();
60
- } catch (error) {
61
- pending = false;
62
- const retryable = !(error instanceof ApiError) || error.status >= 500;
63
-
64
- if (
65
- retryable &&
66
- attempts < MAX_READ_ATTEMPTS &&
67
- isVisible() &&
68
- !stopped
69
- ) {
70
- scheduleRead(READ_RETRY_DELAY_MS);
90
+ if (!isVisible() || stopped || state.gaveUp) return;
91
+
92
+ // An earlier run's report still settling, or failed just now:
93
+ // look again after it.
94
+ if (state.inFlight || Date.now() < state.retryAt) {
95
+ scheduleRead(READ_VISIBILITY_DELAY_MS);
96
+
97
+ return;
71
98
  }
72
99
 
73
- return;
74
- }
100
+ state.inFlight = true;
101
+ state.attempts += 1;
102
+
103
+ try {
104
+ await onVisibleRef.current();
105
+ state.inFlight = false;
106
+ readMessageId.current = messageId;
75
107
 
76
- pending = false;
77
- }, delay);
108
+ if (!stopped) observer.disconnect();
109
+ } catch (error) {
110
+ state.inFlight = false;
111
+
112
+ const retryable =
113
+ !(error instanceof ApiError) || error.status >= 500;
114
+
115
+ if (!retryable || state.attempts >= MAX_READ_ATTEMPTS) {
116
+ state.gaveUp = true;
117
+ } else {
118
+ state.retryAt = Date.now() + READ_RETRY_DELAY_MS;
119
+
120
+ if (!stopped) scheduleRead(READ_RETRY_DELAY_MS);
121
+ }
122
+ }
123
+ },
124
+ Math.max(delay, state.retryAt - Date.now())
125
+ );
78
126
  };
79
127
 
80
- const targetHeight = Math.max(target.getBoundingClientRect().height, 1);
128
+ const handleIntersection = ([entry]: IntersectionObserverEntry[]) => {
129
+ if (!entry) return;
130
+
131
+ const requiredHeight = Math.min(
132
+ MIN_VISIBLE_HEIGHT_PX,
133
+ entry.boundingClientRect.height * 0.5
134
+ );
81
135
 
82
- const visibilityThreshold = Math.min(
83
- 0.5,
84
- MIN_VISIBLE_HEIGHT_PX / targetHeight
85
- );
136
+ intersecting =
137
+ entry.isIntersecting && entry.intersectionRect.height >= requiredHeight;
86
138
 
87
- const observer = new IntersectionObserver(
88
- ([entry]) => {
89
- if (!entry) return;
139
+ if (!isVisible()) {
140
+ clearTimeout(visibleTimer);
141
+ visibleTimer = undefined;
90
142
 
91
- const requiredHeight = Math.min(
92
- MIN_VISIBLE_HEIGHT_PX,
93
- entry.boundingClientRect.height * 0.5
94
- );
143
+ return;
144
+ }
95
145
 
96
- intersecting =
97
- entry.isIntersecting &&
98
- entry.intersectionRect.height >= requiredHeight;
146
+ if (!visibleTimer) scheduleRead(READ_VISIBILITY_DELAY_MS);
147
+ };
99
148
 
100
- if (!isVisible()) {
101
- clearTimeout(visibleTimer);
102
- visibleTimer = undefined;
149
+ // The ratio that shows 120px (or half) of the message depends on its
150
+ // height, which grows from the skeleton as the body loads: a long message
151
+ // would never reach a ratio worked out for the skeleton.
152
+ let visibilityThreshold = 0;
153
+ let intersectionObserver: IntersectionObserver | undefined;
103
154
 
104
- return;
105
- }
155
+ const observeAtHeight = () => {
156
+ const targetHeight = Math.max(target.getBoundingClientRect().height, 1);
157
+ const threshold = Math.min(0.5, MIN_VISIBLE_HEIGHT_PX / targetHeight);
106
158
 
107
- if (!visibleTimer && !pending) scheduleRead(READ_VISIBILITY_DELAY_MS);
108
- },
109
- {
159
+ if (threshold === visibilityThreshold) return;
160
+ visibilityThreshold = threshold;
161
+ intersectionObserver?.disconnect();
162
+ intersectionObserver = new IntersectionObserver(handleIntersection, {
110
163
  rootMargin: "-8% 0px -8% 0px",
111
- threshold: [0, visibilityThreshold],
112
- }
113
- );
164
+ threshold: [0, threshold],
165
+ });
166
+ intersectionObserver.observe(target);
167
+ };
168
+
169
+ const resizeObserver = new ResizeObserver(observeAtHeight);
170
+
171
+ const observer = {
172
+ disconnect() {
173
+ resizeObserver.disconnect();
174
+ intersectionObserver?.disconnect();
175
+ },
176
+ };
114
177
 
115
- observer.observe(target);
178
+ observeAtHeight();
179
+ resizeObserver.observe(target);
116
180
 
117
181
  const handleDocumentVisibility = () => {
118
182
  clearTimeout(visibleTimer);
119
183
  visibleTimer = undefined;
120
184
 
121
- if (isVisible() && !pending) scheduleRead(READ_VISIBILITY_DELAY_MS);
185
+ if (isVisible()) scheduleRead(READ_VISIBILITY_DELAY_MS);
122
186
  };
123
187
 
124
188
  document.addEventListener("visibilitychange", handleDocumentVisibility);
@@ -132,7 +196,7 @@ export function useVisibleMessageRead({
132
196
  );
133
197
  observer.disconnect();
134
198
  };
135
- }, [enabled, messageId]);
199
+ }, [enabled, messageId, read]);
136
200
 
137
201
  return element;
138
202
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Whether a browser push subscription was made with the server's current
3
+ * VAPID public key. A subscription made with another key (the keys change
4
+ * when a stage is recreated) still looks active, but the push service
5
+ * rejects every message the server signs with its new key.
6
+ */
7
+ export function pushKeyMatches(
8
+ subscriptionKey: ArrayBuffer | null,
9
+ serverKey: Uint8Array
10
+ ) {
11
+ if (!subscriptionKey) return false;
12
+ const bytes = new Uint8Array(subscriptionKey);
13
+
14
+ return (
15
+ bytes.length === serverKey.length &&
16
+ bytes.every((byte, index) => byte === serverKey[index])
17
+ );
18
+ }
@@ -2,6 +2,7 @@ import type { PushSubscriptionData } from "@mmmike/web-push/client";
2
2
  import { responseJson } from "@open-workspace/core/ui";
3
3
 
4
4
  import { mailApi } from "../lib/mail-api";
5
+ import { pushKeyMatches } from "./push-key";
5
6
 
6
7
  const SERVICE_WORKER_READY_TIMEOUT_MS = 10_000;
7
8
 
@@ -34,18 +35,6 @@ async function activeServiceWorkerRegistration() {
34
35
  }
35
36
  }
36
37
 
37
- async function createPushSubscription(
38
- registration: ServiceWorkerRegistration,
39
- publicKey: string
40
- ) {
41
- const { urlBase64ToUint8Array } = await import("@mmmike/web-push/vapid");
42
-
43
- return registration.pushManager.subscribe({
44
- userVisibleOnly: true,
45
- applicationServerKey: urlBase64ToUint8Array(publicKey),
46
- });
47
- }
48
-
49
38
  async function currentBrowserPushSubscription() {
50
39
  if (!pushIsSupported()) return null;
51
40
  const registration = await navigator.serviceWorker.getRegistration();
@@ -73,6 +62,39 @@ async function removeServerPushSubscription(endpoint: string) {
73
62
  );
74
63
  }
75
64
 
65
+ /**
66
+ * This browser's subscription for the server's current VAPID key: `current`
67
+ * when it was made with that key, else a new one in its place. A stage that
68
+ * is recreated has new keys, and the push service refuses what the server
69
+ * signs for a subscription made with the old ones.
70
+ */
71
+ async function subscriptionForKey(
72
+ registration: ServiceWorkerRegistration,
73
+ current: PushSubscription | null,
74
+ publicKey: string
75
+ ) {
76
+ const { urlBase64ToUint8Array } = await import("@mmmike/web-push/vapid");
77
+ const serverKey = urlBase64ToUint8Array(publicKey);
78
+
79
+ if (
80
+ current &&
81
+ pushKeyMatches(current.options.applicationServerKey, serverKey)
82
+ ) {
83
+ return current;
84
+ }
85
+
86
+ if (current) {
87
+ await removeServerPushSubscription(current.endpoint);
88
+ // The browser has one subscription per service worker; another key needs it gone first.
89
+ await current.unsubscribe();
90
+ }
91
+
92
+ return registration.pushManager.subscribe({
93
+ userVisibleOnly: true,
94
+ applicationServerKey: serverKey,
95
+ });
96
+ }
97
+
76
98
  /**
77
99
  * Before sign-out, stops this device getting the account's notifications.
78
100
  * The browser keeps its subscription, so the next person to sign in on this
@@ -92,27 +114,57 @@ export async function removePushSubscriptionForSignOut() {
92
114
  if (endpoint) await removeServerPushSubscription(endpoint);
93
115
  }
94
116
 
117
+ /** On sign-in or reconnect, claim this browser's subscription for the current session. */
95
118
  export async function syncCurrentPushSubscription() {
96
- const subscription = await currentBrowserPushSubscription();
119
+ if (!pushIsSupported()) return;
120
+ const registration = await navigator.serviceWorker.getRegistration();
121
+ const current = await registration?.pushManager.getSubscription();
122
+
123
+ if (!registration || !current) return;
124
+
125
+ if (Notification.permission === "denied") {
126
+ await removeServerPushSubscription(current.endpoint);
127
+
128
+ return;
129
+ }
130
+
131
+ if (Notification.permission !== "granted") return;
132
+
133
+ const config = await responseJson(
134
+ await mailApi.api.notifications.config.$get()
135
+ );
136
+
137
+ if (!config.publicKey) return;
138
+
139
+ const subscription = await subscriptionForKey(
140
+ registration,
141
+ current,
142
+ config.publicKey
143
+ );
97
144
 
98
- if (!subscription) return;
99
145
  await bindPushSubscription(await serializedSubscription(subscription));
100
146
  }
101
147
 
102
- export async function currentPushRegistrationStatus() {
148
+ /** Inspect this browser without registering it again just to display the settings. */
149
+ export async function currentPushRegistrationStatus(publicKey: string) {
103
150
  if (!pushIsSupported()) return "unsupported" as const;
104
- const subscription = await currentBrowserPushSubscription();
105
151
 
106
- if (Notification.permission === "denied") {
107
- if (subscription) await removeServerPushSubscription(subscription.endpoint);
152
+ if (Notification.permission === "denied") return "denied" as const;
108
153
 
109
- return "denied" as const;
110
- }
154
+ if (Notification.permission !== "granted") return "prompt" as const;
155
+
156
+ const subscription = await currentBrowserPushSubscription();
111
157
 
112
158
  if (!subscription) return "prompt" as const;
113
- await bindPushSubscription(await serializedSubscription(subscription));
114
159
 
115
- return "enabled" as const;
160
+ const { urlBase64ToUint8Array } = await import("@mmmike/web-push/vapid");
161
+
162
+ return pushKeyMatches(
163
+ subscription.options.applicationServerKey,
164
+ urlBase64ToUint8Array(publicKey)
165
+ )
166
+ ? ("enabled" as const)
167
+ : ("prompt" as const);
116
168
  }
117
169
 
118
170
  export async function enableCurrentPushSubscription(publicKey: string) {
@@ -126,11 +178,21 @@ export async function enableCurrentPushSubscription(publicKey: string) {
126
178
 
127
179
  const registration = await activeServiceWorkerRegistration();
128
180
 
129
- const subscription =
130
- (await registration.pushManager.getSubscription()) ??
131
- (await createPushSubscription(registration, publicKey));
181
+ const current = await registration.pushManager.getSubscription();
132
182
 
133
- await bindPushSubscription(await serializedSubscription(subscription));
183
+ const subscription = await subscriptionForKey(
184
+ registration,
185
+ current,
186
+ publicKey
187
+ );
188
+
189
+ try {
190
+ await bindPushSubscription(await serializedSubscription(subscription));
191
+ } catch (error) {
192
+ // Settings reads browser state. Roll back a new subscription if the server never confirmed it.
193
+ if (subscription !== current) await subscription.unsubscribe();
194
+ throw error;
195
+ }
134
196
  }
135
197
 
136
198
  export async function disableCurrentPushSubscription() {