@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,8 +1,13 @@
1
- import { createDb } from "@open-workspace/core/module";
2
- import { and, desc, eq, ne } from "drizzle-orm";
1
+ import { configuredMailDomains, createDb } from "@open-workspace/core/module";
2
+ import { and, countDistinct, desc, eq, ne, or, sql } from "drizzle-orm";
3
3
 
4
+ import { blockPatternsFor } from "../../shared/mail-feedback";
4
5
  import type { FeedbackLabel } from "../../shared/mail-feedback";
5
6
  import { blockedSenders, senderReports } from "../db/schema";
7
+ import type { SpamVerdict } from "../mailbox/placement";
8
+ import { mailboxBlockFor, senderBlockFor } from "../mailbox/senders";
9
+ import type { MessageSenders } from "../mailbox/senders";
10
+ import type { MailboxDatabase } from "../mailbox/support";
6
11
  import { isolateCache, WORKSPACE_CACHE_TTL_MS } from "./isolate-cache";
7
12
 
8
13
  const MAX_WORKSPACE_BLOCKS = 5000;
@@ -21,6 +26,42 @@ export async function workspaceBlockPatterns(binding: D1Database) {
21
26
  return new Map(rows.map((row) => [row.pattern, row.createdAt.getTime()]));
22
27
  }
23
28
 
29
+ /**
30
+ * The one sender screen for arriving mail: the block holding it back when
31
+ * its From or envelope sender is blocked for the workspace or, given the
32
+ * mailbox's storage, for that mailbox; null when none. The workspace's
33
+ * blocks are read fresh, and when they can't be read this throws: the
34
+ * delivery is tried again later, never delivered unscreened.
35
+ */
36
+ export async function screenSender(
37
+ binding: D1Database,
38
+ sender: MessageSenders,
39
+ mailbox?: MailboxDatabase
40
+ ) {
41
+ if (!sender.from?.includes("@") && !sender.envelopeFrom?.includes("@")) {
42
+ return null;
43
+ }
44
+
45
+ return senderBlockFor(
46
+ sender,
47
+ await workspaceBlockPatterns(binding),
48
+ (address) => (mailbox ? mailboxBlockFor(mailbox, address) : null)
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The workspace's blocks, read fresh, for what moving mail out of Spam
54
+ * says about its senders (`leaveSpam`); null when they can't be read, and
55
+ * then it says nothing rather than fail the move.
56
+ */
57
+ export function workspaceBlocksForVerdicts(binding: D1Database) {
58
+ return workspaceBlockPatterns(binding).catch((error) => {
59
+ console.error("Could not read workspace blocks", error);
60
+
61
+ return null;
62
+ });
63
+ }
64
+
24
65
  const blockPatternCache = isolateCache(
25
66
  WORKSPACE_CACHE_TTL_MS,
26
67
  workspaceBlockPatterns
@@ -36,6 +77,32 @@ export function cachedWorkspaceBlockPatterns(binding: D1Database) {
36
77
  return blockPatternCache.get(binding);
37
78
  }
38
79
 
80
+ /** Whether an address's or block pattern's domain is one of the workspace's own mail domains, or overlaps one. */
81
+ export function blocksOwnMailDomain(pattern: string) {
82
+ const domain = pattern.slice(pattern.lastIndexOf("@") + 1);
83
+
84
+ return configuredMailDomains().some(
85
+ (name) =>
86
+ domain === name ||
87
+ domain.endsWith(`.${name}`) ||
88
+ name.endsWith(`.${domain}`)
89
+ );
90
+ }
91
+
92
+ /**
93
+ * Whether the mailbox at `ownAddress` may not block `pattern`: its own
94
+ * address or a domain over it, or a domain of the workspace (or over one),
95
+ * since the workspace's own mail would go to Spam with it. One colleague's
96
+ * address can still be blocked. The mailbox's screen and its restore both
97
+ * ask this.
98
+ */
99
+ export function mailboxBlockRefused(ownAddress: string, pattern: string) {
100
+ return (
101
+ blockPatternsFor(ownAddress).includes(pattern) ||
102
+ (pattern.startsWith("@") && blocksOwnMailDomain(pattern))
103
+ );
104
+ }
105
+
39
106
  export function forgetWorkspaceBlockPatterns() {
40
107
  blockPatternCache.clear();
41
108
  }
@@ -52,7 +119,8 @@ export async function recordWorkspaceFeedback(
52
119
  emailId: string;
53
120
  address: string;
54
121
  label: FeedbackLabel;
55
- }
122
+ },
123
+ keepPrevious = false
56
124
  ) {
57
125
  const address = input.address.toLocaleLowerCase();
58
126
 
@@ -74,24 +142,106 @@ export async function recordWorkspaceFeedback(
74
142
  ? ne(senderReports.label, "not_spam")
75
143
  : eq(senderReports.label, "not_spam");
76
144
 
77
- await db.batch([
78
- db
79
- .delete(senderReports)
80
- .where(
81
- and(
82
- eq(senderReports.mailboxId, input.mailboxId),
83
- eq(senderReports.address, address),
84
- opposite
85
- )
86
- ),
87
- db
88
- .insert(senderReports)
89
- .values(row)
90
- .onConflictDoUpdate({
91
- target: [senderReports.mailboxId, senderReports.emailId],
92
- set: { label: row.label, createdAt: row.createdAt },
93
- }),
145
+ const displaced = db
146
+ .delete(senderReports)
147
+ .where(
148
+ and(
149
+ eq(senderReports.mailboxId, input.mailboxId),
150
+ eq(senderReports.address, address),
151
+ or(opposite, eq(senderReports.emailId, input.emailId))
152
+ )
153
+ );
154
+
155
+ const insert = db.insert(senderReports).values(row);
156
+
157
+ if (!keepPrevious) {
158
+ await db.batch([displaced, insert]);
159
+
160
+ return;
161
+ }
162
+
163
+ const [previous] = await db.batch([
164
+ displaced.returning({
165
+ emailId: senderReports.emailId,
166
+ label: senderReports.label,
167
+ createdAt: senderReports.createdAt,
168
+ }),
169
+ insert,
94
170
  ]);
171
+
172
+ return {
173
+ address,
174
+ emailId: row.emailId,
175
+ at: row.createdAt.getTime(),
176
+ previous: previous.map(({ emailId, label, createdAt }) => ({
177
+ emailId,
178
+ label,
179
+ at: createdAt.getTime(),
180
+ })),
181
+ };
182
+ }
183
+
184
+ export type WorkspaceVerdictUndo = NonNullable<
185
+ Awaited<ReturnType<typeof recordWorkspaceFeedback>>
186
+ >;
187
+
188
+ /** Replay only rows displaced by this verdict, and only while that verdict is current. */
189
+ export async function undoWorkspaceFeedback(
190
+ binding: D1Database,
191
+ mailboxId: string,
192
+ changes: WorkspaceVerdictUndo[]
193
+ ) {
194
+ if (!changes.length) return;
195
+ await binding.batch(
196
+ changes.flatMap((change) => [
197
+ binding
198
+ .prepare(
199
+ "delete from sender_reports where mailbox_id = ? and email_id = ? and created_at = ?"
200
+ )
201
+ .bind(mailboxId, change.emailId, change.at),
202
+ binding
203
+ .prepare(`insert into sender_reports (mailbox_id, email_id, address, domain, label, created_at)
204
+ select ?, json_extract(value, '$.emailId'), ?, ?, json_extract(value, '$.label'), json_extract(value, '$.at')
205
+ from json_each(?) where changes() > 0 on conflict do nothing`)
206
+ .bind(
207
+ mailboxId,
208
+ change.address,
209
+ addressDomain(change.address),
210
+ JSON.stringify(change.previous)
211
+ ),
212
+ ])
213
+ );
214
+ }
215
+
216
+ /**
217
+ * Shares what a person said about senders in one mailbox (Report spam, Not
218
+ * spam, or a move into or out of Spam) with the workspace. A failure is
219
+ * logged: the mailbox already learned it.
220
+ */
221
+ export async function shareSpamVerdicts(
222
+ binding: D1Database,
223
+ mailboxId: string,
224
+ verdicts: readonly SpamVerdict[],
225
+ keepPrevious = false
226
+ ) {
227
+ const changes = await Promise.all(
228
+ verdicts.map((verdict) =>
229
+ recordWorkspaceFeedback(
230
+ binding,
231
+ { mailboxId, ...verdict },
232
+ keepPrevious
233
+ ).catch((error) => {
234
+ console.error(
235
+ `Could not share the ${verdict.label} verdict for ${verdict.emailId}`,
236
+ error
237
+ );
238
+
239
+ return undefined;
240
+ })
241
+ )
242
+ );
243
+
244
+ return changes.filter((change) => change !== undefined);
95
245
  }
96
246
 
97
247
  /** Verdicts other mailboxes in the workspace gave this sender and its domain. */
@@ -102,48 +252,32 @@ export async function workspaceFeedbackSummary(
102
252
  ) {
103
253
  const value = address.toLocaleLowerCase();
104
254
 
105
- const [groups, reporters] = await binding.batch<
106
- {
107
- label: FeedbackLabel;
108
- same_address: number;
109
- count: number;
110
- } & { mailboxes: number }
111
- >([
112
- binding
113
- .prepare(`
114
- select label, address = ?1 as same_address, count(*) as count
115
- from sender_reports
116
- where domain = ?2 and mailbox_id <> ?3
117
- group by label, address = ?1
118
- `)
119
- .bind(value, addressDomain(value), mailboxId),
120
- binding
121
- .prepare(`
122
- select count(distinct mailbox_id) as mailboxes
123
- from sender_reports
124
- where address = ?1 and label <> 'not_spam' and mailbox_id <> ?2
125
- `)
126
- .bind(value, mailboxId),
127
- ]);
128
-
129
- const rows = groups?.results ?? [];
255
+ const db = createDb(binding);
256
+ const { label, address: sender, mailboxId: reporter } = senderReports;
130
257
 
131
- const count = (labels: FeedbackLabel[], sameAddress: boolean) =>
132
- rows
133
- .filter(
134
- (row) =>
135
- labels.includes(row.label) &&
136
- Boolean(row.same_address) === sameAddress
137
- )
138
- .reduce((total, row) => total + Number(row.count), 0);
258
+ const [[counts], [distinct]] = await db.batch([
259
+ db
260
+ .select({
261
+ spamReports: sql<number>`count(*) filter (where ${label} = 'spam' and ${sender} = ${value})`,
262
+ notSpam: sql<number>`count(*) filter (where ${label} = 'not_spam' and ${sender} = ${value})`,
263
+ domainReports: sql<number>`count(*) filter (where ${label} = 'spam' and ${sender} <> ${value})`,
264
+ })
265
+ .from(senderReports)
266
+ .where(
267
+ and(
268
+ eq(senderReports.domain, addressDomain(value)),
269
+ ne(reporter, mailboxId)
270
+ )
271
+ ),
272
+ db
273
+ .select({ mailboxes: countDistinct(reporter) })
274
+ .from(senderReports)
275
+ .where(
276
+ and(eq(sender, value), ne(label, "not_spam"), ne(reporter, mailboxId))
277
+ ),
278
+ ]);
139
279
 
140
- return {
141
- spamReports: count(["spam"], true),
142
- notSpam: count(["not_spam"], true),
143
- domainReports: count(["spam"], false),
144
- /** How many other mailboxes reported this exact address. */
145
- reportingMailboxes: Number(reporters?.results[0]?.mailboxes ?? 0),
146
- };
280
+ return { ...counts, reportingMailboxes: distinct.mailboxes };
147
281
  }
148
282
 
149
283
  export type WorkspaceFeedbackSummary = Awaited<
@@ -14,7 +14,7 @@ import {
14
14
  hirelineHtml,
15
15
  } from "./demo-html";
16
16
  import type { EmailAiClassification, MailAddress } from "./model";
17
- import type { NewEmail, NewFolder } from "./schema";
17
+ import type { NewEmail } from "./schema";
18
18
 
19
19
  type DemoInput = {
20
20
  id: string;
@@ -336,10 +336,7 @@ function demoRawMime(input: DemoInput, now: number) {
336
336
  ].join("\r\n");
337
337
  }
338
338
 
339
- function demoSenderIntel(
340
- input: DemoInput,
341
- checkedAt: number
342
- ): SenderIntel | null {
339
+ function demoSenderIntel(input: DemoInput, checkedAt: number) {
343
340
  const { checks } = input;
344
341
  const intel = checks?.intel;
345
342
 
@@ -403,7 +400,7 @@ function demoSenderIntel(
403
400
  bimi: intel.bimi
404
401
  ? { domain: fromDomain, status: "ok", reason: null }
405
402
  : null,
406
- };
403
+ } satisfies SenderIntel;
407
404
  }
408
405
 
409
406
  /** The domain of a demo address; every one has one. */
@@ -411,7 +408,7 @@ function demoDomain(address: string) {
411
408
  return required(address.split("@")[1], `${address} has a domain`);
412
409
  }
413
410
 
414
- function email(input: DemoInput, now: number): NewEmail {
411
+ function email(input: DemoInput, now: number) {
415
412
  const timelineAt = new Date(now - input.ageMs);
416
413
  const outgoing = input.direction === "outgoing";
417
414
 
@@ -476,9 +473,9 @@ function email(input: DemoInput, now: number): NewEmail {
476
473
  const sam = { address: "sam@demo.example", name: "Sam Brooks" };
477
474
  const support = { address: "support@demo.example", name: "Customer care" };
478
475
 
479
- function demoInputs(mailboxId: string): DemoInput[] {
476
+ function demoInputs(mailboxId: string) {
480
477
  if (mailboxId === "mbx_demo_personal") {
481
- return [
478
+ const personalInputs: DemoInput[] = [
482
479
  {
483
480
  id: "msg_demo_01",
484
481
  conversationId: "conv_demo_launch",
@@ -1030,10 +1027,12 @@ function demoInputs(mailboxId: string): DemoInput[] {
1030
1027
  },
1031
1028
  },
1032
1029
  ];
1030
+
1031
+ return personalInputs;
1033
1032
  }
1034
1033
 
1035
1034
  if (mailboxId === "mbx_demo_support") {
1036
- return [
1035
+ const supportInputs: DemoInput[] = [
1037
1036
  {
1038
1037
  id: "msg_demo_08",
1039
1038
  conversationId: "conv_demo_customer1",
@@ -1198,6 +1197,8 @@ function demoInputs(mailboxId: string): DemoInput[] {
1198
1197
  },
1199
1198
  },
1200
1199
  ];
1200
+
1201
+ return supportInputs;
1201
1202
  }
1202
1203
 
1203
1204
  return [];
@@ -1253,10 +1254,7 @@ export function demoMailboxSenders(mailboxId: string, now = Date.now()) {
1253
1254
  return [];
1254
1255
  }
1255
1256
 
1256
- export function demoMailboxEmails(
1257
- mailboxId: string,
1258
- now = Date.now()
1259
- ): NewEmail[] {
1257
+ export function demoMailboxEmails(mailboxId: string, now = Date.now()) {
1260
1258
  return demoInputs(mailboxId).map((input) => email(input, now));
1261
1259
  }
1262
1260
 
@@ -1298,7 +1296,7 @@ export function demoMailboxObjects(mailboxId: string, now = Date.now()) {
1298
1296
  ]);
1299
1297
  }
1300
1298
 
1301
- export function demoMailboxFolders(mailboxId: string): NewFolder[] {
1299
+ export function demoMailboxFolders(mailboxId: string) {
1302
1300
  if (mailboxId !== "mbx_demo_personal") return [];
1303
1301
 
1304
1302
  return [
@@ -1,3 +1,35 @@
1
+ import { insertOfficePreviewJobs } from "./office-preview-jobs";
2
+ import { emails } from "./schema";
3
+ import type { NewEmail } from "./schema";
4
+ import { recordCorrespondents } from "./senders";
5
+ import type { MailboxDatabase } from "./support";
6
+
7
+ /**
8
+ * Stores one message, the one way every path does (delivery, sending,
9
+ * import, tests): its row, its conversation and search rows, its Office
10
+ * preview jobs and its correspondents. Call it inside a transaction. Null
11
+ * when a message with its id is stored already.
12
+ */
13
+ export function storeEmail(
14
+ db: Pick<MailboxDatabase, "insert">,
15
+ sql: SqlStorage,
16
+ email: NewEmail
17
+ ) {
18
+ const inserted = db
19
+ .insert(emails)
20
+ .values(email)
21
+ .onConflictDoNothing()
22
+ .returning()
23
+ .all()[0];
24
+
25
+ if (!inserted) return null;
26
+ indexInsertedEmail(sql, inserted.id);
27
+ insertOfficePreviewJobs(db, email);
28
+ recordCorrespondents(db, email);
29
+
30
+ return inserted;
31
+ }
32
+
1
33
  /**
2
34
  * Keeps the conversation projection and the search index in step with one
3
35
  * stored message. Call it inside the transaction that inserted the row, right
@@ -28,9 +60,7 @@ export function indexInsertedEmail(sql: SqlStorage, emailId: string) {
28
60
  end,
29
61
  timeline_at = max(conversations.timeline_at, excluded.timeline_at),
30
62
  mailbox_state = case
31
- when conversations.mailbox_state in ('archive', 'trash')
32
- or (conversations.mailbox_state = 'spam' and excluded.has_outgoing)
33
- then 'active'
63
+ when conversations.mailbox_state in ('archive', 'trash') then 'active'
34
64
  else conversations.mailbox_state
35
65
  end,
36
66
  has_incoming = conversations.has_incoming or excluded.has_incoming,
@@ -38,16 +68,65 @@ export function indexInsertedEmail(sql: SqlStorage, emailId: string) {
38
68
  emailId
39
69
  );
40
70
  sql.exec(
41
- `insert into email_search (email_id, conversation_id, subject, addresses, body)
42
- select id, conversation_id, subject,
43
- coalesce(from_json, '') || ' '
44
- || coalesce(reply_to_json, '') || ' '
45
- || coalesce(to_json, '') || ' '
46
- || coalesce(cc_json, '') || ' '
47
- || coalesce(bcc_json, ''),
48
- coalesce(body_text, '') || ' ' || coalesce(preview, '')
49
- from emails
50
- where id = ?`,
71
+ "insert into email_search select * from email_search_document where email_id = ?",
51
72
  emailId
52
73
  );
53
74
  }
75
+
76
+ /**
77
+ * Moves every message of conversation `fromId` into `intoId`, inside the
78
+ * caller's transaction: the messages, their search rows, and `intoId`'s
79
+ * latest message, timeline and directions, which are recomputed from its
80
+ * messages. `intoId` keeps its place (state and folder); `fromId` is removed.
81
+ * Read states belong to messages and move with them.
82
+ */
83
+ export function mergeConversation(
84
+ sql: SqlStorage,
85
+ fromId: string,
86
+ intoId: string
87
+ ) {
88
+ sql.exec(
89
+ "update emails set conversation_id = ? where conversation_id = ?",
90
+ intoId,
91
+ fromId
92
+ );
93
+ sql.exec(
94
+ "update email_search set conversation_id = ? where conversation_id = ?",
95
+ intoId,
96
+ fromId
97
+ );
98
+ // Reply drafts follow their conversation, or they'd name one that's gone.
99
+ sql.exec(
100
+ "update drafts set conversation_id = ?, version = version + 1 where conversation_id = ?",
101
+ intoId,
102
+ fromId
103
+ );
104
+ refreshConversation(sql, intoId);
105
+ sql.exec("delete from conversations where id = ?", fromId);
106
+ }
107
+
108
+ /**
109
+ * Recomputes a conversation's latest message, timeline and directions from
110
+ * the messages it holds, after messages moved in or out of it.
111
+ */
112
+ export function refreshConversation(
113
+ sql: SqlStorage,
114
+ conversationId: string,
115
+ excluding: string[] = []
116
+ ) {
117
+ sql.exec(
118
+ `with remaining as (
119
+ select id, timeline_at, direction from emails
120
+ where conversation_id = ? and id not in (select value from json_each(?))
121
+ )
122
+ update conversations set
123
+ latest_email_id = (select id from remaining order by timeline_at desc, id desc limit 1),
124
+ timeline_at = (select max(timeline_at) from remaining),
125
+ has_incoming = exists (select 1 from remaining where direction = 'incoming'),
126
+ has_outgoing = exists (select 1 from remaining where direction = 'outgoing')
127
+ where id = ? and exists (select 1 from remaining)`,
128
+ conversationId,
129
+ JSON.stringify(excluding),
130
+ conversationId
131
+ );
132
+ }
@@ -44,26 +44,6 @@ export function customFolderPredicate(conversationAlias: string) {
44
44
  return inboxDistributionPredicate(conversationAlias);
45
45
  }
46
46
 
47
- export function folderAggregateJoinPredicate(
48
- folderAlias: string,
49
- conversationAlias: string
50
- ) {
51
- const custom = `(
52
- ${folderAlias}.kind = 'custom'
53
- and ${conversationAlias}.folder_id = ${folderAlias}.id
54
- and ${customFolderPredicate(conversationAlias)}
55
- )`;
56
-
57
- const system = systemFolderTypes.map(
58
- (systemType) => `(
59
- ${folderAlias}.system_type = '${systemType}'
60
- and ${systemFolderPredicate(systemType, conversationAlias)}
61
- )`
62
- );
63
-
64
- return [custom, ...system].join("\n or ");
65
- }
66
-
67
47
  /**
68
48
  * System folders are views over conversations, not stored folder records.
69
49
  * Only user-defined classification folders live in SQLite, with the places
@@ -1,5 +1,6 @@
1
1
  import type { ImportPlacement } from "../../shared/mail-import";
2
2
  import type { MailboxState } from "./folder-model";
3
+ import { placementRank } from "./placement";
3
4
 
4
5
  /** A conversation's place: its state, and its custom folder while it is in the Inbox. */
5
6
  export type ConversationPlacement = {
@@ -7,59 +8,43 @@ export type ConversationPlacement = {
7
8
  folderId: string | null;
8
9
  };
9
10
 
10
- /**
11
- * How strongly a place holds a conversation when imported messages disagree
12
- * (Gmail labels each message, a conversation here has one place): Trash,
13
- * then Spam, then a custom folder, then the Inbox, then Archive. A sent
14
- * message on its own has no say.
15
- */
11
+ /** A place's strength (`placementRank`); a sent message on its own has no say. */
16
12
  function rank(placement: ConversationPlacement | null) {
17
- if (!placement) return 0;
18
-
19
- switch (placement.mailboxState) {
20
- case "trash": {
21
- return 5;
22
- }
23
-
24
- case "spam": {
25
- return 4;
26
- }
27
-
28
- case "active": {
29
- return placement.folderId ? 3 : 2;
30
- }
31
-
32
- case "archive": {
33
- return 1;
34
- }
35
-
36
- default: {
37
- const unexpected: never = placement.mailboxState;
38
- throw new Error(`Unknown mailbox state ${String(unexpected)}`);
39
- }
40
- }
13
+ return placement ? placementRank(placement) : 0;
41
14
  }
42
15
 
43
16
  /** The place an imported message asks for, or null for none (`sent`). */
44
17
  export function requestedPlacement(
45
18
  placement: ImportPlacement,
46
19
  folderId: string | null
47
- ): ConversationPlacement | null {
20
+ ) {
48
21
  switch (placement) {
49
22
  case "inbox": {
50
- return { mailboxState: "active", folderId };
23
+ return {
24
+ mailboxState: "active",
25
+ folderId,
26
+ } satisfies ConversationPlacement;
51
27
  }
52
28
 
53
29
  case "archive": {
54
- return { mailboxState: "archive", folderId: null };
30
+ return {
31
+ mailboxState: "archive",
32
+ folderId: null,
33
+ } satisfies ConversationPlacement;
55
34
  }
56
35
 
57
36
  case "spam": {
58
- return { mailboxState: "spam", folderId: null };
37
+ return {
38
+ mailboxState: "spam",
39
+ folderId: null,
40
+ } satisfies ConversationPlacement;
59
41
  }
60
42
 
61
43
  case "trash": {
62
- return { mailboxState: "trash", folderId: null };
44
+ return {
45
+ mailboxState: "trash",
46
+ folderId: null,
47
+ } satisfies ConversationPlacement;
63
48
  }
64
49
 
65
50
  case "sent": {
@@ -81,7 +66,7 @@ export function requestedPlacement(
81
66
  export function mergedPlacement(
82
67
  before: ConversationPlacement | null,
83
68
  requested: ConversationPlacement | null
84
- ): ConversationPlacement | null {
69
+ ) {
85
70
  if (!before) return requested;
86
71
 
87
72
  return rank(requested) > rank(before) ? requested : before;