@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,120 +1,50 @@
1
- import {
2
- aiObjectRunner,
3
- aiFeatureEnabled,
4
- aiModel,
5
- createId,
6
- normalizeMailboxAddress,
7
- deferWebhookTask,
8
- queueWebhookEvent,
9
- } from "@open-workspace/core/module";
10
- import type { AiModel } from "@open-workspace/core/module";
11
- import { required } from "@open-workspace/core/shared";
1
+ import { aiModel, inJsonList } from "@open-workspace/core/module";
12
2
  import { DurableObject } from "cloudflare:workers";
13
- import {
14
- and,
15
- asc,
16
- desc,
17
- eq,
18
- inArray,
19
- isNull,
20
- lt,
21
- lte,
22
- or,
23
- sql,
24
- } from "drizzle-orm";
3
+ import { and, desc, eq, isNotNull, or, min, sql } from "drizzle-orm";
25
4
  import { drizzle } from "drizzle-orm/durable-sqlite";
26
- import type { DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
27
5
  import { migrate } from "drizzle-orm/durable-sqlite/migrator";
28
- import { z } from "zod";
29
6
 
30
7
  import migrations from "../../drizzle/mailbox/migrations.js";
31
- import {
32
- FOLDER_ORDER_STEP,
33
- folderOrderPositions,
34
- isCompleteFolderOrder,
35
- sortFolders,
36
- } from "../../shared/folder-order";
37
- import {
38
- MAX_CUSTOM_FOLDER_COUNT,
39
- mailboxRealtimeUpdate,
40
- } from "../../shared/mail";
41
- import type {
42
- MailboxPushJob,
43
- MailboxRealtimeClientMessage,
44
- } from "../../shared/mail";
8
+ import { conversationFolder } from "../../shared/folder-order";
9
+ import { mailboxRealtimeUpdate } from "../../shared/mail";
10
+ import type { MailboxPushJob } from "../../shared/mail";
45
11
  import { blockPatternsFor } from "../../shared/mail-feedback";
46
- import type {
47
- FeedbackLabel,
48
- SenderBlock,
49
- Unsubscription,
50
- } from "../../shared/mail-feedback";
51
- import { headerValues } from "../../shared/mail-headers";
52
- import { MAX_IMPORTED_TEXT_CHARACTERS } from "../../shared/mail-import";
53
- import type { ImportPlacement } from "../../shared/mail-import";
54
- import {
55
- officePreviewExtension,
56
- officePreviewKey,
57
- } from "../../shared/office-preview";
58
- import {
59
- EMAIL_RECEIVED_EVENT,
60
- EMAIL_WEBHOOK_SOURCE,
61
- emailWebhookEventId,
62
- } from "../../shared/webhooks";
63
- import {
64
- classifyInboundEmail,
65
- EmailAiClassificationError,
66
- MAILBOX_AI_MAX_ATTEMPTS,
67
- } from "../mail/ai-classification";
68
- import { classificationSignals } from "../mail/classification-signals";
69
- import type { ClassificationSignals } from "../mail/classification-signals";
70
- import { deliveryFacts } from "../mail/delivery-facts";
71
- import {
72
- inboundMessageId,
73
- MissingRawMimeError,
74
- prepareInboundEmail,
75
- prepareUnprocessableInboundEmail,
76
- rawHeaderText,
77
- rawMessageId,
78
- readInboundRawMime,
79
- UnprocessableInboundEmailError,
80
- } from "../mail/inbound";
12
+ import type { Unsubscription } from "../../shared/mail-feedback";
13
+ import type { JmapStateMessage } from "../jmap/push-types";
14
+ import type { DraftSenders } from "../mail/draft-sender";
81
15
  import { listActiveMailboxSessions } from "../mail/mailbox-directory";
82
- import { messageSecurity } from "../mail/message-security";
83
- import { emailListKey } from "../mail/message-view";
84
- import { prepareOutboundDelivery } from "../mail/outbound-delivery";
16
+ import { hasNewRecipients } from "../mail/outbound-threading";
85
17
  import { suggestParticipants } from "../mail/participants";
86
18
  import type { ParticipantSource } from "../mail/participants";
87
- import { buildEmailSearchQuery } from "../mail/search";
88
- import { spamhausDqsKey, workspaceIdentity } from "../mail/security-settings";
89
- import type { WorkspaceIdentity } from "../mail/security-settings";
90
- import { collectSenderIntel } from "../mail/sender-intel";
19
+ import type { RecipientFields } from "../mail/recipients";
20
+ import type { RuleInput } from "../mail/rules";
21
+ import { officePreviewKey } from "../mail/storage-keys";
22
+ import { storeEmail } from "./email-index";
23
+ import type { MailboxState } from "./folder-model";
91
24
  import {
92
- workspaceBlockPatterns,
93
- workspaceFeedbackSummary,
94
- } from "../mail/workspace-safety";
95
- import { indexInsertedEmail } from "./email-index";
96
- import {
97
- customFolderPredicate,
98
- folderAggregateJoinPredicate,
99
- systemFolderDefinitions,
100
- systemFolderPredicate,
101
- } from "./folder-model";
102
- import type { MailboxState, SystemFolderType } from "./folder-model";
103
- import { mergedPlacement, requestedPlacement } from "./import-placement";
104
- import { readInboxCounts, writeInboxCounts } from "./inbox-counts";
25
+ advanceInboxCountsVersion,
26
+ readInboxCounts,
27
+ writeInboxCounts,
28
+ } from "./inbox-counts";
105
29
  import type { InboxCounts } from "./inbox-counts";
106
- import {
107
- bumpJmapState,
108
- emailPlacement as jmapEmailPlacement,
109
- jmapState,
110
- mailboxes as jmapMailboxRows,
111
- moveEmails as jmapMoveEmails,
112
- queryEmails as queryJmapEmails,
113
- threadEmails as jmapThreadEmails,
114
- } from "./jmap-store";
30
+ import { bumpJmapState, currentSeq, jmapState } from "./jmap-change-log";
31
+ import type { jmapChanges as jmapChangeLog } from "./jmap-change-log";
32
+ import { jmapEmails } from "./jmap-email-rows";
33
+ import type { MailboxChange } from "./jmap-placement";
34
+ import type { queryEmails as queryJmapEmails } from "./jmap-store";
35
+ import * as autoReplies from "./mailbox-auto-reply";
36
+ import * as mailboxBackup from "./mailbox-backup";
37
+ import * as mailboxDrafts from "./mailbox-drafts";
38
+ import * as mailboxFolders from "./mailbox-folders";
39
+ import * as mailboxImport from "./mailbox-import";
40
+ import * as mailboxInbound from "./mailbox-inbound";
41
+ import * as mailboxJmap from "./mailbox-jmap";
42
+ import * as mailboxOutbound from "./mailbox-outbound";
43
+ import * as mailboxRules from "./mailbox-rules";
44
+ import * as senderSafety from "./mailbox-senders";
45
+ import * as mailboxStorage from "./mailbox-storage";
46
+ import * as mailboxViews from "./mailbox-views";
115
47
  import type {
116
- EmailAiClassification,
117
- EmailScreening,
118
48
  MailboxAiConfiguration,
119
49
  RecipientDeliveryStatus,
120
50
  SenderIntel,
@@ -122,324 +52,113 @@ import type {
122
52
  import {
123
53
  dispatchOfficePreviewJobs,
124
54
  hasPendingOfficePreviews,
125
- insertOfficePreviewJobs,
126
55
  nextOfficePreviewAttempt,
127
56
  prepareOfficePreviews,
128
57
  } from "./office-preview-jobs";
58
+ import {
59
+ blocksForLeavingSpam,
60
+ fileConversations,
61
+ placeConversations,
62
+ } from "./placement";
63
+ import type { RetentionFolder } from "./retention";
129
64
  import {
130
65
  conversations,
66
+ drafts,
131
67
  emailReadStates,
68
+ pendingInbound,
69
+ pendingObjectDeletions,
132
70
  emails,
133
71
  folders,
134
72
  systemFolderOrder,
135
- mailboxAiConfiguration,
136
- pendingInbound,
137
- pendingObjectDeletions,
73
+ senderFeedback,
138
74
  senders,
139
75
  unsubscriptions,
140
76
  } from "./schema";
77
+ import type { NewEmail, NewFolder } from "./schema";
78
+ import { setSenderBlocked } from "./senders";
79
+ import {
80
+ withSpamUndo,
81
+ undoSpam,
82
+ nextSpamUndoExpiry,
83
+ expireSpamUndo,
84
+ } from "./spam-undo";
141
85
  import type {
142
- Email,
143
- FolderRecord,
144
- NewEmail,
145
- NewFolder,
146
- PendingInbound,
147
- } from "./schema";
86
+ AutoReplyInput,
87
+ ConversationCursorPosition,
88
+ ConversationPage,
89
+ ConversationUpdate,
90
+ DraftInput,
91
+ ImportMessageInput,
92
+ ImportOriginal,
93
+ InboundDeliveryInput,
94
+ MailboxBackupSettings,
95
+ MailboxDatabase,
96
+ MailboxSocketAttachment,
97
+ SendingDraft,
98
+ TransportUpdate,
99
+ MailboxContext,
100
+ } from "./support";
148
101
  import {
149
- blockFromPattern,
150
- listBlockedSenders,
151
- recordCorrespondents,
152
- recordSenderFeedback,
153
- senderFeedbackSummary,
154
- senderHistory,
155
- senderStatuses,
156
- setSenderBlocked,
157
- setSenderTrusted,
158
- workspaceBlockFor,
159
- } from "./senders";
160
-
161
- const schema = {
162
- conversations,
163
- emailReadStates,
164
- emails,
165
- folders,
166
- mailboxAiConfiguration,
167
- pendingInbound,
168
- pendingObjectDeletions,
169
- senders,
170
- unsubscriptions,
171
- };
172
-
173
- type MailboxDatabase = DrizzleSqliteDODatabase<typeof schema>;
174
-
175
- /** The change counter whose inbox counts D1 has (see `syncInboxCounts`). */
176
- const COUNTS_VERSION_KEY = "inboxCountsVersion";
177
- const INBOUND_ALARM_BATCH_SIZE = 1;
178
- const OBJECT_DELETION_ALARM_BATCH_SIZE = 100;
179
- const MAX_RETRY_DELAY_MS = 60 * 60 * 1000;
180
- const MAX_INBOUND_RETRY_AGE_MS = 24 * 60 * 60 * 1000;
181
- const ALARM_WAKE_DELAY_MS = 1000;
182
- const PRESENCE_TTL_MS = 60_000;
183
- const AI_CONFIGURATION_ID = "default";
184
-
185
- /** Set while imported mail has not been announced (counts, realtime, JMAP state). */
186
- const IMPORT_PENDING_KEY = "import:pending";
187
-
188
- /** How long imported mail may wait to be announced when the importer does not finish. */
189
- const IMPORT_ANNOUNCE_DELAY_MS = 15_000;
190
-
191
- /** Browser sessions, authorized against their session on every update. */
192
- const SESSION_SOCKET_TAG = "session";
193
-
194
- /** JMAP EventSource streams held by the Worker; they receive the new state. */
195
- const JMAP_SOCKET_TAG = "jmap";
196
-
197
- /** What a browser session sends: whether its tab is visible. */
198
- const visibilitySchema = z.enum([
199
- "visible",
200
- "hidden",
201
- ]) satisfies z.ZodType<MailboxRealtimeClientMessage>;
202
-
203
- /** Who a session socket belongs to; it survives hibernation with the socket. */
204
- const socketAttachmentSchema = z.object({
205
- userId: z.string(),
206
- sessionId: z.string(),
207
- sessionTokenHash: z.string(),
208
- visibility: visibilitySchema,
209
- presenceUpdatedAt: z.number(),
210
- });
211
-
212
- type MailboxSocketAttachment = z.output<typeof socketAttachmentSchema>;
213
-
214
- /** A session socket's attachment; null for other sockets (JMAP streams carry none). */
215
- function socketAttachment(socket: WebSocket): MailboxSocketAttachment | null {
216
- const attachment = socketAttachmentSchema.safeParse(
217
- socket.deserializeAttachment()
218
- );
219
-
220
- return attachment.success ? attachment.data : null;
221
- }
222
-
223
- function errorMessage(cause: unknown) {
224
- return cause instanceof Error ? cause.message : String(cause);
225
- }
226
-
227
- function retryDelay(attempts: number) {
228
- return Math.min(
229
- MAX_RETRY_DELAY_MS,
230
- 5000 * 2 ** Math.min(Math.max(attempts - 1, 0), 10)
231
- );
232
- }
233
-
234
- function stringListJson(values: string[]) {
235
- return JSON.stringify([...new Set(values)]);
236
- }
237
-
238
- export type ConversationUpdate = {
239
- mailboxState?: MailboxState;
240
- folderId?: string | null;
241
- };
242
-
243
- export type ConversationCursorPosition = {
244
- timelineAt: number;
245
- emailId: string;
246
- };
247
-
248
- export type ConversationListItem = {
249
- email: Email;
250
- messageCount: number;
251
- unreadCount: number;
252
- hasIncoming: boolean;
253
- };
254
-
255
- export type SubmitOutgoingResult = {
256
- outcome: "inserted" | "existing" | "conflict";
257
- email: Email;
258
- };
259
-
260
- export type InboundDeliveryInput = {
261
- id: string;
262
- mailboxId: string;
263
- rawObjectKey: string;
264
- envelopeFrom: string;
265
- envelopeTo: string;
266
- /** Set when this is a member's copy of mail to a workspace mailing list. */
267
- listAddress?: string;
268
- receivedAt: number;
269
- };
270
-
271
- export type ImportMessageInput = {
272
- /** The import's delivery id: the message is stored as `inboundMessageId(importId)`. */
273
- importId: string;
274
- /** Where the route stored the raw message. */
275
- rawObjectKey: string;
276
- /** The mailbox's own address, which tells sent mail from received. */
277
- mailboxAddress: string;
278
- /** When the message was received; the Date header (then now) without one. */
279
- receivedAt: number | null;
280
- placement: ImportPlacement;
281
- /** A custom folder (by name, created when missing) for a message in the Inbox. */
282
- folderName: string | null;
283
- /** The people a received message is read for. */
284
- seenBy: string[];
285
- /** The conversation the importer's thread key names; null threads by Message-ID headers. */
286
- conversationId: string | null;
287
- /** Null decides by the From address. */
288
- direction: "incoming" | "outgoing" | null;
289
- };
290
-
291
- export type ImportMessageResult =
292
- | {
293
- status: "imported";
294
- id: string;
295
- conversationId: string;
296
- /** Why the requested folder was not used, if it was not. */
297
- folderSkipped: "limit" | "invalid" | null;
298
- }
299
- | { status: "duplicate"; id: string; conversationId: string }
300
- | { status: "unprocessable"; reason: string };
301
-
302
- function clampText(value: string | null | undefined) {
303
- return value && value.length > MAX_IMPORTED_TEXT_CHARACTERS
304
- ? value.slice(0, MAX_IMPORTED_TEXT_CHARACTERS)
305
- : (value ?? null);
306
- }
307
-
308
- /** The Date header of a raw message, in ms, if it parses. */
309
- function headerDate(rawMime: ArrayBuffer) {
310
- const value = headerValues(rawHeaderText(rawMime), "date")[0];
311
- const time = value ? Date.parse(value) : Number.NaN;
312
-
313
- return Number.isFinite(time) ? time : null;
314
- }
315
-
316
- export type FolderListItem = {
317
- id: string;
318
- name: string;
319
- kind: "system" | "custom";
320
- systemType: SystemFolderType | null;
321
- sortOrder: number;
322
- totalCount: number;
323
- unreadCount: number;
324
- };
325
-
326
- type MailFolder =
327
- | (FolderRecord & { kind: "custom"; systemType: null })
328
- | {
329
- id: string;
330
- name: string;
331
- kind: "system";
332
- systemType: SystemFolderType;
333
- sortOrder: number;
334
- };
335
-
336
- type ConversationRow = {
337
- email_id: string;
338
- timeline_at: number;
339
- message_count: number;
340
- unread_count: number;
341
- has_incoming: number;
342
- };
343
-
344
- type ConversationSnapshotCountRow = {
345
- message_count: number;
346
- unread_count: number;
347
- };
348
-
349
- type FolderCountRow = {
350
- total_count: number;
351
- unread_count: number;
352
- };
353
-
354
- type FolderListRow = {
355
- id: string;
356
- name: string;
357
- kind: "system" | "custom";
358
- system_type: SystemFolderType | null;
359
- sort_order: number;
360
- total_count: number;
361
- unread_count: number;
362
- };
363
-
364
- export type FolderCounts = {
365
- totalCount: number;
366
- unreadCount: number;
367
- };
368
-
369
- function folderMembership(folder: MailFolder) {
370
- if (folder.kind === "custom") {
371
- return {
372
- predicate: `
373
- c.folder_id = ?
374
- and ${customFolderPredicate("c")}
375
- `,
376
- bindings: [folder.id],
377
- };
378
- }
379
-
380
- return {
381
- predicate: systemFolderPredicate(folder.systemType, "c"),
382
- bindings: [],
383
- };
384
- }
385
-
386
- const FOLDER_AGGREGATE_JOIN_PREDICATE = folderAggregateJoinPredicate(
387
- "folder",
388
- "conversation"
389
- );
390
-
391
- export type TransportUpdate = {
392
- state: Email["transportState"];
393
- messageIdHeader?: string;
394
- error?: string | null;
395
- };
396
-
397
- /** Where an incoming message lands, decided before it is stored. */
398
- type InboundPlacement = {
399
- state: "spam" | null;
400
- folderId: string | null;
401
- };
402
-
403
- type InboundScreening = {
404
- block: SenderBlock | null;
405
- trusted: boolean;
406
- };
407
-
408
- const LIKE_ESCAPE = (value: string) =>
409
- value.replaceAll(/[\\%_]/gu, (char) => `\\${char}`);
410
-
411
- /** SQL predicate on a lowercased address expression for a block pattern. */
412
- function blockPatternPredicate(expression: string, pattern: string) {
413
- if (!pattern.startsWith("@")) {
414
- return { sql: `${expression} = ?`, bindings: [pattern] };
415
- }
416
-
417
- const domain = LIKE_ESCAPE(pattern.slice(1));
418
-
419
- return {
420
- sql: `(${expression} like ? escape '\\' or ${expression} like ? escape '\\')`,
421
- bindings: [`%@${domain}`, `%.${domain}`],
422
- };
423
- }
102
+ ALARM_WAKE_DELAY_MS,
103
+ COUNTS_VERSION_KEY,
104
+ WEB_VERSION_KEY,
105
+ IMPORT_PENDING_KEY,
106
+ JMAP_SOCKET_TAG,
107
+ PRESENCE_TTL_MS,
108
+ SESSION_SOCKET_TAG,
109
+ folderMembership,
110
+ schema,
111
+ socketAttachment,
112
+ visibilitySchema,
113
+ } from "./support";
424
114
 
425
115
  export class MailboxDO extends DurableObject<Env> {
426
116
  private readonly db: MailboxDatabase;
427
117
  private readonly state: DurableObjectState;
428
- private readonly bindings: Env;
118
+ private readonly context: MailboxContext;
119
+ /** Messages being handed to Email Sending now; one send each at a time. */
120
+ private readonly sending = new Set<string>();
429
121
  private recentParticipantSources: ParticipantSource[] | null = null;
430
122
  /** The running D1 write of the inbox counts; see `syncInboxCounts`. */
431
123
  private countsWrite: Promise<void> | null = null;
432
- private countsDirty = false;
124
+ private pendingCounts: "recount" | "version" | null = null;
433
125
  /** What the last successful write stored, so the next writes only what changed. */
434
126
  private writtenCounts: InboxCounts | null = null;
435
127
  /** The D1 bookmark after that write; realtime messages pass it on. */
436
128
  private countsBookmark: string | null = null;
129
+ /**
130
+ * The wake this alarm set before parsing a delivery, for when it is killed
131
+ * mid-parse; replaced by the real next wake once the attempt finishes.
132
+ */
133
+ private attemptAlarmAt: number | null = null;
437
134
 
438
135
  constructor(ctx: DurableObjectState, env: Env) {
439
136
  super(ctx, env);
440
137
  this.state = ctx;
441
- this.bindings = env;
442
138
  this.db = drizzle(ctx.storage, { schema });
139
+
140
+ this.context = {
141
+ db: this.db,
142
+ state: ctx,
143
+ env,
144
+ announce: (options) => this.announce(options),
145
+ scheduleAlarm: (at) => this.scheduleAlarm(at),
146
+ scheduleRetention: () => this.scheduleRetention(),
147
+ getEmail: (id) => this.getEmail(id),
148
+ resolveParent: (inReplyTo, references) =>
149
+ this.resolveParent(inReplyTo, references),
150
+ forgetParticipants: () => {
151
+ this.recentParticipantSources = null;
152
+ },
153
+ getEmailByMessageId: (messageIdHeader) =>
154
+ this.getEmailByMessageId(messageIdHeader),
155
+ classificationModel: () => this.classificationModel(),
156
+ noteAttemptAlarm: (at) => {
157
+ this.attemptAlarmAt = at;
158
+ },
159
+ version: () => this.version(),
160
+ sending: this.sending,
161
+ };
443
162
  ctx.blockConcurrencyWhile(async () => {
444
163
  await migrate(this.db, migrations);
445
164
 
@@ -531,13 +250,16 @@ export class MailboxDO extends DurableObject<Env> {
531
250
  await this.state.storage.deleteAll();
532
251
  }
533
252
 
534
- async shouldSuppressPush(messageId: string, userId: string) {
253
+ async pushDestination(messageId: string, userId: string) {
535
254
  const messageState = this.db
536
255
  .select({
537
- messageId: emails.id,
256
+ conversationId: conversations.id,
257
+ mailboxState: conversations.mailboxState,
258
+ folderId: conversations.folderId,
538
259
  readByUserId: emailReadStates.userId,
539
260
  })
540
261
  .from(emails)
262
+ .innerJoin(conversations, eq(emails.conversationId, conversations.id))
541
263
  .leftJoin(
542
264
  emailReadStates,
543
265
  and(
@@ -548,10 +270,20 @@ export class MailboxDO extends DurableObject<Env> {
548
270
  .where(eq(emails.id, messageId))
549
271
  .get();
550
272
 
551
- if (!messageState || messageState.readByUserId) return true;
273
+ if (messageState?.mailboxState !== "active" || messageState.readByUserId) {
274
+ return null;
275
+ }
276
+
552
277
  const visibleAfter = Date.now() - PRESENCE_TTL_MS;
553
278
 
554
- return (await this.authorizedSockets({ userId, visibleAfter })).length > 0;
279
+ if ((await this.authorizedSockets({ userId, visibleAfter })).length) {
280
+ return null;
281
+ }
282
+
283
+ return {
284
+ conversationId: messageState.conversationId,
285
+ folder: conversationFolder(messageState),
286
+ };
555
287
  }
556
288
 
557
289
  private async authorizedSockets(filter?: {
@@ -598,7 +330,7 @@ export class MailboxDO extends DurableObject<Env> {
598
330
  ];
599
331
 
600
332
  const validSessions = await listActiveMailboxSessions(
601
- this.bindings.DB,
333
+ this.env.DB,
602
334
  mailboxId,
603
335
  sessionIds,
604
336
  Date.now()
@@ -666,10 +398,14 @@ export class MailboxDO extends DurableObject<Env> {
666
398
  /**
667
399
  * The change counter that realtime updates carry (`update:<version>`).
668
400
  * Reads return it so clients can tell whether their data already has a
669
- * change they are told about.
401
+ * change they are told about. It moves only with an announcement web
402
+ * clients hear: a change only JMAP sees (a draft's autosave) would make
403
+ * a client's next own change look like someone else's.
670
404
  */
671
405
  private version() {
672
- return Number(jmapState(this.state.storage));
406
+ return (
407
+ this.state.storage.kv.get<number>(WEB_VERSION_KEY) ?? currentSeq(this.db)
408
+ );
673
409
  }
674
410
 
675
411
  /**
@@ -679,8 +415,11 @@ export class MailboxDO extends DurableObject<Env> {
679
415
  * at the latest counts. Settles once D1 has them (failures are logged and
680
416
  * retried by the next change or start).
681
417
  */
682
- private syncInboxCounts(): Promise<void> {
683
- this.countsDirty = true;
418
+ private syncInboxCounts(recount = true) {
419
+ // A version-only announcement must never downgrade a pending recount.
420
+ this.pendingCounts = recount
421
+ ? "recount"
422
+ : (this.pendingCounts ?? "version");
684
423
 
685
424
  if (!this.countsWrite) {
686
425
  // Started after the assignment, so its `finally` clears this one.
@@ -695,24 +434,23 @@ export class MailboxDO extends DurableObject<Env> {
695
434
  const mailboxId = this.state.id.name;
696
435
 
697
436
  try {
698
- // countsDirty is set again by writes while the await below is pending.
699
- // oxlint-disable-next-line no-unmodified-loop-condition
700
- while (mailboxId && this.countsDirty) {
701
- this.countsDirty = false;
437
+ if (!mailboxId) return;
438
+
439
+ while (this.pendingCounts) {
440
+ const recount = this.pendingCounts === "recount";
441
+ this.pendingCounts = null;
702
442
  const version = this.version();
703
- const counts = readInboxCounts(this.state.storage.sql);
704
- // oxlint-disable-next-line eslint/no-await-in-loop -- writes the counts again until no write raced this one; each write needs the previous counts
705
- this.countsBookmark = await writeInboxCounts(this.bindings.DB, {
443
+ // oxlint-disable-next-line eslint/no-await-in-loop -- commit versions to D1 in order
444
+ this.countsBookmark = await this.writeInboxVersion(
706
445
  mailboxId,
707
446
  version,
708
- counts,
709
- previous: this.writtenCounts,
710
- });
711
- this.writtenCounts = counts;
447
+ recount
448
+ );
712
449
  this.state.storage.kv.put(COUNTS_VERSION_KEY, version);
713
450
  }
714
451
  } catch (error) {
715
452
  // The stored version stays behind, so the next start writes them again.
453
+ this.pendingCounts = "recount";
716
454
  this.writtenCounts = null;
717
455
  console.error("Could not write mailbox counts to D1", error);
718
456
  } finally {
@@ -720,27 +458,73 @@ export class MailboxDO extends DurableObject<Env> {
720
458
  }
721
459
  }
722
460
 
723
- private publishUpdate() {
724
- bumpJmapState(this.state.storage);
725
- const countsWritten = this.syncInboxCounts();
726
- this.state.waitUntil(
727
- this.broadcastUpdate(countsWritten).catch((error) => {
728
- console.error("Could not authorize realtime delivery", error);
729
- })
730
- );
731
- this.announceJmapState();
461
+ private async writeInboxVersion(
462
+ mailboxId: string,
463
+ version: number,
464
+ recount: boolean
465
+ ) {
466
+ if (!recount) {
467
+ const advanced = await advanceInboxCountsVersion(
468
+ this.env.DB,
469
+ mailboxId,
470
+ version
471
+ );
472
+
473
+ if (advanced) return advanced.bookmark;
474
+ // The row is missing in D1. Rebuild the counts and all per-person rows.
475
+ this.writtenCounts = null;
476
+ }
477
+
478
+ const counts = readInboxCounts(this.db);
479
+
480
+ const bookmark = await writeInboxCounts(this.env.DB, {
481
+ mailboxId,
482
+ version,
483
+ counts,
484
+ previous: this.writtenCounts,
485
+ });
486
+
487
+ this.writtenCounts = counts;
488
+
489
+ return bookmark;
490
+ }
491
+
492
+ /** See `MailboxContext.announce`. */
493
+ private announce({
494
+ web = true,
495
+ push = true,
496
+ delivered = false,
497
+ inboxChanged = true,
498
+ } = {}) {
499
+ bumpJmapState(this.db);
500
+ let countsWritten = Promise.resolve();
501
+
502
+ if (web) {
503
+ this.state.storage.kv.put(WEB_VERSION_KEY, currentSeq(this.db));
504
+ countsWritten = this.syncInboxCounts(inboxChanged);
505
+ this.state.waitUntil(
506
+ this.broadcastUpdate(countsWritten).catch((error) => {
507
+ console.error("Could not authorize realtime delivery", error);
508
+ })
509
+ );
510
+ }
511
+
512
+ this.announceJmapState(push, delivered);
513
+
514
+ return countsWritten;
732
515
  }
733
516
 
734
517
  /** Tells JMAP EventSource streams and (unless `push` is false) push subscribers the new state. */
735
- private announceJmapState(push = true) {
518
+ private announceJmapState(push: boolean, delivered: boolean) {
736
519
  const mailboxId = this.state.id.name;
737
520
 
738
521
  if (!mailboxId) return;
739
- const state = jmapState(this.state.storage);
522
+ const state = jmapState(this.db);
523
+ const message: JmapStateMessage = { state, delivered };
740
524
 
741
525
  for (const socket of this.state.getWebSockets(JMAP_SOCKET_TAG)) {
742
526
  try {
743
- socket.send(state);
527
+ socket.send(JSON.stringify(message));
744
528
  } catch {
745
529
  socket.close(1011, "Could not deliver realtime event");
746
530
  }
@@ -752,516 +536,244 @@ export class MailboxDO extends DurableObject<Env> {
752
536
  type: "jmap-state",
753
537
  mailboxId,
754
538
  state,
539
+ delivered,
755
540
  occurredAt: Date.now(),
756
541
  };
757
542
 
758
543
  this.state.waitUntil(
759
- this.bindings.PUSH_NOTIFICATIONS.send(job).catch((error) => {
544
+ this.env.PUSH_NOTIFICATIONS.send(job).catch((error) => {
760
545
  console.error("Could not queue JMAP push", error);
761
546
  })
762
547
  );
763
548
  }
764
549
 
765
- private queueIncomingNotification(email: Email) {
766
- if (email.direction !== "incoming") return;
767
- const sender = email.fromJson[0];
768
-
769
- const job: MailboxPushJob = {
770
- type: "dispatch",
771
- mailboxId: this.state.id.name ?? "unknown-mailbox",
772
- conversationId: email.conversationId,
773
- messageId: email.id,
774
- occurredAt: Date.now(),
775
- sender: sender?.name || sender?.address || "Unknown sender",
776
- subject: email.subject,
777
- };
550
+ listConversations(
551
+ userId: string,
552
+ folderId: string,
553
+ limit: number,
554
+ cursor: ConversationCursorPosition | null,
555
+ search: string | undefined,
556
+ unreadOnly = false,
557
+ draftSenders?: DraftSenders
558
+ ) {
559
+ const page: ConversationPage | null = mailboxViews.listConversations(
560
+ this.context,
561
+ userId,
562
+ folderId,
563
+ limit,
564
+ cursor,
565
+ search,
566
+ unreadOnly,
567
+ draftSenders
568
+ );
778
569
 
779
- return this.bindings.PUSH_NOTIFICATIONS.send(job);
570
+ return page;
780
571
  }
781
572
 
782
- private retryStoredInboundNotification(
783
- job: PendingInbound,
784
- now: number,
785
- cause: unknown
786
- ) {
787
- if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
788
- this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
789
- console.error(
790
- `Stopped retrying notification for inbound delivery ${job.id}`,
791
- cause
792
- );
793
-
794
- return;
795
- }
573
+ getFolder(id: string) {
574
+ return mailboxFolders.getFolder(this.context, id);
575
+ }
796
576
 
797
- const attempts = job.attempts + 1;
798
- this.db
799
- .update(pendingInbound)
800
- .set({
801
- attempts,
802
- nextAttemptAt: new Date(now + retryDelay(attempts)),
803
- })
804
- .where(eq(pendingInbound.id, job.id))
805
- .run();
806
- console.error(
807
- `Could not queue notification for inbound delivery ${job.id}`,
808
- cause
809
- );
577
+ createFolder(id: string, name: string) {
578
+ return mailboxFolders.createFolder(this.context, id, name);
810
579
  }
811
580
 
812
- private async finishStoredInbound(
813
- job: PendingInbound,
814
- email: Email,
815
- now: number,
816
- announce: boolean
817
- ) {
818
- try {
819
- const mailboxId = this.state.id.name ?? "unknown-mailbox";
820
- deferWebhookTask(
821
- (task) => this.state.waitUntil(task),
822
- () =>
823
- queueWebhookEvent(this.bindings, {
824
- eventId: emailWebhookEventId(
825
- EMAIL_RECEIVED_EVENT,
826
- mailboxId,
827
- email.id
828
- ),
829
- eventType: EMAIL_RECEIVED_EVENT,
830
- occurredAt: email.timelineAt.getTime(),
831
- source: {
832
- kind: EMAIL_WEBHOOK_SOURCE,
833
- mailboxId,
834
- messageId: email.id,
835
- },
836
- })
837
- );
581
+ renameFolder(id: string, name: string) {
582
+ return mailboxFolders.renameFolder(this.context, id, name);
583
+ }
838
584
 
839
- if (announce) this.publishUpdate();
585
+ deleteFolder(id: string) {
586
+ return mailboxFolders.deleteFolder(this.context, id);
587
+ }
840
588
 
841
- const conversation = this.db
842
- .select({ mailboxState: conversations.mailboxState })
843
- .from(conversations)
844
- .where(eq(conversations.id, email.conversationId))
845
- .all()[0];
589
+ reorderFolders(folderIds: string[]) {
590
+ return mailboxFolders.reorderFolders(this.context, folderIds);
591
+ }
846
592
 
847
- if (conversation?.mailboxState !== "spam") {
848
- await this.queueIncomingNotification(email);
849
- }
593
+ listRules() {
594
+ return mailboxRules.listRules(this.context);
595
+ }
850
596
 
851
- this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
852
- } catch (error) {
853
- this.retryStoredInboundNotification(job, now, error);
854
- }
597
+ createRule(input: RuleInput) {
598
+ return mailboxRules.createRule(this.context, input);
855
599
  }
856
600
 
857
- listConversations(
858
- userId: string,
859
- folderId: string,
860
- limit: number,
861
- cursor: ConversationCursorPosition | null,
862
- search: string | undefined,
863
- unreadOnly = false
864
- ) {
865
- const folder = this.getFolder(folderId);
601
+ setRuleEnabled(id: string, enabled: boolean) {
602
+ return mailboxRules.setRuleEnabled(this.context, id, enabled);
603
+ }
866
604
 
867
- if (!folder) return null;
868
- const membership = folderMembership(folder);
869
- const searchQuery = search ? buildEmailSearchQuery(search) : undefined;
605
+ updateRule(id: string, input: Omit<RuleInput, "enabled">) {
606
+ return mailboxRules.updateRule(this.context, id, input);
607
+ }
870
608
 
871
- if (search && !searchQuery) {
872
- return { items: [], next: null, version: this.version() };
873
- }
609
+ deleteRule(id: string) {
610
+ return mailboxRules.deleteRule(this.context, id);
611
+ }
874
612
 
875
- const predicates = [membership.predicate];
876
- const bindings: (string | number)[] = [...membership.bindings];
877
-
878
- if (unreadOnly) {
879
- predicates.push(`exists (
880
- select 1
881
- from emails unread_message
882
- where unread_message.conversation_id = c.id
883
- and unread_message.direction = 'incoming'
884
- and not exists (
885
- select 1
886
- from email_read_states unread_state
887
- where unread_state.user_id = ?
888
- and unread_state.email_id = unread_message.id
889
- )
890
- )`);
891
- bindings.push(userId);
892
- }
613
+ reorderRules(ruleIds: string[]) {
614
+ return mailboxRules.reorderRules(this.context, ruleIds);
615
+ }
893
616
 
894
- if (searchQuery) {
895
- // Folder membership belongs to the conversation, while a match can be in
896
- // any message in that conversation.
897
- predicates.push(`c.id in (
898
- select conversation_id
899
- from email_search
900
- where email_search match ?
901
- )`);
902
- bindings.push(searchQuery);
903
- }
617
+ testRule(rule: Pick<RuleInput, "match" | "conditions">) {
618
+ return mailboxRules.testRule(this.context, rule);
619
+ }
904
620
 
905
- if (cursor) {
906
- predicates.push(
907
- "(c.timeline_at < ? or (c.timeline_at = ? and c.latest_email_id < ?))"
908
- );
909
- bindings.push(cursor.timelineAt, cursor.timelineAt, cursor.emailId);
910
- }
621
+ getMailboxAiSettings() {
622
+ return mailboxRules.getMailboxAiSettings(this.context);
623
+ }
911
624
 
912
- bindings.push(limit + 1);
913
-
914
- const rows = this.state.storage.sql
915
- .exec<ConversationRow>(
916
- `
917
- select
918
- c.latest_email_id as email_id,
919
- c.timeline_at,
920
- c.has_incoming,
921
- (
922
- select count(*)
923
- from emails message
924
- where message.conversation_id = c.id
925
- ) as message_count,
926
- (
927
- select count(*)
928
- from emails message
929
- where message.conversation_id = c.id
930
- and message.direction = 'incoming'
931
- and not exists (
932
- select 1
933
- from email_read_states read_state
934
- where read_state.user_id = ?
935
- and read_state.email_id = message.id
936
- )
937
- ) as unread_count
938
- from conversations c
939
- where ${predicates.join(" and ")}
940
- order by c.timeline_at desc, c.latest_email_id desc
941
- limit ?
942
- `,
943
- userId,
944
- ...bindings
945
- )
946
- .toArray();
947
-
948
- const pageRows = rows.slice(0, limit);
949
- const emailIds = pageRows.map((row) => row.email_id);
950
-
951
- const emailRows = emailIds.length
952
- ? this.db.select().from(emails).where(inArray(emails.id, emailIds)).all()
953
- : [];
954
-
955
- const emailsById = new Map(emailRows.map((email) => [email.id, email]));
956
-
957
- const items = pageRows.flatMap((row): ConversationListItem[] => {
958
- const email = emailsById.get(row.email_id);
959
-
960
- return email
961
- ? [
962
- {
963
- email,
964
- messageCount: Number(row.message_count),
965
- unreadCount: Number(row.unread_count),
966
- hasIncoming: Boolean(row.has_incoming),
967
- },
968
- ]
969
- : [];
970
- });
625
+ setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
626
+ return mailboxRules.setMailboxAiConfiguration(this.context, configuration);
627
+ }
971
628
 
972
- const last = pageRows.at(-1);
629
+ listDrafts(userId: string) {
630
+ return mailboxDrafts.listDrafts(this.context, userId);
631
+ }
973
632
 
633
+ /** The person's drafts with the mailbox version they reflect, for clients that refresh by it. */
634
+ versionedDrafts(userId: string) {
974
635
  return {
975
- items,
976
- next:
977
- rows.length > limit && last
978
- ? { timelineAt: Number(last.timeline_at), emailId: last.email_id }
979
- : null,
636
+ drafts: mailboxDrafts.listDrafts(this.context, userId),
980
637
  version: this.version(),
981
638
  };
982
639
  }
983
640
 
984
- /** The system folders at their places in the mailbox's folder order. */
985
- private systemFolders() {
986
- const stored = new Map(
987
- this.db
988
- .select()
989
- .from(systemFolderOrder)
990
- .all()
991
- .map((row) => [row.folderId, row.sortOrder])
992
- );
993
-
994
- return systemFolderDefinitions.map((folder) => ({
995
- ...folder,
996
- sortOrder:
997
- folder.id === "inbox" ? 0 : (stored.get(folder.id) ?? folder.sortOrder),
998
- }));
641
+ getDraft(userId: string, id: string) {
642
+ return mailboxDrafts.getDraft(this.context, userId, id);
999
643
  }
1000
644
 
1001
- getFolder(id: string): MailFolder | null {
1002
- const system = this.systemFolders().find((folder) => folder.id === id);
1003
-
1004
- if (system) {
1005
- return {
1006
- ...system,
1007
- kind: "system",
1008
- };
1009
- }
1010
-
1011
- const custom = this.db
1012
- .select()
1013
- .from(folders)
1014
- .where(eq(folders.id, id))
1015
- .all()[0];
1016
-
1017
- return custom ? { ...custom, kind: "custom", systemType: null } : null;
645
+ draftForEditor(userId: string, id: string) {
646
+ return mailboxDrafts.draftForEditor(this.context, userId, id);
1018
647
  }
1019
648
 
1020
- private folderNameTaken(name: string, excludingId?: string) {
1021
- const normalized = name.toLocaleLowerCase("en-US");
1022
-
649
+ getDraftAttachments(userId: string, id: string) {
1023
650
  return (
1024
- systemFolderDefinitions.some(
1025
- (folder) => folder.name.toLocaleLowerCase("en-US") === normalized
1026
- ) ||
1027
651
  this.db
1028
- .select({ id: folders.id, name: folders.name })
1029
- .from(folders)
1030
- .all()
1031
- .some(
1032
- (folder) =>
1033
- folder.id !== excludingId &&
1034
- folder.name.toLocaleLowerCase("en-US") === normalized
1035
- )
652
+ .select({ files: drafts.attachments })
653
+ .from(drafts)
654
+ .where(and(eq(drafts.userId, userId), eq(drafts.id, id)))
655
+ .get()?.files ?? []
1036
656
  );
1037
657
  }
1038
658
 
1039
- createFolder(id: string, name: string) {
1040
- const result = this.insertFolder(id, name);
1041
-
1042
- if (result.status === "ok") this.publishUpdate();
1043
-
1044
- return result;
659
+ saveDraft(
660
+ userId: string,
661
+ input: DraftInput,
662
+ expectedVersion: number,
663
+ copiedKeys: string[] = []
664
+ ) {
665
+ return mailboxDrafts.saveDraft(
666
+ this.context,
667
+ userId,
668
+ input,
669
+ expectedVersion,
670
+ copiedKeys
671
+ );
1045
672
  }
1046
673
 
1047
- private insertFolder(id: string, name: string) {
1048
- const normalizedName = name.trim();
1049
-
1050
- if (!normalizedName || normalizedName.length > 80) {
1051
- return { status: "invalid" as const };
1052
- }
1053
-
1054
- const existing = this.db
1055
- .select({ id: folders.id, sortOrder: folders.sortOrder })
1056
- .from(folders)
1057
- .all();
1058
-
1059
- if (existing.length >= MAX_CUSTOM_FOLDER_COUNT) {
1060
- return { status: "limit" as const };
1061
- }
1062
-
1063
- if (this.folderNameTaken(normalizedName)) {
1064
- return { status: "conflict" as const };
1065
- }
674
+ discardDrafts(userId: string, selected: { id: string; version: number }[]) {
675
+ return mailboxDrafts.discardDrafts(this.context, userId, selected);
676
+ }
1066
677
 
1067
- // A new folder goes to the end of the whole order, system folders included.
1068
- const last = Math.max(
1069
- ...existing.map((item) => item.sortOrder),
1070
- ...this.systemFolders().map((item) => item.sortOrder)
1071
- );
678
+ deleteDraft(userId: string, id: string, version?: number) {
679
+ return mailboxDrafts.deleteDraft(this.context, userId, id, version);
680
+ }
1072
681
 
1073
- const folder = this.db
1074
- .insert(folders)
1075
- .values({ id, name: normalizedName, sortOrder: last + FOLDER_ORDER_STEP })
1076
- .returning()
682
+ holdsDraftFile(userId: string, key: string) {
683
+ return !!this.db
684
+ .select({ id: drafts.id })
685
+ .from(drafts)
686
+ .where(
687
+ and(
688
+ eq(drafts.userId, userId),
689
+ sql`exists (
690
+ select 1 from json_each(${drafts.attachments}) where value ->> 'r2Key' = ${key}
691
+ )`
692
+ )
693
+ )
694
+ .limit(1)
1077
695
  .get();
1078
-
1079
- return { status: "ok" as const, folder };
1080
696
  }
1081
697
 
1082
- renameFolder(id: string, name: string) {
1083
- const normalizedName = name.trim();
1084
-
1085
- if (!normalizedName || normalizedName.length > 80) {
1086
- return { status: "invalid" as const };
1087
- }
1088
-
1089
- if (
1090
- !this.getFolder(id) ||
1091
- systemFolderDefinitions.some((item) => item.id === id)
1092
- ) {
1093
- return { status: "not_found" as const };
1094
- }
1095
-
1096
- if (this.folderNameTaken(normalizedName, id)) {
1097
- return { status: "conflict" as const };
1098
- }
1099
-
1100
- const [folder] = this.db
1101
- .update(folders)
1102
- .set({ name: normalizedName })
1103
- .where(eq(folders.id, id))
1104
- .returning()
1105
- .all();
1106
-
1107
- if (!folder) return { status: "not_found" as const };
1108
- this.publishUpdate();
698
+ forgetDraftFiles(objectKeys: string[]) {
699
+ return mailboxDrafts.forgetDraftFiles(this.context, objectKeys);
700
+ }
1109
701
 
1110
- return { status: "ok" as const, folder };
702
+ jmapState() {
703
+ return mailboxJmap.jmapState(this.context);
1111
704
  }
1112
705
 
1113
- deleteFolder(id: string) {
1114
- const deleted = this.db
1115
- .delete(folders)
1116
- .where(eq(folders.id, id))
1117
- .returning({ id: folders.id })
1118
- .all()[0];
706
+ jmapChanges(input: Parameters<typeof jmapChangeLog>[1]) {
707
+ return mailboxJmap.jmapChanges(this.context, input);
708
+ }
1119
709
 
1120
- if (!deleted) return { status: "not_found" as const };
1121
- this.publishUpdate();
710
+ jmapMailboxes(userId: string, withCounts = true) {
711
+ return mailboxJmap.jmapMailboxes(this.context, userId, withCounts);
712
+ }
1122
713
 
1123
- return { status: "ok" as const };
714
+ jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
715
+ return mailboxJmap.jmapQueryEmails(this.context, input);
1124
716
  }
1125
717
 
1126
- /**
1127
- * Sets the one order of every folder but Inbox: each system folder and
1128
- * custom folder exactly once, so system folders can sit among custom ones.
1129
- */
1130
- reorderFolders(folderIds: string[]) {
1131
- const customIds = this.db
1132
- .select({ id: folders.id })
1133
- .from(folders)
1134
- .all()
1135
- .map((folder) => folder.id);
1136
-
1137
- if (!isCompleteFolderOrder(folderIds, customIds)) {
1138
- return { status: "conflict" as const };
1139
- }
718
+ jmapQueryChanges(input: Parameters<typeof mailboxJmap.jmapQueryChanges>[1]) {
719
+ return mailboxJmap.jmapQueryChanges(this.context, input);
720
+ }
1140
721
 
1141
- const custom = new Set(customIds);
1142
- this.db.transaction((tx) => {
1143
- for (const { id, sortOrder } of folderOrderPositions(folderIds)) {
1144
- if (custom.has(id)) {
1145
- tx.update(folders).set({ sortOrder }).where(eq(folders.id, id)).run();
1146
- } else {
1147
- tx.insert(systemFolderOrder)
1148
- .values({ folderId: id, sortOrder })
1149
- .onConflictDoUpdate({
1150
- target: systemFolderOrder.folderId,
1151
- set: { sortOrder },
1152
- })
1153
- .run();
1154
- }
1155
- }
1156
- });
1157
- this.publishUpdate();
722
+ jmapEmails(userId: string, ids: string[], properties?: string[] | null) {
723
+ return jmapEmails(this.context, userId, ids, properties);
724
+ }
1158
725
 
1159
- return { status: "ok" as const };
726
+ jmapThreads(ids: string[], userId: string) {
727
+ return mailboxJmap.jmapThreads(this.context, ids, userId);
1160
728
  }
1161
729
 
1162
- private aiConfiguration(): MailboxAiConfiguration {
1163
- const stored = this.db
1164
- .select()
1165
- .from(mailboxAiConfiguration)
1166
- .where(eq(mailboxAiConfiguration.id, AI_CONFIGURATION_ID))
1167
- .all()[0];
730
+ jmapChangeMailboxes(
731
+ changes: { emailId: string; change: MailboxChange }[],
732
+ by: { userId: string; trustSenders: boolean }
733
+ ) {
734
+ return mailboxJmap.jmapChangeMailboxes(this.context, changes, by);
735
+ }
1168
736
 
1169
- return stored
1170
- ? {
1171
- instructions: stored.instructions,
1172
- confidenceThreshold: stored.confidenceThreshold,
1173
- }
1174
- : {
1175
- instructions: "",
1176
- confidenceThreshold: 75,
1177
- };
737
+ listBackupEmails(afterId: string | null, limit: number, newLimit: number) {
738
+ return mailboxBackup.listBackupEmails(
739
+ this.context,
740
+ afterId,
741
+ limit,
742
+ newLimit
743
+ );
1178
744
  }
1179
745
 
1180
- getMailboxAiSettings() {
1181
- return {
1182
- configuration: this.aiConfiguration(),
1183
- globalEnabled: aiFeatureEnabled("classification"),
1184
- };
746
+ listBackupDrafts(after: mailboxBackup.BackupDraftKey | null) {
747
+ return mailboxBackup.listBackupDrafts(this.context, after);
1185
748
  }
1186
749
 
1187
- setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
1188
- if (
1189
- configuration.confidenceThreshold < 50 ||
1190
- configuration.confidenceThreshold > 100 ||
1191
- configuration.instructions.length > 4000
1192
- ) {
1193
- throw new Error("Invalid mailbox AI configuration");
1194
- }
750
+ backupSettings() {
751
+ return mailboxBackup.backupSettings(this.context);
752
+ }
1195
753
 
1196
- this.db
1197
- .insert(mailboxAiConfiguration)
1198
- .values({
1199
- id: AI_CONFIGURATION_ID,
1200
- instructions: configuration.instructions.trim(),
1201
- confidenceThreshold: configuration.confidenceThreshold,
1202
- updatedAt: new Date(),
1203
- })
1204
- .onConflictDoUpdate({
1205
- target: mailboxAiConfiguration.id,
1206
- set: {
1207
- instructions: configuration.instructions.trim(),
1208
- confidenceThreshold: configuration.confidenceThreshold,
1209
- updatedAt: new Date(),
1210
- },
1211
- })
1212
- .run();
754
+ restoreSettings(settings: MailboxBackupSettings) {
755
+ return mailboxBackup.restoreSettings(this.context, settings);
756
+ }
1213
757
 
1214
- return this.getMailboxAiSettings();
758
+ restoreDraft(
759
+ userId: string,
760
+ input: DraftInput,
761
+ restoredSource: Parameters<typeof mailboxBackup.restoreDraft>[3]
762
+ ) {
763
+ return mailboxBackup.restoreDraft(
764
+ this.context,
765
+ userId,
766
+ input,
767
+ restoredSource
768
+ );
1215
769
  }
1216
770
 
1217
- jmapState() {
1218
- return jmapState(this.state.storage);
771
+ clearBackupHashes() {
772
+ return mailboxBackup.clearBackupHashes(this.context);
1219
773
  }
1220
774
 
1221
- jmapMailboxes(userId: string) {
1222
- return {
1223
- state: jmapState(this.state.storage),
1224
- mailboxes: jmapMailboxRows(this.state.storage.sql, userId),
1225
- };
1226
- }
1227
-
1228
- jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
1229
- return {
1230
- state: jmapState(this.state.storage),
1231
- ...queryJmapEmails(this.state.storage.sql, input),
1232
- };
1233
- }
1234
-
1235
- /** Emails with their JMAP Mailbox and this user's $seen keyword; unknown ids are left out. */
1236
- jmapEmails(userId: string, ids: string[]) {
1237
- const placement = jmapEmailPlacement(this.state.storage.sql, userId, ids);
1238
-
1239
- return {
1240
- state: jmapState(this.state.storage),
1241
- emails: ids.flatMap((id) => {
1242
- const email = this.getEmail(id);
1243
- const place = placement.get(id);
1244
-
1245
- return email && place ? [{ email, ...place }] : [];
1246
- }),
1247
- };
1248
- }
1249
-
1250
- jmapThreads(ids: string[]) {
1251
- return {
1252
- state: jmapState(this.state.storage),
1253
- threads: [...jmapThreadEmails(this.state.storage.sql, ids)].map(
1254
- ([id, emailIds]) => ({ id, emailIds })
1255
- ),
1256
- };
1257
- }
1258
-
1259
- jmapMoveEmails(emailIds: string[], target: string) {
1260
- const moved = jmapMoveEmails(this.state.storage.sql, emailIds, target);
1261
-
1262
- if (moved) this.publishUpdate();
1263
-
1264
- return moved;
775
+ setBackupHashes(hashes: mailboxBackup.BackupHash[]) {
776
+ return mailboxBackup.setBackupHashes(this.context, hashes);
1265
777
  }
1266
778
 
1267
779
  getEmail(id: string) {
@@ -1281,43 +793,32 @@ export class MailboxDO extends DurableObject<Env> {
1281
793
  );
1282
794
  }
1283
795
 
1284
- getConversation(conversationId: string) {
1285
- return this.db
1286
- .select()
796
+ hasNewConversationRecipients(
797
+ conversationId: string,
798
+ ownAddress: string,
799
+ recipients: RecipientFields
800
+ ) {
801
+ const history = this.db
802
+ .select({
803
+ fromJson: emails.fromJson,
804
+ toJson: emails.toJson,
805
+ ccJson: emails.ccJson,
806
+ bccJson: emails.bccJson,
807
+ listPostAddress: emails.listPostAddress,
808
+ })
1287
809
  .from(emails)
1288
810
  .where(eq(emails.conversationId, conversationId))
1289
- .orderBy(asc(emails.timelineAt), asc(emails.id))
1290
811
  .all();
1291
- }
1292
812
 
1293
- getConversationSnapshot(conversationId: string) {
1294
- const conversation = this.db
1295
- .select({
1296
- mailboxState: conversations.mailboxState,
1297
- folderId: conversations.folderId,
1298
- })
1299
- .from(conversations)
1300
- .where(eq(conversations.id, conversationId))
1301
- .all()[0];
813
+ return hasNewRecipients({ ownAddress, history, ...recipients });
814
+ }
1302
815
 
1303
- if (!conversation) return null;
816
+ getConversation(conversationId: string) {
817
+ return mailboxViews.getConversation(this.context, conversationId);
818
+ }
1304
819
 
1305
- return {
1306
- mailboxState: conversation.mailboxState,
1307
- folderId: conversation.folderId,
1308
- messages: this.getConversation(conversationId),
1309
- readStates: this.db
1310
- .select({
1311
- emailId: emailReadStates.emailId,
1312
- userId: emailReadStates.userId,
1313
- readAt: emailReadStates.readAt,
1314
- })
1315
- .from(emailReadStates)
1316
- .innerJoin(emails, eq(emailReadStates.emailId, emails.id))
1317
- .where(eq(emails.conversationId, conversationId))
1318
- .orderBy(asc(emailReadStates.readAt))
1319
- .all(),
1320
- };
820
+ getConversationSnapshot(conversationId: string) {
821
+ return mailboxViews.getConversationSnapshot(this.context, conversationId);
1321
822
  }
1322
823
 
1323
824
  getConversationPageSnapshot(
@@ -1326,165 +827,49 @@ export class MailboxDO extends DurableObject<Env> {
1326
827
  limit: number,
1327
828
  cursor: ConversationCursorPosition | null
1328
829
  ) {
1329
- const conversation = this.db
1330
- .select({
1331
- mailboxState: conversations.mailboxState,
1332
- folderId: conversations.folderId,
1333
- hasIncoming: conversations.hasIncoming,
1334
- hasOutgoing: conversations.hasOutgoing,
1335
- })
1336
- .from(conversations)
1337
- .where(eq(conversations.id, conversationId))
1338
- .all()[0];
1339
-
1340
- if (!conversation) return null;
1341
-
1342
- const pageLimit = Math.max(1, Math.min(limit, 25));
1343
- const cursorDate = cursor ? new Date(cursor.timelineAt) : null;
1344
-
1345
- const predicate =
1346
- cursor && cursorDate
1347
- ? and(
1348
- eq(emails.conversationId, conversationId),
1349
- or(
1350
- lt(emails.timelineAt, cursorDate),
1351
- and(
1352
- eq(emails.timelineAt, cursorDate),
1353
- lt(emails.id, cursor.emailId)
1354
- )
1355
- )
1356
- )
1357
- : eq(emails.conversationId, conversationId);
1358
-
1359
- const descending = this.db
1360
- .select()
1361
- .from(emails)
1362
- .where(predicate)
1363
- .orderBy(desc(emails.timelineAt), desc(emails.id))
1364
- .limit(pageLimit + 1)
1365
- .all();
1366
-
1367
- const page = descending.slice(0, pageLimit);
1368
- const oldest = page.at(-1);
1369
- const messageIds = page.map((email) => email.id);
1370
-
1371
- const counts = this.state.storage.sql
1372
- .exec<ConversationSnapshotCountRow>(
1373
- `
1374
- select
1375
- count(*) as message_count,
1376
- coalesce(sum(
1377
- case
1378
- when message.direction = 'incoming' and not exists (
1379
- select 1
1380
- from email_read_states read_state
1381
- where read_state.user_id = ?
1382
- and read_state.email_id = message.id
1383
- ) then 1
1384
- else 0
1385
- end
1386
- ), 0) as unread_count
1387
- from emails message
1388
- where message.conversation_id = ?
1389
- `,
1390
- userId,
1391
- conversationId
1392
- )
1393
- .one();
1394
-
1395
- return {
1396
- mailboxState: conversation.mailboxState,
1397
- folderId: conversation.folderId,
1398
- hasIncoming: conversation.hasIncoming,
1399
- hasOutgoing: conversation.hasOutgoing,
1400
- messageCount: Number(counts.message_count),
1401
- unreadCount: Number(counts.unread_count),
1402
- messages: page.reverse(),
1403
- next:
1404
- descending.length > pageLimit && oldest
1405
- ? { timelineAt: oldest.timelineAt.getTime(), emailId: oldest.id }
1406
- : null,
1407
- readStates: messageIds.length
1408
- ? this.db
1409
- .select({
1410
- emailId: emailReadStates.emailId,
1411
- userId: emailReadStates.userId,
1412
- readAt: emailReadStates.readAt,
1413
- })
1414
- .from(emailReadStates)
1415
- .where(inArray(emailReadStates.emailId, messageIds))
1416
- .orderBy(asc(emailReadStates.readAt))
1417
- .all()
1418
- : [],
1419
- };
830
+ return mailboxViews.getConversationPageSnapshot(
831
+ this.context,
832
+ conversationId,
833
+ userId,
834
+ limit,
835
+ cursor
836
+ );
1420
837
  }
1421
838
 
1422
- /**
1423
- * Everything the reader needs from this mailbox in one call: a page of the
1424
- * conversation with read states, plus sender history and block, trust and
1425
- * unsubscribe state for its incoming senders.
1426
- */
1427
839
  getConversationView(
1428
840
  conversationId: string,
1429
841
  userId: string,
1430
842
  limit: number,
1431
- cursor: ConversationCursorPosition | null
843
+ cursor: ConversationCursorPosition | null,
844
+ includeReplyDraft: boolean,
845
+ matchId?: string
1432
846
  ) {
1433
- const snapshot = this.getConversationPageSnapshot(
847
+ return mailboxViews.getConversationView(
848
+ this.context,
1434
849
  conversationId,
1435
850
  userId,
1436
851
  limit,
1437
- cursor
1438
- );
1439
-
1440
- if (!snapshot) return null;
1441
-
1442
- const incoming = snapshot.messages.filter(
1443
- (message) => message.direction === "incoming"
852
+ cursor,
853
+ includeReplyDraft,
854
+ matchId
1444
855
  );
1445
-
1446
- const senderAddresses = incoming.flatMap((message) =>
1447
- message.fromJson[0] ? [message.fromJson[0].address] : []
1448
- );
1449
-
1450
- return {
1451
- ...snapshot,
1452
- history: this.getSenderHistory(senderAddresses),
1453
- safety: this.getMessageSafetyContext(
1454
- senderAddresses,
1455
- incoming.flatMap((message) => emailListKey(message) ?? [])
1456
- ),
1457
- version: this.version(),
1458
- };
1459
856
  }
1460
857
 
1461
- /** One message with its sender's history and safety state, for re-deriving its security summary. */
1462
858
  getMessageSenderView(emailId: string) {
1463
- const email = this.getEmail(emailId);
1464
-
1465
- if (!email) return null;
1466
-
1467
- const sender =
1468
- email.direction === "incoming" ? email.fromJson[0]?.address : undefined;
1469
-
1470
- const senderAddresses = sender ? [sender] : [];
1471
- const listKey = emailListKey(email);
1472
-
1473
- return {
1474
- email,
1475
- history: this.getSenderHistory(senderAddresses),
1476
- safety: this.getMessageSafetyContext(
1477
- senderAddresses,
1478
- listKey ? [listKey] : []
1479
- ),
1480
- };
859
+ return mailboxViews.getMessageSenderView(this.context, emailId);
1481
860
  }
1482
861
 
1483
862
  getAttachment(emailId: string, attachmentId: string) {
1484
- const email = this.getEmail(emailId);
863
+ return mailboxViews.getAttachment(this.context, emailId, attachmentId);
864
+ }
1485
865
 
866
+ getRawMimeKey(emailId: string) {
1486
867
  return (
1487
- email?.attachmentsJson.find((file) => file.id === attachmentId) ?? null
868
+ this.db
869
+ .select({ key: emails.rawMimeR2Key })
870
+ .from(emails)
871
+ .where(eq(emails.id, emailId))
872
+ .get()?.key ?? null
1488
873
  );
1489
874
  }
1490
875
 
@@ -1494,26 +879,20 @@ export class MailboxDO extends DurableObject<Env> {
1494
879
  sourceKey: string,
1495
880
  status: "ready" | "failed"
1496
881
  ) {
1497
- const email = this.getEmail(emailId);
882
+ const attachments = mailboxViews.emailAttachments(this.context, emailId);
1498
883
 
1499
- const file = email?.attachmentsJson.find(
884
+ const file = attachments.find(
1500
885
  (attachment) =>
1501
886
  attachment.id === attachmentId && attachment.r2Key === sourceKey
1502
887
  );
1503
888
 
1504
- if (!email || !file) {
1505
- // Conversion may finish after permanent deletion already removed its objects.
1506
- // Persist cleanup before the queue acknowledges, so an R2 outage cannot orphan the PDF.
1507
- const cleanupAt = new Date();
1508
- await this.scheduleAlarm(cleanupAt.getTime() + ALARM_WAKE_DELAY_MS);
1509
- this.db
1510
- .insert(pendingObjectDeletions)
1511
- .values({
1512
- objectKey: officePreviewKey(sourceKey),
1513
- nextAttemptAt: cleanupAt,
1514
- })
1515
- .onConflictDoNothing()
1516
- .run();
889
+ if (!file) {
890
+ // Conversion may finish after permanent deletion already removed its
891
+ // objects: queue the PDF before the queue acknowledges, so an R2
892
+ // outage can't orphan it.
893
+ await mailboxStorage.forgetObjects(this.context, [
894
+ officePreviewKey(sourceKey),
895
+ ]);
1517
896
 
1518
897
  return false;
1519
898
  }
@@ -1522,7 +901,7 @@ export class MailboxDO extends DurableObject<Env> {
1522
901
  this.db
1523
902
  .update(emails)
1524
903
  .set({
1525
- attachmentsJson: email.attachmentsJson.map((attachment) =>
904
+ attachmentsJson: attachments.map((attachment) =>
1526
905
  attachment.id === attachmentId
1527
906
  ? { ...attachment, pdfPreviewStatus: status }
1528
907
  : attachment
@@ -1530,7 +909,7 @@ export class MailboxDO extends DurableObject<Env> {
1530
909
  })
1531
910
  .where(eq(emails.id, emailId))
1532
911
  .run();
1533
- this.publishUpdate();
912
+ void this.announce({ inboxChanged: false });
1534
913
 
1535
914
  return true;
1536
915
  }
@@ -1548,195 +927,75 @@ export class MailboxDO extends DurableObject<Env> {
1548
927
  .limit(500)
1549
928
  .all();
1550
929
 
1551
- const flagged = this.state.storage.sql
1552
- .exec<{ address: string }>(
1553
- "select address from senders where blocked_at is not null or reported_at is not null"
1554
- )
1555
- .toArray()
1556
- .map((row) => row.address);
1557
-
1558
- const excluded = new Set(flagged);
1559
-
1560
- return suggestParticipants(
930
+ const candidates = suggestParticipants(
1561
931
  this.recentParticipantSources,
1562
932
  ownAddress,
1563
- query,
1564
- limit,
1565
- (address) =>
1566
- blockPatternsFor(address).some((pattern) => excluded.has(pattern))
933
+ query
1567
934
  );
1568
- }
1569
935
 
1570
- listFolders(userId: string): FolderListItem[] {
1571
- const rows = this.state.storage.sql
1572
- .exec<FolderListRow>(
1573
- `
1574
- with folder_rows(id, name, kind, system_type, sort_order) as (
1575
- select
1576
- json_extract(value, '$.id'),
1577
- json_extract(value, '$.name'),
1578
- 'system',
1579
- json_extract(value, '$.systemType'),
1580
- json_extract(value, '$.sortOrder')
1581
- from json_each(?)
1582
- union all
1583
- select id, name, 'custom', null, sort_order
1584
- from folders
1585
- ),
1586
- conversation_unread as (
1587
- select
1588
- c.id,
1589
- c.mailbox_state,
1590
- c.folder_id,
1591
- c.has_incoming,
1592
- c.has_outgoing,
1593
- coalesce(sum(case
1594
- when message.id is not null and read_state.email_id is null then 1
1595
- else 0
1596
- end), 0) as unread_count
1597
- from conversations c
1598
- left join emails message
1599
- on message.conversation_id = c.id
1600
- and message.direction = 'incoming'
1601
- left join email_read_states read_state
1602
- on read_state.user_id = ?
1603
- and read_state.email_id = message.id
1604
- group by
1605
- c.id,
1606
- c.mailbox_state,
1607
- c.folder_id,
1608
- c.has_incoming,
1609
- c.has_outgoing
936
+ if (!candidates.length) return [];
937
+
938
+ const patterns = candidates.flatMap((row) => blockPatternsFor(row.address));
939
+
940
+ const flagged = this.db
941
+ .select({ address: senders.address })
942
+ .from(senders)
943
+ .where(
944
+ and(
945
+ inJsonList(senders.address, patterns),
946
+ or(isNotNull(senders.blockedAt), isNotNull(senders.reportedAt))
947
+ )
1610
948
  )
1611
- select
1612
- folder.id,
1613
- folder.name,
1614
- folder.kind,
1615
- folder.system_type,
1616
- folder.sort_order,
1617
- count(conversation.id) as total_count,
1618
- coalesce(sum(conversation.unread_count), 0) as unread_count
1619
- from folder_rows folder
1620
- left join conversation_unread conversation on
1621
- ${FOLDER_AGGREGATE_JOIN_PREDICATE}
1622
- group by
1623
- folder.id,
1624
- folder.name,
1625
- folder.kind,
1626
- folder.system_type,
1627
- folder.sort_order
1628
- `,
1629
- JSON.stringify(this.systemFolders()),
1630
- userId
949
+ .all();
950
+
951
+ const excluded = new Set(flagged.map((row) => row.address));
952
+
953
+ return candidates
954
+ .filter(
955
+ (row) =>
956
+ !blockPatternsFor(row.address).some((pattern) =>
957
+ excluded.has(pattern)
958
+ )
1631
959
  )
1632
- .toArray();
1633
-
1634
- return sortFolders(
1635
- rows.map((row): FolderListItem => ({
1636
- id: row.id,
1637
- name: row.name,
1638
- kind: row.kind,
1639
- systemType: row.system_type,
1640
- sortOrder: Number(row.sort_order),
1641
- totalCount: Number(row.total_count),
1642
- unreadCount: Number(row.unread_count),
1643
- }))
1644
- );
960
+ .slice(0, limit);
1645
961
  }
1646
962
 
1647
- /**
1648
- * What the mail screen shows first, in one call: the folders and the first
1649
- * page of `folderId` (null for no such folder).
1650
- */
1651
- startupView(userId: string, folderId: string, limit: number) {
1652
- return {
1653
- folders: this.folderView(userId),
1654
- conversations: this.listConversations(
1655
- userId,
1656
- folderId,
1657
- limit,
1658
- null,
1659
- undefined
1660
- ),
1661
- };
963
+ listFolders(userId: string) {
964
+ return mailboxViews.listFolders(this.context, userId);
965
+ }
966
+
967
+ startupView(
968
+ userId: string,
969
+ folderId: string,
970
+ limit: number,
971
+ draftSenders?: DraftSenders
972
+ ) {
973
+ return mailboxViews.startupView(
974
+ this.context,
975
+ userId,
976
+ folderId,
977
+ limit,
978
+ draftSenders
979
+ );
1662
980
  }
1663
981
 
1664
- /** `listFolders` with the change counter it reflects. */
1665
982
  folderView(userId: string) {
1666
- return { folders: this.listFolders(userId), version: this.version() };
1667
- }
1668
-
1669
- getFolderCounts(userId: string, folderId: string): FolderCounts | null {
1670
- const folder = this.getFolder(folderId);
1671
-
1672
- return folder ? this.countFolder(userId, folder) : null;
1673
- }
1674
-
1675
- private countFolder(userId: string, folder: MailFolder): FolderCounts {
1676
- const membership = folderMembership(folder);
1677
-
1678
- const counts = this.state.storage.sql
1679
- .exec<FolderCountRow>(
1680
- `
1681
- select
1682
- count(*) as total_count,
1683
- coalesce(sum((
1684
- select count(*)
1685
- from emails message
1686
- where message.conversation_id = c.id
1687
- and message.direction = 'incoming'
1688
- and not exists (
1689
- select 1
1690
- from email_read_states read_state
1691
- where read_state.user_id = ?
1692
- and read_state.email_id = message.id
1693
- )
1694
- )), 0) as unread_count
1695
- from conversations c
1696
- where ${membership.predicate}
1697
- `,
1698
- userId,
1699
- ...membership.bindings
1700
- )
1701
- .one();
983
+ return mailboxViews.folderView(this.context, userId);
984
+ }
1702
985
 
1703
- return {
1704
- totalCount: Number(counts.total_count),
1705
- unreadCount: Number(counts.unread_count),
1706
- };
986
+ getFolderCounts(userId: string, folderId: string) {
987
+ return mailboxViews.getFolderCounts(this.context, userId, folderId);
1707
988
  }
1708
989
 
1709
- /** Sets one person's read state; the change counter after it, or false for no such message. */
1710
990
  setMessageRead(userId: string, emailId: string, isRead: boolean) {
1711
- const email = this.getEmail(emailId);
1712
-
1713
- if (!email) return false;
1714
-
1715
- if (isRead) {
1716
- const readAt = new Date();
1717
- this.db
1718
- .insert(emailReadStates)
1719
- .values({ userId, emailId, readAt })
1720
- .onConflictDoUpdate({
1721
- target: [emailReadStates.userId, emailReadStates.emailId],
1722
- set: { readAt },
1723
- })
1724
- .run();
1725
- } else {
1726
- this.db
1727
- .delete(emailReadStates)
1728
- .where(
1729
- and(
1730
- eq(emailReadStates.userId, userId),
1731
- eq(emailReadStates.emailId, emailId)
1732
- )
1733
- )
1734
- .run();
1735
- }
1736
-
1737
- this.publishUpdate();
991
+ return mailboxViews.setMessageRead(this.context, userId, emailId, isRead);
992
+ }
1738
993
 
1739
- return { version: this.version() };
994
+ setReadStates(
995
+ userId: string,
996
+ changes: { emailId: string; isRead: boolean }[]
997
+ ) {
998
+ return mailboxViews.setReadStates(this.context, userId, changes);
1740
999
  }
1741
1000
 
1742
1001
  bulkSetConversationRead(
@@ -1744,117 +1003,16 @@ export class MailboxDO extends DurableObject<Env> {
1744
1003
  conversationIds: string[],
1745
1004
  isRead: boolean
1746
1005
  ) {
1747
- const candidates = [...new Set(conversationIds)];
1748
-
1749
- if (!candidates.length) return 0;
1750
- const candidatesJson = stringListJson(candidates);
1751
-
1752
- const existingIds = this.db
1753
- .select({ id: conversations.id })
1754
- .from(conversations)
1755
- .where(
1756
- and(
1757
- sql`${conversations.id} in (
1758
- select cast(value as text) from json_each(${candidatesJson})
1759
- )`,
1760
- eq(conversations.hasIncoming, true)
1761
- )
1762
- )
1763
- .all()
1764
- .map((conversation) => conversation.id);
1765
-
1766
- if (!existingIds.length) return 0;
1767
- const existingIdsJson = stringListJson(existingIds);
1768
-
1769
- if (isRead) {
1770
- this.db.run(sql`
1771
- insert into email_read_states (user_id, email_id, read_at)
1772
- select ${userId}, id, ${Date.now()}
1773
- from emails
1774
- where conversation_id in (
1775
- select cast(value as text) from json_each(${existingIdsJson})
1776
- ) and direction = 'incoming'
1777
- on conflict (user_id, email_id) do update set read_at = excluded.read_at
1778
- `);
1779
- } else {
1780
- this.db.run(sql`
1781
- delete from email_read_states
1782
- where user_id = ${userId}
1783
- and email_id in (
1784
- select message.id
1785
- from emails message
1786
- where message.conversation_id in (
1787
- select cast(value as text) from json_each(${existingIdsJson})
1788
- )
1789
- and message.direction = 'incoming'
1790
- and not exists (
1791
- select 1
1792
- from emails newer
1793
- where newer.conversation_id = message.conversation_id
1794
- and newer.direction = 'incoming'
1795
- and (
1796
- newer.timeline_at > message.timeline_at
1797
- or (
1798
- newer.timeline_at = message.timeline_at
1799
- and newer.id > message.id
1800
- )
1801
- )
1802
- )
1803
- )
1804
- `);
1805
- }
1806
-
1807
- this.publishUpdate();
1808
-
1809
- return existingIds.length;
1006
+ return mailboxViews.bulkSetConversationRead(
1007
+ this.context,
1008
+ userId,
1009
+ conversationIds,
1010
+ isRead
1011
+ );
1810
1012
  }
1811
1013
 
1812
- async enqueueInbound(input: InboundDeliveryInput) {
1813
- const receivedAt = new Date(input.receivedAt);
1814
-
1815
- if (Number.isNaN(receivedAt.getTime())) {
1816
- throw new Error("Inbound delivery has an invalid receipt time");
1817
- }
1818
-
1819
- if (this.state.id.name && this.state.id.name !== input.mailboxId) {
1820
- throw new Error("Inbound delivery targeted the wrong mailbox object");
1821
- }
1822
-
1823
- const queuedAt = new Date();
1824
- // Keep the alarm just ahead of the due time. Scheduling it for "now" can
1825
- // wake it on the setAlarm await before the synchronous insert below runs.
1826
- const alarmAt = queuedAt.getTime() + ALARM_WAKE_DELAY_MS;
1827
- await this.scheduleAlarm(alarmAt);
1828
- const messageId = inboundMessageId(input.id);
1829
-
1830
- const queued = this.db.transaction((tx) => {
1831
- const existing = tx
1832
- .select({ id: emails.id })
1833
- .from(emails)
1834
- .where(eq(emails.id, messageId))
1835
- .all()[0];
1836
-
1837
- if (existing) return false;
1838
-
1839
- const result = tx
1840
- .insert(pendingInbound)
1841
- .values({
1842
- id: input.id,
1843
- rawObjectKey: input.rawObjectKey,
1844
- envelopeFrom: input.envelopeFrom,
1845
- envelopeTo: input.envelopeTo,
1846
- listAddress: input.listAddress ?? null,
1847
- receivedAt,
1848
- nextAttemptAt: queuedAt,
1849
- })
1850
- .onConflictDoNothing()
1851
- .returning({ id: pendingInbound.id })
1852
- .all();
1853
-
1854
- return result.length > 0;
1855
- });
1856
-
1857
- return { messageId, queued };
1014
+ enqueueInbound(input: InboundDeliveryInput) {
1015
+ return mailboxInbound.enqueueInbound(this.context, input);
1858
1016
  }
1859
1017
 
1860
1018
  async insertEmail(input: NewEmail) {
@@ -1865,18 +1023,7 @@ export class MailboxDO extends DurableObject<Env> {
1865
1023
  }
1866
1024
 
1867
1025
  this.db.transaction((tx) => {
1868
- const inserted = tx
1869
- .insert(emails)
1870
- .values(email)
1871
- .onConflictDoNothing()
1872
- .returning({ id: emails.id })
1873
- .all();
1874
-
1875
- if (inserted.length) {
1876
- indexInsertedEmail(this.state.storage.sql, email.id);
1877
- insertOfficePreviewJobs(this.state.storage.sql, email);
1878
- recordCorrespondents(this.state.storage.sql, email);
1879
- }
1026
+ storeEmail(tx, this.state.storage.sql, email);
1880
1027
  });
1881
1028
  this.recentParticipantSources = null;
1882
1029
  void this.syncInboxCounts();
@@ -1884,958 +1031,156 @@ export class MailboxDO extends DurableObject<Env> {
1884
1031
  return this.getEmail(email.id);
1885
1032
  }
1886
1033
 
1887
- /**
1888
- * The message an import already stored: the one `importId` made, or one
1889
- * with the same Message-ID (from another source, or delivered here).
1890
- */
1891
- findImported(importId: string, messageIdHeader: string | null) {
1892
- const existing =
1893
- this.getEmail(inboundMessageId(importId)) ??
1894
- (messageIdHeader ? this.getEmailByMessageId(messageIdHeader) : null);
1895
-
1896
- return existing
1897
- ? { id: existing.id, conversationId: existing.conversationId }
1898
- : null;
1034
+ findImported(
1035
+ emailId: string,
1036
+ original: Pick<ImportOriginal, "emailId" | "conversationId"> | null,
1037
+ conversationId: string | null,
1038
+ copy?: mailboxImport.ImportCopyKey | null
1039
+ ) {
1040
+ return mailboxImport.findImported(
1041
+ this.context,
1042
+ emailId,
1043
+ original,
1044
+ conversationId,
1045
+ copy
1046
+ );
1899
1047
  }
1900
1048
 
1901
- /**
1902
- * Stores one existing message (raw MIME already in R2) as delivery would,
1903
- * with its place, read state, date and thread given by the importer. No
1904
- * AI, sender checks, webhooks or push: imported mail is history. The
1905
- * conversation and search index are kept as for any message; counts,
1906
- * realtime and JMAP state are announced once for the batch
1907
- * (`finishImport`, or the alarm when the importer never says it finished).
1908
- * Idempotent by `importId` and by Message-ID.
1909
- */
1910
- async importMessage(input: ImportMessageInput): Promise<ImportMessageResult> {
1911
- const id = inboundMessageId(input.importId);
1912
- const known = this.getEmail(id);
1913
-
1914
- if (known) {
1915
- return { status: "duplicate", id, conversationId: known.conversationId };
1916
- }
1917
-
1918
- const object = await this.bindings.MAIL_STORAGE.get(input.rawObjectKey);
1049
+ importMessage(input: ImportMessageInput) {
1050
+ return mailboxImport.importMessage(this.context, input);
1051
+ }
1919
1052
 
1920
- if (!object) throw new MissingRawMimeError();
1921
- const rawMime = await object.arrayBuffer();
1922
- const messageIdHeader = rawMessageId(rawMime);
1053
+ finishImport() {
1054
+ return mailboxImport.finishImport(this.context);
1055
+ }
1923
1056
 
1924
- const copy = messageIdHeader
1925
- ? this.getEmailByMessageId(messageIdHeader)
1926
- : null;
1057
+ /** The model from openworkspace.json; tests substitute one on the instance. */
1058
+ protected classificationModel() {
1059
+ return aiModel(this.env, "classification");
1060
+ }
1927
1061
 
1928
- if (copy) {
1929
- // Nothing will point at this upload.
1930
- await this.bindings.MAIL_STORAGE.delete(input.rawObjectKey);
1062
+ setEmailSenderIntel(
1063
+ emailId: string,
1064
+ intel: SenderIntel,
1065
+ replacesCheckedAt: number | null = null
1066
+ ) {
1067
+ return senderSafety.setEmailSenderIntel(
1068
+ this.context,
1069
+ emailId,
1070
+ intel,
1071
+ replacesCheckedAt
1072
+ );
1073
+ }
1931
1074
 
1932
- return {
1933
- status: "duplicate",
1934
- id: copy.id,
1935
- conversationId: copy.conversationId,
1936
- };
1937
- }
1075
+ getSenderHistory(addresses: string[]) {
1076
+ return senderSafety.getSenderHistory(this.context, addresses);
1077
+ }
1938
1078
 
1939
- const receivedAt = new Date(
1940
- input.receivedAt ?? headerDate(rawMime) ?? Date.now()
1079
+ getMessageSafetyContext(addresses: string[], listKeys: string[]) {
1080
+ return senderSafety.getMessageSafetyContext(
1081
+ this.context,
1082
+ addresses,
1083
+ listKeys
1941
1084
  );
1085
+ }
1086
+
1087
+ recordUnsubscription(input: {
1088
+ listKey: string;
1089
+ emailId: string;
1090
+ method: Unsubscription["method"];
1091
+ status: Unsubscription["status"];
1092
+ target: string | null;
1093
+ detail: string | null;
1094
+ userId: string;
1095
+ }) {
1096
+ return senderSafety.recordUnsubscription(this.context, input);
1097
+ }
1942
1098
 
1943
- let parsed: NewEmail;
1099
+ blockSender(pattern: string, moveExisting: boolean) {
1100
+ return senderSafety.blockSender(this.context, pattern, moveExisting);
1101
+ }
1944
1102
 
1945
- try {
1946
- parsed = (
1947
- await prepareInboundEmail({
1948
- env: this.bindings,
1949
- mailboxId: this.state.id.name ?? "unknown-mailbox",
1950
- job: {
1951
- id: input.importId,
1952
- rawObjectKey: input.rawObjectKey,
1953
- envelopeFrom: "",
1954
- envelopeTo: input.mailboxAddress,
1955
- listAddress: null,
1956
- receivedAt,
1957
- },
1958
- rawMime,
1959
- resolveParent: (inReplyTo, references) =>
1960
- this.resolveParent(inReplyTo, references),
1961
- })
1962
- ).email;
1963
- } catch (error) {
1964
- if (!(error instanceof UnprocessableInboundEmailError)) throw error;
1965
- await this.bindings.MAIL_STORAGE.delete(input.rawObjectKey);
1103
+ moveSenderToSpam(pattern: string) {
1104
+ return senderSafety.moveSenderToSpam(this.context, pattern);
1105
+ }
1966
1106
 
1967
- return { status: "unprocessable", reason: error.message };
1968
- }
1107
+ unblockSender(pattern: string) {
1108
+ return senderSafety.unblockSender(this.context, pattern);
1109
+ }
1969
1110
 
1970
- const own = normalizeMailboxAddress(input.mailboxAddress);
1971
-
1972
- const direction =
1973
- input.direction ??
1974
- (parsed.fromJson[0] &&
1975
- normalizeMailboxAddress(parsed.fromJson[0].address) === own
1976
- ? "outgoing"
1977
- : "incoming");
1978
-
1979
- const imported: NewEmail = {
1980
- ...parsed,
1981
- conversationId: input.conversationId ?? parsed.conversationId,
1982
- direction,
1983
- bodyText: clampText(parsed.bodyText),
1984
- quotedText: clampText(parsed.quotedText),
1985
- // Not an SMTP delivery to this workspace.
1986
- envelopeFrom: null,
1987
- envelopeTo: null,
1988
- };
1111
+ listBlockedSenders() {
1112
+ return senderSafety.listBlockedSenders(this.context);
1113
+ }
1989
1114
 
1990
- // Mail this mailbox sent went out already, unauthenticated by anyone here.
1991
- if (direction === "outgoing") {
1992
- imported.transportState = "submitted";
1993
- imported.authenticationResultsJson = null;
1994
- imported.listUnsubscribeJson = null;
1995
- }
1115
+ setSenderTrusted(address: string, trusted: boolean) {
1116
+ return senderSafety.setSenderTrusted(this.context, address, trusted);
1117
+ }
1996
1118
 
1997
- const email = prepareOfficePreviews(imported);
1119
+ reportSpam(input: Parameters<typeof senderSafety.reportSpam>[1]) {
1120
+ return senderSafety.reportSpam(this.context, input);
1121
+ }
1998
1122
 
1999
- const stored = this.db.transaction((tx) => {
2000
- const before =
2001
- tx
2002
- .select({
2003
- mailboxState: conversations.mailboxState,
2004
- folderId: conversations.folderId,
2005
- })
2006
- .from(conversations)
2007
- .where(eq(conversations.id, email.conversationId))
2008
- .all()[0] ?? null;
1123
+ markNotSpam(input: Parameters<typeof senderSafety.markNotSpam>[1]) {
1124
+ return senderSafety.markNotSpam(this.context, input);
1125
+ }
2009
1126
 
2010
- let folderId: string | null = null;
2011
- let folderSkipped: "limit" | "invalid" | null = null;
1127
+ submitOutgoing(input: NewEmail, userId: string, draft?: SendingDraft) {
1128
+ return mailboxOutbound.submitOutgoing(this.context, input, userId, draft);
1129
+ }
2012
1130
 
2013
- if (input.placement === "inbox" && input.folderName) {
2014
- const folder = this.importFolder(input.folderName);
1131
+ resendOutgoing(id: string, origin: string) {
1132
+ return mailboxOutbound.resendOutgoing(this.context, id, origin);
1133
+ }
2015
1134
 
2016
- if ("id" in folder) folderId = folder.id;
2017
- else folderSkipped = folder.skipped;
1135
+ async seedMailbox(
1136
+ folderValues: NewFolder[],
1137
+ emailValues: NewEmail[],
1138
+ conversationValues: {
1139
+ id: string;
1140
+ mailboxState?: MailboxState;
1141
+ folderId?: string | null;
1142
+ }[] = [],
1143
+ senderValues: (typeof senders.$inferInsert)[] = []
1144
+ ) {
1145
+ this.db.transaction((tx) => {
1146
+ // Prior history first: seeded messages then add to it exactly once.
1147
+ for (const sender of senderValues) {
1148
+ tx.insert(senders).values(sender).onConflictDoNothing().run();
2018
1149
  }
2019
1150
 
2020
- const inserted = tx
2021
- .insert(emails)
2022
- .values(email)
2023
- .onConflictDoNothing()
2024
- .returning({ id: emails.id })
2025
- .all();
2026
-
2027
- if (!inserted.length) return null;
2028
- indexInsertedEmail(this.state.storage.sql, email.id);
2029
- insertOfficePreviewJobs(this.state.storage.sql, email);
2030
- recordCorrespondents(this.state.storage.sql, email);
2031
-
2032
- const placement = mergedPlacement(
2033
- before,
2034
- requestedPlacement(input.placement, folderId)
2035
- );
1151
+ // Seeding sets the folder order afresh: seeded folders at their places,
1152
+ // system folders at their defaults (so a demo login undoes a reorder).
1153
+ tx.delete(systemFolderOrder).run();
2036
1154
 
2037
- if (placement) {
2038
- tx.update(conversations)
2039
- .set(placement)
2040
- .where(eq(conversations.id, email.conversationId))
1155
+ for (const folder of folderValues) {
1156
+ tx.insert(folders)
1157
+ .values(folder)
1158
+ .onConflictDoUpdate({
1159
+ target: folders.id,
1160
+ set: { sortOrder: folder.sortOrder },
1161
+ })
2041
1162
  .run();
2042
1163
  }
2043
1164
 
2044
- if (direction === "incoming") {
2045
- for (const userId of new Set(input.seenBy)) {
2046
- tx.insert(emailReadStates)
2047
- .values({ userId, emailId: email.id, readAt: receivedAt })
2048
- .onConflictDoNothing()
2049
- .run();
2050
- }
1165
+ for (const email of emailValues) {
1166
+ storeEmail(tx, this.state.storage.sql, email);
2051
1167
  }
2052
1168
 
2053
- return { folderSkipped };
1169
+ for (const conversation of conversationValues) {
1170
+ fileConversations(
1171
+ this.state.storage.sql,
1172
+ [conversation.id],
1173
+ {
1174
+ mailboxState: conversation.mailboxState,
1175
+ folderId: conversation.folderId,
1176
+ },
1177
+ { stored: true }
1178
+ );
1179
+ }
2054
1180
  });
2055
-
2056
- if (!stored) {
2057
- const existing = this.getEmail(id);
2058
-
2059
- return {
2060
- status: "duplicate",
2061
- id,
2062
- conversationId: existing?.conversationId ?? email.conversationId,
2063
- };
2064
- }
2065
-
2066
- this.recentParticipantSources = null;
2067
- this.state.storage.kv.put(IMPORT_PENDING_KEY, true);
2068
- await this.scheduleAlarm(
2069
- Date.now() +
2070
- (hasPendingOfficePreviews(email)
2071
- ? ALARM_WAKE_DELAY_MS
2072
- : IMPORT_ANNOUNCE_DELAY_MS)
2073
- );
2074
-
2075
- return {
2076
- status: "imported",
2077
- id,
2078
- conversationId: email.conversationId,
2079
- folderSkipped: stored.folderSkipped,
2080
- };
2081
- }
2082
-
2083
- /** The custom folder with this name (any case), created when missing; why not, when it cannot be. */
2084
- private importFolder(
2085
- name: string
2086
- ): { id: string } | { skipped: "limit" | "invalid" } {
2087
- const normalized = name.trim().toLocaleLowerCase("en-US");
2088
-
2089
- const existing = this.db
2090
- .select({ id: folders.id, name: folders.name })
2091
- .from(folders)
2092
- .all()
2093
- .find((folder) => folder.name.toLocaleLowerCase("en-US") === normalized);
2094
-
2095
- if (existing) return { id: existing.id };
2096
- const created = this.insertFolder(createId("fld"), name);
2097
-
2098
- if (created.status === "ok") return { id: created.folder.id };
2099
-
2100
- // A system folder's name ("Sent", "Archive") is no custom folder.
2101
- return { skipped: created.status === "limit" ? "limit" : "invalid" };
2102
- }
2103
-
2104
- /**
2105
- * Announces what imports stored since the last time: writes the inbox
2106
- * counts to D1 once, bumps the JMAP state, and tells open apps to refresh.
2107
- * Push subscribers are not told; imported mail is not new mail.
2108
- */
2109
- async finishImport() {
2110
- if (this.state.storage.kv.get<boolean>(IMPORT_PENDING_KEY)) {
2111
- this.state.storage.kv.delete(IMPORT_PENDING_KEY);
2112
- bumpJmapState(this.state.storage);
2113
- const countsWritten = this.syncInboxCounts();
2114
- this.state.waitUntil(
2115
- this.broadcastUpdate(countsWritten).catch((error) => {
2116
- console.error("Could not authorize realtime delivery", error);
2117
- })
2118
- );
2119
- this.announceJmapState(false);
2120
- await countsWritten;
2121
- }
2122
-
2123
- return { version: this.version() };
2124
- }
2125
-
2126
- /**
2127
- * DNS intelligence and receiver signals for a parsed delivery, gathered
2128
- * before AI classification so the model can use them. Fails open.
2129
- */
2130
- private async inboundSenderSignals(email: NewEmail, links: string[]) {
2131
- let identity: WorkspaceIdentity = { domains: [], names: new Map() };
2132
- let dqsKey: string | null = null;
2133
- let workspaceBlocks = new Map<string, number>();
2134
-
2135
- try {
2136
- [identity, dqsKey, workspaceBlocks] = await Promise.all([
2137
- workspaceIdentity(this.bindings.DB),
2138
- spamhausDqsKey(this.bindings),
2139
- workspaceBlockPatterns(this.bindings.DB),
2140
- ]);
2141
- } catch (error) {
2142
- console.error(
2143
- "Could not read workspace identity for sender checks",
2144
- error
2145
- );
2146
- }
2147
-
2148
- const stored = email.authenticationResultsJson;
2149
- const authentication = stored ?? null;
2150
- const from = email.fromJson[0] ?? { address: "", name: null };
2151
- const storage = this.state.storage.sql;
2152
-
2153
- const status = from.address
2154
- ? senderStatuses(storage, [from.address]).get(
2155
- from.address.toLocaleLowerCase()
2156
- )
2157
- : undefined;
2158
-
2159
- const block =
2160
- workspaceBlockFor(from.address, workspaceBlocks) ?? status?.block ?? null;
2161
-
2162
- const trusted = Boolean(status?.trustedAt) && !block;
2163
- let intel: SenderIntel | null = null;
2164
-
2165
- try {
2166
- intel = await collectSenderIntel({
2167
- authentication,
2168
- fromAddress: from.address,
2169
- linkDomains: links,
2170
- workspaceDomains: identity.domains,
2171
- dqsKey,
2172
- bucket: this.bindings.MAIL_STORAGE,
2173
- });
2174
- } catch (error) {
2175
- console.error(
2176
- `Could not collect sender intelligence for ${email.id}`,
2177
- error
2178
- );
2179
- }
2180
-
2181
- const history = senderHistory(storage, [from.address]).get(
2182
- from.address.toLocaleLowerCase()
2183
- );
2184
-
2185
- const delivery = deliveryFacts({
2186
- authentication,
2187
- deliveredTo: email.envelopeTo ?? null,
2188
- to: (email.toJson ?? []).map((item) => item.address),
2189
- cc: (email.ccJson ?? []).map((item) => item.address),
2190
- listId: email.listId ?? null,
2191
- workspaceDomains: identity.domains,
2192
- isKnownAddressee: (address) => this.isKnownAddressee(address),
2193
- });
2194
-
2195
- const security = messageSecurity({
2196
- fromAddress: from.address,
2197
- fromName: from.name,
2198
- authentication,
2199
- listUnsubscribe: null,
2200
- workspaceDomains: identity.domains,
2201
- internalNames: identity.names,
2202
- intel,
2203
- // Counted as if this message were already stored.
2204
- history: {
2205
- inboundCount: (history?.inboundCount ?? 0) + 1,
2206
- outboundCount: history?.outboundCount ?? 0,
2207
- },
2208
- replyTo: (email.replyToJson ?? []).map((item) => item.address),
2209
- listId: email.listId ?? null,
2210
- delivery,
2211
- trusted,
2212
- });
2213
-
2214
- const screening: InboundScreening = { block, trusted };
2215
-
2216
- let workspaceFeedback: Awaited<
2217
- ReturnType<typeof workspaceFeedbackSummary>
2218
- > | null = null;
2219
-
2220
- const mailboxId = this.state.id.name;
2221
-
2222
- if (from.address && mailboxId && !block) {
2223
- try {
2224
- workspaceFeedback = await workspaceFeedbackSummary(
2225
- this.bindings.DB,
2226
- mailboxId,
2227
- from.address
2228
- );
2229
- } catch (error) {
2230
- console.error(
2231
- `Could not read workspace feedback for ${email.id}`,
2232
- error
2233
- );
2234
- }
2235
- }
2236
-
2237
- return {
2238
- intel,
2239
- delivery,
2240
- screening,
2241
- signals: classificationSignals({
2242
- authentication,
2243
- intel,
2244
- firstTimeSender: security.firstTimeSender,
2245
- warnings: security.warnings,
2246
- feedback: from.address
2247
- ? senderFeedbackSummary(storage, from.address)
2248
- : null,
2249
- workspaceFeedback,
2250
- delivery,
2251
- }),
2252
- };
2253
- }
2254
-
2255
- /** Mail written to this address already reached the mailbox from at least two senders. */
2256
- private isKnownAddressee(address: string) {
2257
- const [row] = this.state.storage.sql
2258
- .exec<{ senders: number }>(
2259
- `
2260
- select count(distinct lower(json_extract(message.from_json, '$[0].address'))) as senders
2261
- from emails message
2262
- where message.direction = 'incoming'
2263
- and exists (
2264
- select 1 from json_each(message.to_json) recipient
2265
- where lower(json_extract(recipient.value, '$.address')) = ?1
2266
- union all
2267
- select 1 from json_each(message.cc_json) recipient
2268
- where lower(json_extract(recipient.value, '$.address')) = ?1
2269
- )
2270
- `,
2271
- address.toLocaleLowerCase()
2272
- )
2273
- .toArray();
2274
-
2275
- return Number(row?.senders ?? 0) >= 2;
2276
- }
2277
-
2278
- /** Blocks win over AI; trusted senders override an AI spam verdict. */
2279
- private inboundPlacement(
2280
- screening: InboundScreening,
2281
- classification: EmailAiClassification | null
2282
- ): InboundPlacement {
2283
- if (screening.block) return { state: "spam", folderId: null };
2284
-
2285
- if (classification?.spam && !screening.trusted) {
2286
- return { state: "spam", folderId: null };
2287
- }
2288
-
2289
- return { state: null, folderId: classification?.folderId ?? null };
2290
- }
2291
-
2292
- /** The model from openworkspace.json; tests substitute one on the instance. */
2293
- protected classificationModel(): Promise<AiModel | null> {
2294
- return aiModel(this.bindings, "classification");
2295
- }
2296
-
2297
- private async classifyInbound(
2298
- rawMime: ArrayBuffer,
2299
- signals: ClassificationSignals | null
2300
- ) {
2301
- let ai: AiModel | null;
2302
-
2303
- try {
2304
- ai = await this.classificationModel();
2305
- } catch (error) {
2306
- throw new EmailAiClassificationError(
2307
- "The classification model is misconfigured",
2308
- { cause: error }
2309
- );
2310
- }
2311
-
2312
- if (!ai) return null;
2313
- const configuration = this.aiConfiguration();
2314
-
2315
- const customFolders = this.db
2316
- .select({ id: folders.id, name: folders.name })
2317
- .from(folders)
2318
- .orderBy(asc(folders.sortOrder), asc(folders.name))
2319
- .all();
2320
-
2321
- return classifyInboundEmail({
2322
- rawMime,
2323
- folders: customFolders,
2324
- configuration,
2325
- signals,
2326
- model: ai.id,
2327
- run: aiObjectRunner(ai),
2328
- });
2329
- }
2330
-
2331
- private insertClassifiedInboundEmail(
2332
- input: NewEmail,
2333
- classification: EmailAiClassification | null,
2334
- placement: InboundPlacement
2335
- ) {
2336
- const email = prepareOfficePreviews(input);
2337
-
2338
- const stored = this.db.transaction((tx) => {
2339
- const trustedFolder = placement.folderId
2340
- ? tx
2341
- .select({ id: folders.id })
2342
- .from(folders)
2343
- .where(eq(folders.id, placement.folderId))
2344
- .all()[0]
2345
- : null;
2346
-
2347
- const normalizedClassification =
2348
- classification?.folderId &&
2349
- !tx
2350
- .select({ id: folders.id })
2351
- .from(folders)
2352
- .where(eq(folders.id, classification.folderId))
2353
- .all()[0]
2354
- ? { ...classification, folderId: null }
2355
- : classification;
2356
-
2357
- const inserted = tx
2358
- .insert(emails)
2359
- .values({
2360
- ...email,
2361
- aiClassificationJson: normalizedClassification,
2362
- })
2363
- .onConflictDoNothing()
2364
- .returning()
2365
- .all()[0];
2366
-
2367
- if (!inserted) return null;
2368
- indexInsertedEmail(this.state.storage.sql, inserted.id);
2369
- insertOfficePreviewJobs(this.state.storage.sql, email);
2370
- recordCorrespondents(this.state.storage.sql, email);
2371
-
2372
- const activeConversation = and(
2373
- eq(conversations.id, email.conversationId),
2374
- eq(conversations.mailboxState, "active")
2375
- );
2376
-
2377
- if (placement.state) {
2378
- tx.update(conversations)
2379
- .set({ mailboxState: placement.state, folderId: null })
2380
- .where(activeConversation)
2381
- .run();
2382
- } else if (trustedFolder) {
2383
- tx.update(conversations)
2384
- .set({ folderId: trustedFolder.id })
2385
- .where(and(activeConversation, isNull(conversations.folderId)))
2386
- .run();
2387
- }
2388
-
2389
- return (
2390
- tx.select().from(emails).where(eq(emails.id, inserted.id)).all()[0] ??
2391
- null
2392
- );
2393
- });
2394
-
2395
- this.recentParticipantSources = null;
2396
-
2397
- return stored;
2398
- }
2399
-
2400
- /**
2401
- * Fills sender intelligence in on view: for a message without any, or
2402
- * replacing the failed result checked at `replacesCheckedAt`.
2403
- */
2404
- setEmailSenderIntel(
2405
- emailId: string,
2406
- intel: SenderIntel,
2407
- replacesCheckedAt: number | null = null
2408
- ) {
2409
- const current =
2410
- replacesCheckedAt === null
2411
- ? isNull(emails.senderIntelJson)
2412
- : sql`json_extract(${emails.senderIntelJson}, '$.checkedAt') = ${replacesCheckedAt}`;
2413
-
2414
- return (
2415
- this.db
2416
- .update(emails)
2417
- .set({ senderIntelJson: intel })
2418
- .where(
2419
- and(eq(emails.id, emailId), eq(emails.direction, "incoming"), current)
2420
- )
2421
- .returning({ id: emails.id })
2422
- .all().length > 0
2423
- );
2424
- }
2425
-
2426
- /** Inbound/outbound counters for the given addresses (lowercased keys). */
2427
- getSenderHistory(addresses: string[]) {
2428
- return Object.fromEntries(senderHistory(this.state.storage.sql, addresses));
2429
- }
2430
-
2431
- /** Block, trust and report state for senders, and unsubscribe records for lists. */
2432
- getMessageSafetyContext(addresses: string[], listKeys: string[]) {
2433
- const keys = [...new Set(listKeys)].slice(0, 100);
2434
-
2435
- const rows = keys.length
2436
- ? this.db
2437
- .select()
2438
- .from(unsubscriptions)
2439
- .where(inArray(unsubscriptions.listKey, keys))
2440
- .all()
2441
- : [];
2442
-
2443
- return {
2444
- senders: Object.fromEntries(
2445
- senderStatuses(this.state.storage.sql, addresses)
2446
- ),
2447
- unsubscriptions: Object.fromEntries(
2448
- rows.map((row): [string, Unsubscription] => [
2449
- row.listKey,
2450
- {
2451
- listKey: row.listKey,
2452
- method: row.method,
2453
- status: row.status,
2454
- target: row.target,
2455
- at: row.createdAt.getTime(),
2456
- },
2457
- ])
2458
- ),
2459
- };
2460
- }
2461
-
2462
- recordUnsubscription(input: {
2463
- listKey: string;
2464
- emailId: string;
2465
- method: Unsubscription["method"];
2466
- status: Unsubscription["status"];
2467
- target: string | null;
2468
- detail: string | null;
2469
- userId: string;
2470
- }): Unsubscription {
2471
- const createdAt = new Date();
2472
- const values = { ...input, createdAt };
2473
- this.db
2474
- .insert(unsubscriptions)
2475
- .values(values)
2476
- .onConflictDoUpdate({ target: unsubscriptions.listKey, set: values })
2477
- .run();
2478
- this.publishUpdate();
2479
-
2480
- return {
2481
- listKey: input.listKey,
2482
- method: input.method,
2483
- status: input.status,
2484
- target: input.target,
2485
- at: createdAt.getTime(),
2486
- };
2487
- }
2488
-
2489
- /** Moves every Inbox or Archive conversation with mail from the pattern to Spam. */
2490
- private moveSenderConversationsToSpam(pattern: string) {
2491
- const predicate = blockPatternPredicate(
2492
- "lower(json_extract(message.from_json, '$[0].address'))",
2493
- pattern
2494
- );
2495
-
2496
- return this.state.storage.sql
2497
- .exec<{ id: string }>(
2498
- `
2499
- update conversations
2500
- set mailbox_state = 'spam', folder_id = null
2501
- where mailbox_state in ('active', 'archive')
2502
- and id in (
2503
- select message.conversation_id from emails message
2504
- where message.direction = 'incoming' and ${predicate.sql}
2505
- )
2506
- returning id
2507
- `,
2508
- ...predicate.bindings
2509
- )
2510
- .toArray().length;
2511
- }
2512
-
2513
- blockSender(pattern: string, moveExisting: boolean) {
2514
- const moved = this.db.transaction(() => {
2515
- setSenderBlocked(this.state.storage.sql, pattern, true, Date.now());
2516
-
2517
- return moveExisting ? this.moveSenderConversationsToSpam(pattern) : 0;
2518
- });
2519
-
2520
- this.recentParticipantSources = null;
2521
- this.publishUpdate();
2522
-
2523
- return { block: blockFromPattern(pattern, Date.now(), false), moved };
2524
- }
2525
-
2526
- /** For a workspace-wide block: existing mail goes to Spam; the block itself lives in D1. */
2527
- moveSenderToSpam(pattern: string) {
2528
- const moved = this.moveSenderConversationsToSpam(pattern);
2529
-
2530
- if (moved) {
2531
- this.recentParticipantSources = null;
2532
- this.publishUpdate();
2533
- }
2534
-
2535
- return moved;
2536
- }
2537
-
2538
- unblockSender(pattern: string) {
2539
- const existed =
2540
- this.state.storage.sql
2541
- .exec(
2542
- "select 1 from senders where address = ? and blocked_at is not null",
2543
- pattern
2544
- )
2545
- .toArray().length > 0;
2546
-
2547
- setSenderBlocked(this.state.storage.sql, pattern, false, Date.now());
2548
- this.recentParticipantSources = null;
2549
- this.publishUpdate();
2550
-
2551
- return existed;
2552
- }
2553
-
2554
- listBlockedSenders() {
2555
- return listBlockedSenders(this.state.storage.sql);
2556
- }
2557
-
2558
- setSenderTrusted(address: string, trusted: boolean) {
2559
- setSenderTrusted(this.state.storage.sql, address, trusted, Date.now());
2560
- this.publishUpdate();
2561
-
2562
- return true;
2563
- }
2564
-
2565
- /** The newest incoming message of each conversation, for actions that need a sender. */
2566
- latestIncomingEmails(conversationIds: string[]) {
2567
- const ids = [...new Set(conversationIds)].slice(0, 100);
2568
-
2569
- if (!ids.length) return [];
2570
-
2571
- const rows = this.state.storage.sql
2572
- .exec<{ id: string }>(
2573
- `
2574
- select (
2575
- select message.id from emails message
2576
- where message.conversation_id = requested.value and message.direction = 'incoming'
2577
- order by message.timeline_at desc, message.id desc limit 1
2578
- ) as id
2579
- from json_each(?) requested
2580
- `,
2581
- stringListJson(ids)
2582
- )
2583
- .toArray()
2584
- .flatMap((row) => (row.id ? [row.id] : []));
2585
-
2586
- return rows.length
2587
- ? this.db.select().from(emails).where(inArray(emails.id, rows)).all()
2588
- : [];
2589
- }
2590
-
2591
- /**
2592
- * Report spam: labels the message, records feedback for the classifier,
2593
- * and moves its conversation to Spam. Never contacts the sender.
2594
- */
2595
- reportMessage(input: { emailId: string; userId: string }) {
2596
- const email = this.getEmail(input.emailId);
2597
-
2598
- if (!email || email.direction !== "incoming") return null;
2599
- const address = email.fromJson[0]?.address ?? "";
2600
-
2601
- const moved = this.db.transaction((tx) => {
2602
- tx.update(emails)
2603
- .set({ reportLabel: "spam" })
2604
- .where(eq(emails.id, email.id))
2605
- .run();
2606
-
2607
- if (address.includes("@")) {
2608
- recordSenderFeedback(this.state.storage.sql, {
2609
- id: createId("fbk"),
2610
- address,
2611
- emailId: email.id,
2612
- label: "spam",
2613
- userId: input.userId,
2614
- now: Date.now(),
2615
- });
2616
- }
2617
-
2618
- return (
2619
- tx
2620
- .update(conversations)
2621
- .set({ mailboxState: "spam", folderId: null })
2622
- .where(
2623
- and(
2624
- eq(conversations.id, email.conversationId),
2625
- inArray(conversations.mailboxState, ["active", "archive"])
2626
- )
2627
- )
2628
- .returning({ id: conversations.id })
2629
- .all().length > 0
2630
- );
2631
- });
2632
-
2633
- this.recentParticipantSources = null;
2634
- this.publishUpdate();
2635
-
2636
- return {
2637
- email: required(this.getEmail(email.id), "The reported email exists"),
2638
- moved,
2639
- };
2640
- }
2641
-
2642
- /** "Not spam": back to Inbox, the sender becomes trusted, and the feedback is recorded. */
2643
- markNotSpam(input: { emailId: string; userId: string }) {
2644
- const email = this.getEmail(input.emailId);
2645
-
2646
- if (!email || email.direction !== "incoming") return null;
2647
- const address = email.fromJson[0]?.address ?? "";
2648
- const label: FeedbackLabel = "not_spam";
2649
-
2650
- const restored = this.db.transaction((tx) => {
2651
- tx.update(emails)
2652
- .set({ reportLabel: null })
2653
- .where(eq(emails.conversationId, email.conversationId))
2654
- .run();
2655
-
2656
- if (address.includes("@")) {
2657
- recordSenderFeedback(this.state.storage.sql, {
2658
- id: createId("fbk"),
2659
- address,
2660
- emailId: email.id,
2661
- label,
2662
- userId: input.userId,
2663
- now: Date.now(),
2664
- });
2665
- setSenderTrusted(this.state.storage.sql, address, true, Date.now());
2666
- }
2667
-
2668
- return (
2669
- tx
2670
- .update(conversations)
2671
- .set({ mailboxState: "active" })
2672
- .where(
2673
- and(
2674
- eq(conversations.id, email.conversationId),
2675
- eq(conversations.mailboxState, "spam")
2676
- )
2677
- )
2678
- .returning({ id: conversations.id })
2679
- .all().length > 0
2680
- );
2681
- });
2682
-
2683
- this.recentParticipantSources = null;
2684
- this.publishUpdate();
2685
-
2686
- return { restored, address: address.includes("@") ? address : null };
2687
- }
2688
-
2689
- submitOutgoing(input: NewEmail) {
2690
- return this.state.blockConcurrencyWhile(async () => {
2691
- if (
2692
- input.direction !== "outgoing" ||
2693
- input.transportState !== "unconfirmed"
2694
- ) {
2695
- throw new Error("Only unconfirmed outgoing messages can be submitted");
2696
- }
2697
-
2698
- if (!input.requestFingerprint) {
2699
- throw new Error("An outgoing request fingerprint is required");
2700
- }
2701
-
2702
- const email = prepareOfficePreviews(input);
2703
-
2704
- if (hasPendingOfficePreviews(email)) {
2705
- await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
2706
- }
2707
-
2708
- const submission = this.db.transaction((tx): SubmitOutgoingResult => {
2709
- const existing = tx
2710
- .select()
2711
- .from(emails)
2712
- .where(eq(emails.id, email.id))
2713
- .all()[0];
2714
-
2715
- if (existing) {
2716
- const sameRequest =
2717
- existing.direction === "outgoing" &&
2718
- existing.requestFingerprint === email.requestFingerprint;
2719
-
2720
- return {
2721
- outcome: sameRequest ? "existing" : "conflict",
2722
- email: existing,
2723
- };
2724
- }
2725
-
2726
- tx.insert(emails).values(email).run();
2727
- indexInsertedEmail(this.state.storage.sql, email.id);
2728
- insertOfficePreviewJobs(this.state.storage.sql, email);
2729
- recordCorrespondents(this.state.storage.sql, email);
2730
-
2731
- const inserted = tx
2732
- .select()
2733
- .from(emails)
2734
- .where(eq(emails.id, email.id))
2735
- .all()[0];
2736
-
2737
- if (!inserted) throw new Error("Outgoing message was not persisted");
2738
-
2739
- return { outcome: "inserted", email: inserted };
2740
- });
2741
-
2742
- if (submission.outcome !== "inserted") return submission;
2743
- this.recentParticipantSources = null;
2744
-
2745
- const result = {
2746
- ...submission,
2747
- email: await this.deliverOutgoing(submission.email.id),
2748
- };
2749
-
2750
- this.publishUpdate();
2751
-
2752
- return result;
2753
- });
2754
- }
2755
-
2756
- resendOutgoing(id: string) {
2757
- return this.state.blockConcurrencyWhile(async () => {
2758
- const result = this.db
2759
- .update(emails)
2760
- .set({
2761
- transportState: "unconfirmed",
2762
- messageIdHeader: null,
2763
- transportError: null,
2764
- deliveryStatusJson: [],
2765
- })
2766
- .where(
2767
- and(
2768
- eq(emails.id, id),
2769
- eq(emails.direction, "outgoing"),
2770
- inArray(emails.transportState, ["failed", "unconfirmed"])
2771
- )
2772
- )
2773
- .returning({ id: emails.id })
2774
- .all();
2775
-
2776
- if (!result.length) return null;
2777
- const email = await this.deliverOutgoing(id);
2778
- this.publishUpdate();
2779
-
2780
- return email;
2781
- });
2782
- }
2783
-
2784
- async seedMailbox(
2785
- folderValues: NewFolder[],
2786
- emailValues: NewEmail[],
2787
- conversationValues: {
2788
- id: string;
2789
- mailboxState?: MailboxState;
2790
- folderId?: string | null;
2791
- }[] = [],
2792
- senderValues: (typeof senders.$inferInsert)[] = []
2793
- ) {
2794
- this.db.transaction((tx) => {
2795
- // Prior history first: seeded messages then add to it exactly once.
2796
- for (const sender of senderValues) {
2797
- tx.insert(senders).values(sender).onConflictDoNothing().run();
2798
- }
2799
-
2800
- // Seeding sets the folder order afresh: seeded folders at their places,
2801
- // system folders at their defaults (so a demo login undoes a reorder).
2802
- tx.delete(systemFolderOrder).run();
2803
-
2804
- for (const folder of folderValues) {
2805
- tx.insert(folders)
2806
- .values(folder)
2807
- .onConflictDoUpdate({
2808
- target: folders.id,
2809
- set: { sortOrder: folder.sortOrder },
2810
- })
2811
- .run();
2812
- }
2813
-
2814
- for (const email of emailValues) {
2815
- const inserted = tx
2816
- .insert(emails)
2817
- .values(email)
2818
- .onConflictDoNothing()
2819
- .returning({ id: emails.id })
2820
- .all();
2821
-
2822
- if (!inserted.length) continue;
2823
- indexInsertedEmail(this.state.storage.sql, email.id);
2824
- recordCorrespondents(this.state.storage.sql, email);
2825
- }
2826
-
2827
- for (const conversation of conversationValues) {
2828
- tx.update(conversations)
2829
- .set({
2830
- mailboxState: conversation.mailboxState,
2831
- folderId: conversation.folderId,
2832
- })
2833
- .where(eq(conversations.id, conversation.id))
2834
- .run();
2835
- }
2836
- });
2837
- this.recentParticipantSources = null;
2838
- await this.syncInboxCounts();
1181
+ this.recentParticipantSources = null;
1182
+ await this.syncInboxCounts();
1183
+ this.scheduleRetention();
2839
1184
 
2840
1185
  return { folders: folderValues.length, emails: emailValues.length };
2841
1186
  }
@@ -2848,682 +1193,279 @@ export class MailboxDO extends DurableObject<Env> {
2848
1193
  emailIds: string[];
2849
1194
  blockedPatterns: { pattern: string; at: number }[];
2850
1195
  }) {
2851
- const storage = this.state.storage.sql;
2852
1196
  this.db.transaction(() => {
2853
- storage.exec(
2854
- "update emails set report_label = null where id in (select value from json_each(?))",
2855
- stringListJson(input.emailIds)
2856
- );
2857
- storage.exec("delete from unsubscriptions");
2858
- storage.exec("delete from sender_feedback");
2859
- storage.exec(
2860
- "update senders set trusted_at = null, reported_at = null, blocked_at = null"
2861
- );
1197
+ this.db
1198
+ .update(emails)
1199
+ .set({ reportLabel: null })
1200
+ .where(inJsonList(emails.id, input.emailIds))
1201
+ .run();
1202
+ this.db.delete(unsubscriptions).run();
1203
+ this.db.delete(senderFeedback).run();
1204
+ this.db
1205
+ .update(senders)
1206
+ .set({ trustedAt: null, reportedAt: null, blockedAt: null })
1207
+ .run();
2862
1208
 
2863
1209
  for (const block of input.blockedPatterns) {
2864
- setSenderBlocked(storage, block.pattern, true, block.at);
1210
+ setSenderBlocked(this.db, block.pattern, block.at);
2865
1211
  }
2866
1212
  });
2867
1213
  this.recentParticipantSources = null;
2868
1214
  }
2869
1215
 
2870
- bulkUpdateConversations(
1216
+ /**
1217
+ * Moves conversations still in `sourceFolderId` (a stale selection can't
1218
+ * overwrite a teammate's newer move), as `by.userId` asks, trusting the
1219
+ * senders it takes out of Spam only with `by.trustSenders`: see
1220
+ * `placeConversations` (no `by.userId`, no verdict: an Undo). Null when
1221
+ * a folder is missing.
1222
+ */
1223
+ async bulkUpdateConversations(
2871
1224
  conversationIds: string[],
2872
1225
  sourceFolderId: string,
2873
- update: ConversationUpdate
2874
- ) {
2875
- const sourceFolder = this.getFolder(sourceFolderId);
2876
-
2877
- if (!sourceFolder) return null;
2878
-
2879
- if (update.folderId) {
2880
- const targetFolder = this.getFolder(update.folderId);
2881
-
2882
- if (!targetFolder || targetFolder.kind !== "custom") return null;
1226
+ update: ConversationUpdate,
1227
+ by: {
1228
+ userId: string | null;
1229
+ trustSenders: boolean;
1230
+ undo?: boolean;
1231
+ offerUndo?: boolean;
2883
1232
  }
2884
-
2885
- const candidates = [...new Set(conversationIds)];
2886
-
2887
- if (!candidates.length) return 0;
2888
- const assignments: string[] = [];
2889
- const values: (string | null)[] = [];
2890
-
1233
+ ) {
2891
1234
  // A custom folder is a classification inside the active Inbox
2892
1235
  // distribution, so assigning one also restores the conversation.
2893
- const mailboxState = update.folderId
2894
- ? ("active" as const)
2895
- : update.mailboxState;
2896
-
2897
- if (mailboxState !== undefined) {
2898
- assignments.push("mailbox_state = ?");
2899
- values.push(mailboxState);
2900
- }
1236
+ const mailboxState =
1237
+ update.mailboxState ?? (update.folderId ? "active" : undefined);
2901
1238
 
2902
- if (update.folderId !== undefined) {
2903
- assignments.push("folder_id = ?");
2904
- values.push(update.folderId);
2905
- }
2906
-
2907
- if (!assignments.length) return 0;
2908
- const membership = folderMembership(sourceFolder);
2909
- const candidatesJson = stringListJson(candidates);
2910
-
2911
- // Setting folderId means placing the conversation in the Inbox
2912
- // distribution. Outgoing-only conversations must stay in Sent.
2913
- const targetPredicate =
2914
- update.folderId === undefined ? "" : "and c.has_incoming = 1";
2915
-
2916
- // Keep the source-folder guard in the update itself so a stale shared
2917
- // selection cannot overwrite a teammate's newer move.
2918
- const result = this.state.storage.sql
2919
- .exec<{ id: string }>(
2920
- `
2921
- update conversations as c
2922
- set ${assignments.join(", ")}
2923
- where c.id in (
2924
- select cast(value as text) from json_each(?)
2925
- )
2926
- and ${membership.predicate}
2927
- ${targetPredicate}
2928
- returning id
2929
- `,
2930
- ...values,
2931
- candidatesJson,
2932
- ...membership.bindings
2933
- )
2934
- .toArray();
1239
+ const workspaceBlocks = await blocksForLeavingSpam(this.context, [
1240
+ { conversationIds, mailboxState },
1241
+ ]);
2935
1242
 
2936
- if (result.length) this.publishUpdate();
1243
+ const sourceFolder = mailboxFolders.getFolder(this.context, sourceFolderId);
2937
1244
 
2938
- return result.length;
2939
- }
1245
+ if (!sourceFolder) return null;
2940
1246
 
2941
- async permanentlyDeleteConversations(conversationIds: string[]) {
2942
- const candidates = [...new Set(conversationIds)];
1247
+ if (update.folderId) {
1248
+ const targetFolder = mailboxFolders.getFolder(
1249
+ this.context,
1250
+ update.folderId
1251
+ );
2943
1252
 
2944
- if (!candidates.length) {
2945
- return { outcome: "not_found" as const, deletedCount: 0 };
1253
+ if (!targetFolder || targetFolder.kind !== "custom") return null;
2946
1254
  }
2947
1255
 
2948
- const candidatesJson = stringListJson(candidates);
2949
-
2950
- const storedConversations = this.db
2951
- .select({
2952
- id: conversations.id,
2953
- mailboxState: conversations.mailboxState,
2954
- })
2955
- .from(conversations)
2956
- .where(sql`${conversations.id} in (
2957
- select cast(value as text) from json_each(${candidatesJson})
2958
- )`)
2959
- .all();
2960
-
2961
- if (storedConversations.length !== candidates.length) {
2962
- return { outcome: "not_found" as const, deletedCount: 0 };
2963
- }
1256
+ const move = (beforeMerge?: (target: string) => void) =>
1257
+ placeConversations(
1258
+ this.context,
1259
+ conversationIds,
1260
+ { mailboxState, folderId: update.folderId },
1261
+ {
1262
+ only: folderMembership(sourceFolder),
1263
+ ...by,
1264
+ workspaceBlocks,
1265
+ beforeMerge,
1266
+ }
1267
+ );
2964
1268
 
2965
1269
  if (
2966
- storedConversations.some(
2967
- (conversation) => conversation.mailboxState !== "trash"
2968
- )
1270
+ by.offerUndo &&
1271
+ by.userId &&
1272
+ (mailboxState === "spam" ||
1273
+ (sourceFolderId === "spam" &&
1274
+ (mailboxState === "active" || mailboxState === "archive")))
2969
1275
  ) {
2970
- return { outcome: "not_in_trash" as const, deletedCount: 0 };
1276
+ return withSpamUndo(this.context, by.userId, conversationIds, move);
2971
1277
  }
2972
1278
 
2973
- const storedEmails = this.db
2974
- .select({
2975
- id: emails.id,
2976
- direction: emails.direction,
2977
- bodyHtmlR2Key: emails.bodyHtmlR2Key,
2978
- rawMimeR2Key: emails.rawMimeR2Key,
2979
- attachmentsJson: emails.attachmentsJson,
2980
- })
2981
- .from(emails)
2982
- .where(sql`${emails.conversationId} in (
2983
- select cast(value as text) from json_each(${candidatesJson})
2984
- )`)
2985
- .all();
2986
-
2987
- const incomingEmailIds = new Set(
2988
- storedEmails.flatMap((email) =>
2989
- email.direction === "incoming" ? [email.id] : []
2990
- )
2991
- );
2992
-
2993
- const pendingInboundIds = incomingEmailIds.size
2994
- ? this.db
2995
- .select({ id: pendingInbound.id })
2996
- .from(pendingInbound)
2997
- .all()
2998
- .flatMap((job) =>
2999
- incomingEmailIds.has(inboundMessageId(job.id)) ? [job.id] : []
3000
- )
3001
- : [];
3002
-
3003
- const pendingInboundIdsJson = stringListJson(pendingInboundIds);
3004
-
3005
- const objectKeys = [
3006
- ...new Set(
3007
- storedEmails.flatMap((email) => [
3008
- ...(email.bodyHtmlR2Key ? [email.bodyHtmlR2Key] : []),
3009
- ...(email.rawMimeR2Key ? [email.rawMimeR2Key] : []),
3010
- ...email.attachmentsJson.flatMap((attachment) => [
3011
- attachment.r2Key,
3012
- ...(officePreviewExtension(attachment.filename)
3013
- ? [officePreviewKey(attachment.r2Key)]
3014
- : []),
3015
- ]),
3016
- ])
3017
- ),
3018
- ];
3019
-
3020
- const referencedObjectKeys = this.referencedObjectKeys(
3021
- objectKeys,
3022
- candidates
3023
- );
1279
+ return { ...move(), undoId: null };
1280
+ }
3024
1281
 
3025
- const ownedObjectKeys = objectKeys.filter(
3026
- (objectKey) => !referencedObjectKeys.has(objectKey)
1282
+ undoSpamDecision(userId: string, id: string) {
1283
+ return this.state.blockConcurrencyWhile(() =>
1284
+ undoSpam(this.context, userId, id)
3027
1285
  );
1286
+ }
3028
1287
 
3029
- const cleanupAt = new Date();
3030
- // Schedule first so the cleanup rows committed below can never be left
3031
- // without a retry after an interruption. The short delay prevents the
3032
- // alarm from waking on setAlarm's await before the rows are inserted.
3033
- const cleanupAlarmAt = cleanupAt.getTime() + ALARM_WAKE_DELAY_MS;
3034
-
3035
- if (ownedObjectKeys.length) {
3036
- await this.scheduleAlarm(cleanupAlarmAt);
3037
- }
3038
-
3039
- this.db.transaction((tx) => {
3040
- tx.run(sql`
3041
- delete from pending_office_previews where email_id in (
3042
- select id from emails where conversation_id in (
3043
- select cast(value as text) from json_each(${candidatesJson})
3044
- )
3045
- )
3046
- `);
3047
-
3048
- for (const objectKey of ownedObjectKeys) {
3049
- tx.insert(pendingObjectDeletions)
3050
- .values({ objectKey, nextAttemptAt: cleanupAt })
3051
- .onConflictDoNothing()
3052
- .run();
3053
- }
3054
-
3055
- if (pendingInboundIds.length) {
3056
- tx.delete(pendingInbound)
3057
- .where(sql`${pendingInbound.id} in (
3058
- select cast(value as text) from json_each(${pendingInboundIdsJson})
3059
- )`)
3060
- .run();
3061
- }
3062
-
3063
- tx.run(sql`
3064
- delete from email_search where conversation_id in (
3065
- select cast(value as text) from json_each(${candidatesJson})
3066
- )
3067
- `);
3068
- tx.run(sql`
3069
- delete from email_read_states
3070
- where email_id in (
3071
- select id from emails where conversation_id in (
3072
- select cast(value as text) from json_each(${candidatesJson})
3073
- )
3074
- )
3075
- `);
3076
- tx.delete(conversations)
3077
- .where(sql`${conversations.id} in (
3078
- select cast(value as text) from json_each(${candidatesJson})
3079
- )`)
3080
- .run();
3081
- tx.delete(emails)
3082
- .where(sql`${emails.conversationId} in (
3083
- select cast(value as text) from json_each(${candidatesJson})
3084
- )`)
3085
- .run();
3086
- });
3087
- this.recentParticipantSources = null;
3088
- this.publishUpdate();
3089
-
3090
- return {
3091
- outcome: "deleted" as const,
3092
- deletedCount: storedConversations.length,
3093
- };
1288
+ permanentlyDeleteEmails(ids: string[]) {
1289
+ return mailboxStorage.permanentlyDeleteEmails(this.context, ids);
3094
1290
  }
3095
1291
 
3096
- private referencedObjectKeys(
3097
- objectKeys: string[],
3098
- excludedConversationIds: string[]
1292
+ permanentlyDeleteConversations(
1293
+ conversationIds: string[],
1294
+ fromState: RetentionFolder = "trash"
3099
1295
  ) {
3100
- if (!objectKeys.length) return new Set<string>();
3101
-
3102
- const rows = this.state.storage.sql
3103
- .exec<{ object_key: string }>(
3104
- `
3105
- with
3106
- candidate_keys(object_key) as (
3107
- select cast(value as text) from json_each(?)
3108
- ),
3109
- excluded_conversations(id) as (
3110
- select cast(value as text) from json_each(?)
3111
- )
3112
- select candidate.object_key
3113
- from candidate_keys candidate
3114
- where exists (
3115
- select 1
3116
- from emails message
3117
- where message.conversation_id not in (
3118
- select id from excluded_conversations
3119
- )
3120
- and (
3121
- message.body_html_r2_key = candidate.object_key
3122
- or message.raw_mime_r2_key = candidate.object_key
3123
- or exists (
3124
- select 1
3125
- from json_each(message.attachments_json) attachment
3126
- where json_extract(attachment.value, '$.r2Key') = candidate.object_key
3127
- or json_extract(attachment.value, '$.r2Key') || '.preview.pdf' = candidate.object_key
3128
- )
3129
- )
3130
- )
3131
- `,
3132
- stringListJson(objectKeys),
3133
- stringListJson(excludedConversationIds)
3134
- )
3135
- .toArray();
3136
-
3137
- return new Set(rows.map((row) => row.object_key));
1296
+ return mailboxStorage.permanentlyDeleteConversations(
1297
+ this.context,
1298
+ conversationIds,
1299
+ fromState
1300
+ );
3138
1301
  }
3139
1302
 
3140
1303
  updateTransport(id: string, update: TransportUpdate) {
3141
- const result = this.db
3142
- .update(emails)
3143
- .set({
3144
- transportState: update.state,
3145
- messageIdHeader: update.messageIdHeader,
3146
- transportError: update.error,
3147
- })
3148
- .where(and(eq(emails.id, id), eq(emails.direction, "outgoing")))
3149
- .returning({ id: emails.id })
3150
- .all();
3151
-
3152
- return result.length > 0;
1304
+ return mailboxOutbound.updateTransport(this.context, id, update);
3153
1305
  }
3154
1306
 
3155
1307
  recordDeliveryStatus(
3156
1308
  messageIdHeader: string,
3157
1309
  status: RecipientDeliveryStatus
3158
1310
  ) {
3159
- const email = this.getEmailByMessageId(messageIdHeader);
3160
-
3161
- if (!email || email.direction !== "outgoing") return "not_found" as const;
3162
-
3163
- const existing = email.deliveryStatusJson.find(
3164
- (item) => item.recipient === status.recipient
3165
- );
3166
-
3167
- if (existing?.eventId === status.eventId) return "duplicate" as const;
3168
-
3169
- if (existing && existing.eventAt > status.eventAt) return "stale" as const;
3170
-
3171
- const next = [
3172
- ...email.deliveryStatusJson.filter(
3173
- (item) => item.recipient !== status.recipient
3174
- ),
3175
- status,
3176
- ];
3177
-
3178
- this.db
3179
- .update(emails)
3180
- .set({ deliveryStatusJson: next })
3181
- .where(eq(emails.id, email.id))
3182
- .run();
3183
- this.publishUpdate();
3184
-
3185
- return "updated" as const;
3186
- }
3187
-
3188
- async alarm() {
3189
- const now = Date.now();
3190
- await this.finishImport();
3191
- await this.processInboundJobs(now);
3192
- await dispatchOfficePreviewJobs(
3193
- this.state.storage.sql,
3194
- this.bindings,
3195
- this.state.id.name ?? "unknown-mailbox"
1311
+ return mailboxOutbound.recordDeliveryStatus(
1312
+ this.context,
1313
+ messageIdHeader,
1314
+ status
3196
1315
  );
3197
- await this.processObjectDeletionJobs(now);
3198
- await this.scheduleRemainingWork();
3199
1316
  }
3200
1317
 
3201
1318
  /**
3202
- * One message reaches a person once: a copy from a team list is dropped when
3203
- * the same message already arrived directly (or the reverse), and a list
3204
- * copy of the person's own post is dropped next to the sent message.
1319
+ * The mailbox's background work, in the order a wake runs it: what an
1320
+ * import left to announce; files to delete (first, so a delivery that keeps
1321
+ * failing can't hold them back); deliveries to process; Trash and Spam to
1322
+ * empty; Office previews to queue (last, with the mail just stored). Each
1323
+ * says when it is next due, which sets the alarm.
3205
1324
  */
3206
- private isDuplicateDelivery(job: PendingInbound, rawMime: ArrayBuffer) {
3207
- const messageId = rawMessageId(rawMime);
3208
-
3209
- if (!messageId) return false;
3210
- const existing = this.getEmailByMessageId(messageId);
3211
-
3212
- if (!existing) return false;
3213
-
3214
- return existing.direction === "incoming" || Boolean(job.listAddress);
3215
- }
3216
-
3217
- private async processInboundJobs(now: number) {
3218
- const jobs = this.db
3219
- .select()
3220
- .from(pendingInbound)
3221
- .where(lte(pendingInbound.nextAttemptAt, new Date(now)))
3222
- .orderBy(
3223
- asc(pendingInbound.nextAttemptAt),
3224
- asc(pendingInbound.receivedAt)
3225
- )
3226
- // MIME parsing can be memory-heavy; the next due row schedules a quick
3227
- // follow-up, so one delivery per wake keeps peak memory bounded.
3228
- .limit(INBOUND_ALARM_BATCH_SIZE)
3229
- .all();
1325
+ private backgroundWork() {
1326
+ const m = this.context;
3230
1327
 
3231
- for (const job of jobs) {
3232
- // oxlint-disable-next-line eslint/no-await-in-loop -- one delivery at a time keeps MIME parsing's peak memory bounded
3233
- await this.processInboundJob(job, now);
3234
- }
1328
+ const earliest = (
1329
+ table: typeof pendingInbound | typeof pendingObjectDeletions
1330
+ ) =>
1331
+ this.db
1332
+ .select({ at: min(table.nextAttemptAt) })
1333
+ .from(table)
1334
+ .get()
1335
+ ?.at?.getTime() ?? null;
1336
+
1337
+ return [
1338
+ {
1339
+ nextDue: () => null,
1340
+ run: async () => {
1341
+ await mailboxImport.finishImport(m);
1342
+ },
1343
+ },
1344
+ {
1345
+ nextDue: () => nextSpamUndoExpiry(m),
1346
+ run: (now) => expireSpamUndo(m, now),
1347
+ },
1348
+ {
1349
+ nextDue: () => earliest(pendingObjectDeletions),
1350
+ run: (now) => mailboxStorage.processObjectDeletionJobs(m, now),
1351
+ },
1352
+ {
1353
+ nextDue: () => earliest(pendingInbound),
1354
+ run: (now) => mailboxInbound.processInboundJobs(m, now),
1355
+ },
1356
+ {
1357
+ nextDue: () => mailboxStorage.nextRetentionAt(m),
1358
+ run: (now) => mailboxStorage.processRetention(m, now),
1359
+ },
1360
+ {
1361
+ nextDue: () => nextOfficePreviewAttempt(this.db) ?? null,
1362
+ run: () =>
1363
+ dispatchOfficePreviewJobs(
1364
+ this.db,
1365
+ this.env,
1366
+ this.state.id.name ?? "unknown-mailbox"
1367
+ ),
1368
+ },
1369
+ ] satisfies {
1370
+ nextDue: () => number | null;
1371
+ run: (now: number) => void | Promise<void>;
1372
+ }[];
3235
1373
  }
3236
1374
 
3237
- private async processInboundJob(job: PendingInbound, now: number) {
3238
- const messageId = inboundMessageId(job.id);
3239
- const existing = this.getEmail(messageId);
3240
-
3241
- if (existing) {
3242
- await this.finishStoredInbound(job, existing, now, false);
3243
-
3244
- return;
3245
- }
3246
-
3247
- try {
3248
- const rawMime = await readInboundRawMime(this.bindings, job);
3249
-
3250
- if (this.isDuplicateDelivery(job, rawMime)) {
3251
- this.db
3252
- .delete(pendingInbound)
3253
- .where(eq(pendingInbound.id, job.id))
3254
- .run();
3255
-
3256
- return;
3257
- }
3258
-
3259
- const prepared = await prepareInboundEmail({
3260
- env: this.bindings,
3261
- mailboxId: this.state.id.name ?? "unknown-mailbox",
3262
- job,
3263
- rawMime,
3264
- resolveParent: (inReplyTo, references) =>
3265
- this.resolveParent(inReplyTo, references),
3266
- });
3267
-
3268
- const { intel, delivery, signals, screening } =
3269
- await this.inboundSenderSignals(prepared.email, prepared.linkDomains);
3270
-
3271
- const screeningJson: EmailScreening | null = screening.block
3272
- ? { blocked: screening.block.workspace ? "workspace" : "mailbox" }
3273
- : null;
3274
-
3275
- const email: NewEmail = {
3276
- ...prepared.email,
3277
- senderIntelJson: intel,
3278
- deliveryJson: delivery,
3279
- screeningJson,
3280
- };
3281
-
3282
- let classification: EmailAiClassification | null = null;
3283
- // Blocked senders need no model.
3284
- const skipAi = Boolean(screening.block);
1375
+ /**
1376
+ * Runs the background work that is due. One kind failing doesn't stop
1377
+ * the others; the first failure is rethrown after the next wake is set,
1378
+ * so the platform retries the alarm.
1379
+ */
1380
+ async alarm() {
1381
+ const now = Date.now();
1382
+ const failures: { error: unknown }[] = [];
3285
1383
 
1384
+ for (const work of this.backgroundWork()) {
3286
1385
  try {
3287
- if (!skipAi) {
3288
- classification = await this.classifyInbound(rawMime, signals);
3289
- }
1386
+ // oxlint-disable-next-line eslint/no-await-in-loop -- in order: see backgroundWork
1387
+ await work.run(now);
3290
1388
  } catch (error) {
3291
- if (!(error instanceof EmailAiClassificationError)) throw error;
3292
- const aiAttempts = job.aiAttempts + 1;
3293
-
3294
- if (aiAttempts < MAILBOX_AI_MAX_ATTEMPTS) {
3295
- this.db
3296
- .update(pendingInbound)
3297
- .set({
3298
- aiAttempts,
3299
- nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
3300
- })
3301
- .where(eq(pendingInbound.id, job.id))
3302
- .run();
3303
- console.error(
3304
- `Could not classify inbound delivery ${job.id}; retrying`,
3305
- error
3306
- );
3307
-
3308
- return;
3309
- }
3310
-
3311
- console.error(
3312
- `Could not classify inbound delivery ${job.id}; delivering to Inbox`,
3313
- error
3314
- );
3315
- }
3316
-
3317
- const stored = this.insertClassifiedInboundEmail(
3318
- email,
3319
- classification,
3320
- this.inboundPlacement(screening, classification)
3321
- );
3322
-
3323
- if (!stored) {
3324
- throw new Error("Parsed inbound email was not persisted");
1389
+ failures.push({ error });
3325
1390
  }
3326
-
3327
- await this.finishStoredInbound(job, stored, now, true);
3328
- } catch (error) {
3329
- if (error instanceof UnprocessableInboundEmailError) {
3330
- const fallback = prepareUnprocessableInboundEmail({
3331
- job,
3332
- reason: error.message,
3333
- rawMimeR2Key: job.rawObjectKey,
3334
- });
3335
-
3336
- const stored = await this.insertEmail(fallback);
3337
-
3338
- if (!stored) {
3339
- throw new Error("Inbound fallback email was not persisted", {
3340
- cause: error,
3341
- });
3342
- }
3343
-
3344
- await this.finishStoredInbound(job, stored, now, true);
3345
- console.error(`Stored fallback for inbound delivery ${job.id}`, error);
3346
-
3347
- return;
3348
- }
3349
-
3350
- if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
3351
- const fallback = prepareUnprocessableInboundEmail({
3352
- job,
3353
- reason: "Message processing remained unavailable for 24 hours",
3354
- rawMimeR2Key:
3355
- error instanceof MissingRawMimeError ? null : job.rawObjectKey,
3356
- });
3357
-
3358
- const stored = await this.insertEmail(fallback);
3359
-
3360
- if (!stored) {
3361
- throw new Error("Inbound infrastructure fallback was not persisted", {
3362
- cause: error,
3363
- });
3364
- }
3365
-
3366
- await this.finishStoredInbound(job, stored, now, true);
3367
- console.error(
3368
- `Stored infrastructure fallback for inbound delivery ${job.id}`,
3369
- error
3370
- );
3371
-
3372
- return;
3373
- }
3374
-
3375
- const attempts = job.attempts + 1;
3376
- this.db
3377
- .update(pendingInbound)
3378
- .set({
3379
- attempts,
3380
- nextAttemptAt: new Date(now + retryDelay(attempts)),
3381
- })
3382
- .where(eq(pendingInbound.id, job.id))
3383
- .run();
3384
- console.error(`Could not ingest inbound delivery ${job.id}`, error);
3385
1391
  }
3386
- }
3387
-
3388
- private async processObjectDeletionJobs(now: number) {
3389
- const jobs = this.db
3390
- .select()
3391
- .from(pendingObjectDeletions)
3392
- .where(lte(pendingObjectDeletions.nextAttemptAt, new Date(now)))
3393
- .orderBy(asc(pendingObjectDeletions.nextAttemptAt))
3394
- .limit(OBJECT_DELETION_ALARM_BATCH_SIZE)
3395
- .all();
3396
-
3397
- if (!jobs.length) return;
3398
- const objectKeys = jobs.map((job) => job.objectKey);
3399
- const referencedObjectKeys = this.referencedObjectKeys(objectKeys, []);
3400
-
3401
- const retainedKeys = objectKeys.filter((key) =>
3402
- referencedObjectKeys.has(key)
3403
- );
3404
1392
 
3405
- if (retainedKeys.length) {
3406
- this.db
3407
- .delete(pendingObjectDeletions)
3408
- .where(inArray(pendingObjectDeletions.objectKey, retainedKeys))
3409
- .run();
3410
- }
1393
+ await this.scheduleRemainingWork();
3411
1394
 
3412
- const deletableJobs = jobs.filter(
3413
- (job) => !referencedObjectKeys.has(job.objectKey)
3414
- );
1395
+ if (failures[0]) throw failures[0].error;
1396
+ }
3415
1397
 
3416
- if (!deletableJobs.length) return;
3417
- const deletableKeys = deletableJobs.map((job) => job.objectKey);
1398
+ /** When the earliest background work is due, or null. */
1399
+ private nextDueWork() {
1400
+ const due = this.backgroundWork().flatMap((work) => {
1401
+ const at = work.nextDue();
3418
1402
 
3419
- try {
3420
- await this.bindings.MAIL_STORAGE.delete(deletableKeys);
3421
- this.db
3422
- .delete(pendingObjectDeletions)
3423
- .where(inArray(pendingObjectDeletions.objectKey, deletableKeys))
3424
- .run();
3425
- } catch (error) {
3426
- for (const job of deletableJobs) {
3427
- const attempts = job.attempts + 1;
3428
- this.db
3429
- .update(pendingObjectDeletions)
3430
- .set({
3431
- attempts,
3432
- nextAttemptAt: new Date(now + retryDelay(attempts)),
3433
- })
3434
- .where(eq(pendingObjectDeletions.objectKey, job.objectKey))
3435
- .run();
3436
- }
1403
+ return at === null ? [] : [at];
1404
+ });
3437
1405
 
3438
- console.error("Could not delete permanent message objects", error);
3439
- }
1406
+ return due.length > 0 ? Math.min(...due) : null;
3440
1407
  }
3441
1408
 
1409
+ /**
1410
+ * Schedules the next wake for the work left. A wake set only for a parse
1411
+ * that might never finish (`recordInboundAttempt`) is replaced by the real
1412
+ * next due time, or removed when nothing is due, so a stored message does
1413
+ * not cause an empty wake. Any other alarm is only moved earlier.
1414
+ */
3442
1415
  private async scheduleRemainingWork() {
3443
- const nextInbound = this.db
3444
- .select({ nextAttemptAt: pendingInbound.nextAttemptAt })
3445
- .from(pendingInbound)
3446
- .orderBy(asc(pendingInbound.nextAttemptAt))
3447
- .limit(1)
3448
- .all()[0];
3449
-
3450
- const nextObjectDeletion = this.db
3451
- .select({ nextAttemptAt: pendingObjectDeletions.nextAttemptAt })
3452
- .from(pendingObjectDeletions)
3453
- .orderBy(asc(pendingObjectDeletions.nextAttemptAt))
3454
- .limit(1)
3455
- .all()[0];
3456
-
3457
- const officePreviewAttempt = nextOfficePreviewAttempt(
3458
- this.state.storage.sql
3459
- );
3460
-
3461
- const attemptTimes = [
3462
- nextInbound,
3463
- nextObjectDeletion,
3464
- ...(officePreviewAttempt === undefined
3465
- ? []
3466
- : [{ nextAttemptAt: new Date(officePreviewAttempt) }]),
3467
- ].flatMap((job) => (job ? [job.nextAttemptAt.getTime()] : []));
3468
-
3469
- const nextAttemptAt =
3470
- attemptTimes.length > 0 ? Math.min(...attemptTimes) : null;
3471
-
3472
- if (nextAttemptAt !== null) {
3473
- await this.scheduleAlarm(
3474
- Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt)
3475
- );
1416
+ const { attemptAlarmAt } = this;
1417
+ this.attemptAlarmAt = null;
1418
+ const current = await this.state.storage.getAlarm();
1419
+ // Read after the await, so nothing changes between the read and the write.
1420
+ const nextAttemptAt = this.nextDueWork();
1421
+
1422
+ const wakeAt =
1423
+ nextAttemptAt === null
1424
+ ? null
1425
+ : Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt);
1426
+
1427
+ const ownWake =
1428
+ current !== null &&
1429
+ current === attemptAlarmAt &&
1430
+ // Imported mail waits for this alarm to be announced.
1431
+ !this.state.storage.kv.get<boolean>(IMPORT_PENDING_KEY);
1432
+
1433
+ if (ownWake) {
1434
+ await (wakeAt === null
1435
+ ? this.state.storage.deleteAlarm()
1436
+ : this.state.storage.setAlarm(wakeAt));
1437
+ } else if (wakeAt !== null) {
1438
+ await this.scheduleAlarm(wakeAt);
3476
1439
  }
3477
1440
  }
3478
1441
 
3479
- private async deliverOutgoing(id: string) {
3480
- const message = this.getEmail(id);
3481
-
3482
- if (
3483
- !message ||
3484
- message.direction !== "outgoing" ||
3485
- message.transportState !== "unconfirmed"
3486
- ) {
3487
- throw new Error("Unconfirmed outgoing message was not found");
3488
- }
3489
-
3490
- let delivery: Awaited<ReturnType<typeof prepareOutboundDelivery>>;
3491
-
3492
- try {
3493
- delivery = await prepareOutboundDelivery(this.bindings, message);
3494
- } catch (error) {
3495
- this.updateTransport(message.id, {
3496
- state: "failed",
3497
- error: errorMessage(error),
3498
- });
3499
- const failed = this.getEmail(id);
3500
-
3501
- if (!failed) {
3502
- throw new Error("Failed message was not persisted", { cause: error });
3503
- }
1442
+ emptyFolder(state: RetentionFolder) {
1443
+ return mailboxStorage.emptyFolder(this.context, state);
1444
+ }
3504
1445
 
3505
- return failed;
3506
- }
1446
+ /**
1447
+ * Call after mail enters Trash or Spam: wakes when the oldest there is due.
1448
+ * Only moves the alarm earlier, so it can run beside `scheduleRemainingWork`.
1449
+ */
1450
+ private scheduleRetention() {
1451
+ const at = mailboxStorage.nextRetentionAt(this.context);
3507
1452
 
3508
- try {
3509
- const result = await this.bindings.EMAIL.send(delivery);
3510
- this.updateTransport(message.id, {
3511
- state: "submitted",
3512
- messageIdHeader: result.messageId,
3513
- error: null,
3514
- });
3515
- } catch (error) {
3516
- this.updateTransport(message.id, {
3517
- state: "unconfirmed",
3518
- error: errorMessage(error),
3519
- });
3520
- }
1453
+ if (at === null) return;
1454
+ this.state.waitUntil(
1455
+ this.scheduleAlarm(Math.max(Date.now() + ALARM_WAKE_DELAY_MS, at))
1456
+ );
1457
+ }
3521
1458
 
3522
- const delivered = this.getEmail(id);
1459
+ getAutoReply() {
1460
+ return autoReplies.getAutoReply(this.context);
1461
+ }
3523
1462
 
3524
- if (!delivered) throw new Error("Submitted message was not persisted");
1463
+ setAutoReply(input: AutoReplyInput, userId: string) {
1464
+ return autoReplies.setAutoReply(this.context, input, userId);
1465
+ }
3525
1466
 
3526
- return delivered;
1467
+ turnOffAutoReply(userId: string) {
1468
+ return autoReplies.turnOffAutoReply(this.context, userId);
3527
1469
  }
3528
1470
 
3529
1471
  private async scheduleAlarm(at: number) {
@@ -3535,6 +1477,15 @@ export class MailboxDO extends DurableObject<Env> {
3535
1477
  /**
3536
1478
  * Message-ID is intentionally non-unique. Ordered header arrays decide which
3537
1479
  * locally known copy is the parent; References fall back newest-to-oldest.
1480
+ *
1481
+ * Anyone can send mail that copies a Message-ID, so among the copies of
1482
+ * one Message-ID:
1483
+ * 1. a message this mailbox sent comes first: its Message-ID is the one
1484
+ * the counterparty's reply names, and a stranger's copy of it must not
1485
+ * take that reply (into Spam, say);
1486
+ * 2. then a copy whose conversation is outside Spam and Trash, so a copy
1487
+ * in Spam is picked only when every copy is in Spam or Trash;
1488
+ * 3. then the newest.
3538
1489
  */
3539
1490
  resolveParent(inReplyTo: string[], references: string[]) {
3540
1491
  const candidates = [...new Set([...inReplyTo, ...references])];
@@ -3542,30 +1493,34 @@ export class MailboxDO extends DurableObject<Env> {
3542
1493
  if (!candidates.length) return null;
3543
1494
 
3544
1495
  const rows = this.db
3545
- .select()
1496
+ .select({ email: emails, mailboxState: conversations.mailboxState })
3546
1497
  .from(emails)
3547
- .where(inArray(emails.messageIdHeader, candidates))
1498
+ .leftJoin(conversations, eq(conversations.id, emails.conversationId))
1499
+ // One bound list: In-Reply-To and References can name 200 ids together.
1500
+ .where(inJsonList(emails.messageIdHeader, candidates))
3548
1501
  .orderBy(desc(emails.timelineAt))
3549
1502
  .all();
3550
1503
 
1504
+ const rank = (row: (typeof rows)[number]) =>
1505
+ (row.email.direction === "outgoing" ? 0 : 2) +
1506
+ (row.mailboxState === "spam" || row.mailboxState === "trash" ? 1 : 0);
1507
+
3551
1508
  const byMessageId = new Map<string, (typeof rows)[number]>();
3552
1509
 
1510
+ // Rows are newest first, so a later row replaces a kept one only when it ranks better.
3553
1511
  for (const row of rows) {
3554
- if (row.messageIdHeader && !byMessageId.has(row.messageIdHeader)) {
3555
- byMessageId.set(row.messageIdHeader, row);
3556
- }
3557
- }
1512
+ const messageId = row.email.messageIdHeader;
3558
1513
 
3559
- for (const messageId of inReplyTo) {
3560
- const row = byMessageId.get(messageId);
1514
+ if (!messageId) continue;
1515
+ const kept = byMessageId.get(messageId);
3561
1516
 
3562
- if (row) return row;
1517
+ if (!kept || rank(row) < rank(kept)) byMessageId.set(messageId, row);
3563
1518
  }
3564
1519
 
3565
- for (const messageId of references.toReversed()) {
1520
+ for (const messageId of [...inReplyTo, ...references.toReversed()]) {
3566
1521
  const row = byMessageId.get(messageId);
3567
1522
 
3568
- if (row) return row;
1523
+ if (row) return row.email;
3569
1524
  }
3570
1525
 
3571
1526
  return null;