@open-workspace/email 0.4.2 → 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 (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -1,3 +1,6 @@
1
+ import { inJsonList } from "@open-workspace/core/module";
2
+ import { and, desc, eq, sql as query, inArray, isNotNull } from "drizzle-orm";
3
+
1
4
  import { blockPatternsFor } from "../../shared/mail-feedback";
2
5
  import type {
3
6
  FeedbackLabel,
@@ -5,7 +8,9 @@ import type {
5
8
  SenderStatus,
6
9
  } from "../../shared/mail-feedback";
7
10
  import type { SenderHistory } from "../mail/message-security";
11
+ import { senderFeedback, senders } from "./schema";
8
12
  import type { NewEmail } from "./schema";
13
+ import type { MailboxDatabase } from "./support";
9
14
 
10
15
  function normalized(address: string | null | undefined) {
11
16
  const value = address?.trim().toLocaleLowerCase() ?? "";
@@ -20,29 +25,39 @@ function timestamp(value: NewEmail["timelineAt"]) {
20
25
  return value instanceof Date ? value.getTime() : Number(value);
21
26
  }
22
27
 
28
+ /** What writes the sender tables: the Mailbox's database or its transaction. */
29
+ type SenderWriter = Pick<MailboxDatabase, "insert" | "update">;
30
+
23
31
  /**
24
32
  * Upserts the correspondent counters for one stored message. Call it inside
25
33
  * the transaction that inserted the row so counts never drift from `emails`.
26
34
  */
27
- export function recordCorrespondents(sql: SqlStorage, email: NewEmail) {
28
- const at = timestamp(email.timelineAt);
35
+ export function recordCorrespondents(
36
+ db: Pick<MailboxDatabase, "insert">,
37
+ email: NewEmail
38
+ ) {
39
+ const at = new Date(timestamp(email.timelineAt));
29
40
 
30
41
  if (email.direction === "incoming") {
31
42
  const sender = normalized(email.fromJson[0]?.address);
32
43
 
33
44
  if (!sender) return;
34
- sql.exec(
35
- `insert into senders (address, domain, first_seen_at, last_seen_at, message_count)
36
- values (?, ?, ?, ?, 1)
37
- on conflict (address) do update set
38
- first_seen_at = min(coalesce(first_seen_at, excluded.first_seen_at), excluded.first_seen_at),
39
- last_seen_at = max(coalesce(last_seen_at, excluded.last_seen_at), excluded.last_seen_at),
40
- message_count = message_count + 1`,
41
- sender.address,
42
- sender.domain,
43
- at,
44
- at
45
- );
45
+ db.insert(senders)
46
+ .values({
47
+ ...sender,
48
+ firstSeenAt: at,
49
+ lastSeenAt: at,
50
+ messageCount: 1,
51
+ })
52
+ .onConflictDoUpdate({
53
+ target: senders.address,
54
+ set: {
55
+ firstSeenAt: query`min(coalesce(${senders.firstSeenAt}, ${at.getTime()}), ${at.getTime()})`,
56
+ lastSeenAt: query`max(coalesce(${senders.lastSeenAt}, ${at.getTime()}), ${at.getTime()})`,
57
+ messageCount: query`${senders.messageCount} + 1`,
58
+ },
59
+ })
60
+ .run();
46
61
 
47
62
  return;
48
63
  }
@@ -60,141 +75,166 @@ export function recordCorrespondents(sql: SqlStorage, email: NewEmail) {
60
75
  }
61
76
 
62
77
  for (const [address, domain] of recipients) {
63
- sql.exec(
64
- `insert into senders (address, domain, outbound_count, last_outbound_at)
65
- values (?, ?, 1, ?)
66
- on conflict (address) do update set
67
- outbound_count = outbound_count + 1,
68
- last_outbound_at = max(coalesce(last_outbound_at, excluded.last_outbound_at), excluded.last_outbound_at)`,
69
- address,
70
- domain,
71
- at
72
- );
78
+ db.insert(senders)
79
+ .values({ address, domain, outboundCount: 1, lastOutboundAt: at })
80
+ .onConflictDoUpdate({
81
+ target: senders.address,
82
+ set: {
83
+ outboundCount: query`${senders.outboundCount} + 1`,
84
+ lastOutboundAt: query`max(coalesce(${senders.lastOutboundAt}, ${at.getTime()}), ${at.getTime()})`,
85
+ },
86
+ })
87
+ .run();
73
88
  }
74
89
  }
75
90
 
76
- type SenderHistoryRow = {
77
- address: string;
78
- message_count: number;
79
- outbound_count: number;
80
- };
81
-
82
- export function senderHistory(sql: SqlStorage, addresses: string[]) {
91
+ export function senderHistory(db: MailboxDatabase, addresses: string[]) {
83
92
  const unique = [
84
93
  ...new Set(addresses.map((address) => address.toLocaleLowerCase())),
85
- ].slice(0, 100);
86
-
87
- const result = new Map<string, SenderHistory>();
88
-
89
- if (!unique.length) return result;
90
-
91
- const rows = sql
92
- .exec<SenderHistoryRow>(
93
- `select address, message_count, outbound_count from senders where address in (${unique.map(() => "?").join(", ")})`,
94
- ...unique
95
- )
96
- .toArray();
97
-
98
- for (const row of rows) {
99
- result.set(row.address, {
100
- inboundCount: Number(row.message_count),
101
- outboundCount: Number(row.outbound_count),
102
- });
103
- }
104
-
105
- return result;
94
+ ];
95
+
96
+ const rows = db
97
+ .select({
98
+ address: senders.address,
99
+ inboundCount: senders.messageCount,
100
+ outboundCount: senders.outboundCount,
101
+ })
102
+ .from(senders)
103
+ .where(inJsonList(senders.address, unique))
104
+ .all();
105
+
106
+ return new Map<string, SenderHistory>(
107
+ rows.map(({ address, ...history }) => [address, history])
108
+ );
106
109
  }
107
110
 
108
- type BlockRow = { address: string; blocked_at: number };
109
-
110
111
  /** The most specific mailbox block covering an address, if any. */
111
- export function mailboxBlockFor(
112
- sql: SqlStorage,
113
- address: string
114
- ): SenderBlock | null {
112
+ export function mailboxBlockFor(db: MailboxDatabase, address: string) {
115
113
  const patterns = blockPatternsFor(address);
116
114
 
117
115
  if (!patterns.length) return null;
118
116
 
119
- const rows = sql
120
- .exec<BlockRow>(
121
- `select address, blocked_at from senders
122
- where blocked_at is not null and address in (${patterns.map(() => "?").join(", ")})`,
123
- ...patterns
117
+ const rows = db
118
+ .select({ address: senders.address, at: senders.blockedAt })
119
+ .from(senders)
120
+ .where(
121
+ and(isNotNull(senders.blockedAt), inArray(senders.address, patterns))
124
122
  )
125
- .toArray();
123
+ .all();
126
124
 
127
- const pattern = patterns.find((candidate) =>
128
- rows.some((row) => row.address === candidate)
125
+ return firstBlock(
126
+ address,
127
+ new Map(rows.map((row) => [row.address, Number(row.at)])),
128
+ false
129
129
  );
130
-
131
- const row = rows.find((candidate) => candidate.address === pattern);
132
-
133
- return row
134
- ? blockFromPattern(row.address, Number(row.blocked_at), false)
135
- : null;
136
130
  }
137
131
 
138
132
  export function blockFromPattern(
139
133
  pattern: string,
140
134
  at: number,
141
135
  workspace: boolean
142
- ): SenderBlock {
136
+ ) {
143
137
  return {
144
138
  pattern,
145
139
  scope: pattern.startsWith("@") ? "domain" : "address",
146
140
  workspace,
147
141
  at,
148
- };
142
+ } satisfies SenderBlock;
149
143
  }
150
144
 
151
- /** First workspace-wide pattern (address before domains) that covers an address. */
152
- export function workspaceBlockFor(
145
+ /** An exact address wins over its parent domains. */
146
+ function firstBlock(
153
147
  address: string,
154
- patterns: ReadonlyMap<string, number>
148
+ patterns: ReadonlyMap<string, number>,
149
+ workspace: boolean
155
150
  ) {
156
151
  for (const pattern of blockPatternsFor(address)) {
157
152
  const blockedAt = patterns.get(pattern);
158
153
 
159
154
  if (blockedAt !== undefined) {
160
- return blockFromPattern(pattern, blockedAt, true);
155
+ return blockFromPattern(pattern, blockedAt, workspace);
161
156
  }
162
157
  }
163
158
 
164
159
  return null;
165
160
  }
166
161
 
167
- type StatusRow = {
168
- address: string;
169
- trusted_at: number | null;
170
- reported_at: number | null;
162
+ /** The addresses a message comes from: its From and its envelope sender. */
163
+ export type MessageSenders = {
164
+ from: string | null | undefined;
165
+ envelopeFrom: string | null | undefined;
171
166
  };
172
167
 
168
+ /**
169
+ * The block holding a message back: the workspace's (`workspaceBlocks`)
170
+ * on its From or its envelope sender, else the mailbox's (`mailboxBlock`
171
+ * looks one address up); null when none. The one rule, for delivery, the
172
+ * reader, a block that moves existing mail, and what Not spam or a reply
173
+ * says about a sender.
174
+ */
175
+ export function senderBlockFor(
176
+ sender: MessageSenders,
177
+ workspaceBlocks: ReadonlyMap<string, number>,
178
+ mailboxBlock: (address: string) => SenderBlock | null
179
+ ) {
180
+ const addresses = [sender.from, sender.envelopeFrom].flatMap((address) => {
181
+ const value = address?.trim().toLocaleLowerCase() ?? "";
182
+
183
+ return value.includes("@") ? [value] : [];
184
+ });
185
+
186
+ for (const address of addresses) {
187
+ const block = firstBlock(address, workspaceBlocks, true);
188
+
189
+ if (block) return block;
190
+ }
191
+
192
+ for (const address of addresses) {
193
+ const block = mailboxBlock(address);
194
+
195
+ if (block) return block;
196
+ }
197
+
198
+ return null;
199
+ }
200
+
173
201
  /** Block, trust and report state of each address in this mailbox (lowercased keys). */
174
- export function senderStatuses(sql: SqlStorage, addresses: string[]) {
202
+
203
+ export function senderStatuses(db: MailboxDatabase, addresses: string[]) {
175
204
  const unique = [
176
205
  ...new Set(addresses.map((address) => address.toLocaleLowerCase())),
177
- ].slice(0, 100);
178
-
179
- const result = new Map<string, SenderStatus>();
206
+ ];
207
+
208
+ // Domain blocks apply to multiple senders; fetch those rows in the same read.
209
+ const keys = [...unique, ...unique.flatMap(blockPatternsFor)];
210
+
211
+ const rows = db
212
+ .select({
213
+ address: senders.address,
214
+ blockedAt: senders.blockedAt,
215
+ trustedAt: senders.trustedAt,
216
+ reportedAt: senders.reportedAt,
217
+ })
218
+ .from(senders)
219
+ .where(inJsonList(senders.address, keys))
220
+ .all();
180
221
 
181
- if (!unique.length) return result;
222
+ const byAddress = new Map(rows.map((row) => [row.address, row]));
182
223
 
183
- const rows = sql
184
- .exec<StatusRow>(
185
- `select address, trusted_at, reported_at from senders where address in (${unique.map(() => "?").join(", ")})`,
186
- ...unique
224
+ const blocks = new Map(
225
+ rows.flatMap((row) =>
226
+ row.blockedAt ? [[row.address, row.blockedAt.getTime()] as const] : []
187
227
  )
188
- .toArray();
228
+ );
189
229
 
190
- const byAddress = new Map(rows.map((row) => [row.address, row]));
230
+ const result = new Map<string, SenderStatus>();
191
231
 
192
232
  for (const address of unique) {
193
233
  const row = byAddress.get(address);
194
234
  result.set(address, {
195
- block: mailboxBlockFor(sql, address),
196
- trustedAt: row?.trusted_at == null ? null : Number(row.trusted_at),
197
- reportedAt: row?.reported_at == null ? null : Number(row.reported_at),
235
+ block: firstBlock(address, blocks, false),
236
+ trustedAt: row?.trustedAt?.getTime() ?? null,
237
+ reportedAt: row?.reportedAt?.getTime() ?? null,
198
238
  });
199
239
  }
200
240
 
@@ -209,29 +249,24 @@ function patternDomain(pattern: string) {
209
249
 
210
250
  /** Blocking clears trust: the two decisions are mutually exclusive. */
211
251
  export function setSenderBlocked(
212
- sql: SqlStorage,
252
+ db: SenderWriter,
213
253
  pattern: string,
214
- blocked: boolean,
215
254
  now: number
216
255
  ) {
217
- if (!blocked) {
218
- sql.exec("update senders set blocked_at = null where address = ?", pattern);
219
-
220
- return;
221
- }
222
-
223
- sql.exec(
224
- `insert into senders (address, domain, blocked_at) values (?, ?, ?)
225
- on conflict (address) do update set blocked_at = excluded.blocked_at, trusted_at = null`,
226
- pattern,
227
- patternDomain(pattern),
228
- now
229
- );
256
+ const blockedAt = new Date(now);
257
+
258
+ db.insert(senders)
259
+ .values({ address: pattern, domain: patternDomain(pattern), blockedAt })
260
+ .onConflictDoUpdate({
261
+ target: senders.address,
262
+ set: { blockedAt, trustedAt: null },
263
+ })
264
+ .run();
230
265
  }
231
266
 
232
267
  /** Trusting an address also lifts a block on that exact address. */
233
268
  export function setSenderTrusted(
234
- sql: SqlStorage,
269
+ db: SenderWriter,
235
270
  address: string,
236
271
  trusted: boolean,
237
272
  now: number
@@ -239,18 +274,23 @@ export function setSenderTrusted(
239
274
  const value = address.toLocaleLowerCase();
240
275
 
241
276
  if (!trusted) {
242
- sql.exec("update senders set trusted_at = null where address = ?", value);
277
+ db.update(senders)
278
+ .set({ trustedAt: null })
279
+ .where(eq(senders.address, value))
280
+ .run();
243
281
 
244
282
  return;
245
283
  }
246
284
 
247
- sql.exec(
248
- `insert into senders (address, domain, trusted_at) values (?, ?, ?)
249
- on conflict (address) do update set trusted_at = excluded.trusted_at, blocked_at = null`,
250
- value,
251
- patternDomain(value),
252
- now
253
- );
285
+ const trustedAt = new Date(now);
286
+
287
+ db.insert(senders)
288
+ .values({ address: value, domain: patternDomain(value), trustedAt })
289
+ .onConflictDoUpdate({
290
+ target: senders.address,
291
+ set: { trustedAt, blockedAt: null },
292
+ })
293
+ .run();
254
294
  }
255
295
 
256
296
  export type BlockedSenderItem = {
@@ -260,22 +300,31 @@ export type BlockedSenderItem = {
260
300
  messageCount: number;
261
301
  };
262
302
 
263
- export function listBlockedSenders(sql: SqlStorage): BlockedSenderItem[] {
264
- return sql
265
- .exec<{ address: string; blocked_at: number; message_count: number }>(
266
- "select address, blocked_at, message_count from senders where blocked_at is not null order by blocked_at desc limit 500"
267
- )
268
- .toArray()
269
- .map((row) => ({
270
- pattern: row.address,
271
- scope: row.address.startsWith("@") ? "domain" : "address",
272
- blockedAt: Number(row.blocked_at),
273
- messageCount: Number(row.message_count),
274
- }));
303
+ export function listBlockedSenders(db: MailboxDatabase) {
304
+ return db
305
+ .select({
306
+ address: senders.address,
307
+ blockedAt: senders.blockedAt,
308
+ messageCount: senders.messageCount,
309
+ })
310
+ .from(senders)
311
+ .where(isNotNull(senders.blockedAt))
312
+ .orderBy(desc(senders.blockedAt))
313
+ .limit(500)
314
+ .all()
315
+ .map(
316
+ (row) =>
317
+ ({
318
+ pattern: row.address,
319
+ scope: row.address.startsWith("@") ? "domain" : "address",
320
+ blockedAt: Number(row.blockedAt),
321
+ messageCount: row.messageCount,
322
+ }) satisfies BlockedSenderItem
323
+ );
275
324
  }
276
325
 
277
326
  export function recordSenderFeedback(
278
- sql: SqlStorage,
327
+ db: SenderWriter,
279
328
  input: {
280
329
  id: string;
281
330
  address: string;
@@ -287,60 +336,49 @@ export function recordSenderFeedback(
287
336
  ) {
288
337
  const address = input.address.toLocaleLowerCase();
289
338
  const domain = patternDomain(address);
290
- sql.exec(
291
- `insert into sender_feedback (id, address, domain, email_id, label, user_id, created_at)
292
- values (?, ?, ?, ?, ?, ?, ?)`,
293
- input.id,
294
- address,
295
- domain,
296
- input.emailId,
297
- input.label,
298
- input.userId,
299
- input.now
300
- );
339
+ const at = new Date(input.now);
340
+
341
+ db.insert(senderFeedback)
342
+ .values({
343
+ id: input.id,
344
+ address,
345
+ domain,
346
+ emailId: input.emailId,
347
+ label: input.label,
348
+ userId: input.userId,
349
+ createdAt: at,
350
+ })
351
+ .run();
301
352
 
302
353
  if (input.label === "not_spam") return;
303
- sql.exec(
304
- `insert into senders (address, domain, reported_at) values (?, ?, ?)
305
- on conflict (address) do update set reported_at = excluded.reported_at, trusted_at = null`,
306
- address,
307
- domain,
308
- input.now
309
- );
354
+ db.insert(senders)
355
+ .values({ address, domain, reportedAt: at })
356
+ .onConflictDoUpdate({
357
+ target: senders.address,
358
+ set: { reportedAt: at, trustedAt: null },
359
+ })
360
+ .run();
310
361
  }
311
362
 
312
363
  /**
313
364
  * Report history for the classifier: what people in this mailbox said about
314
365
  * the sender before. Every label other than "not_spam" counts as a report.
315
366
  */
316
- export function senderFeedbackSummary(sql: SqlStorage, address: string) {
367
+ export function senderFeedbackSummary(db: MailboxDatabase, address: string) {
317
368
  const value = address.toLocaleLowerCase();
318
- const domain = patternDomain(value);
319
-
320
- const rows = sql
321
- .exec<{ not_spam: number; same_address: number; count: number }>(
322
- `select label = 'not_spam' as not_spam, address = ? as same_address, count(*) as count
323
- from sender_feedback where domain = ? group by label = 'not_spam', address = ?`,
324
- value,
325
- domain,
326
- value
327
- )
328
- .toArray();
329
-
330
- const count = (notSpam: boolean, sameAddress: boolean) =>
331
- rows
332
- .filter(
333
- (row) =>
334
- Boolean(row.not_spam) === notSpam &&
335
- (!sameAddress || Boolean(row.same_address))
336
- )
337
- .reduce((total, row) => total + Number(row.count), 0);
338
-
339
- return {
340
- spamReports: count(false, true),
341
- notSpam: count(true, true),
342
- domainReports: count(false, false),
343
- };
369
+ const { label, address: sender } = senderFeedback;
370
+
371
+ const [counts] = db
372
+ .select({
373
+ spamReports: query<number>`count(*) filter (where ${label} <> 'not_spam' and ${sender} = ${value})`,
374
+ notSpam: query<number>`count(*) filter (where ${label} = 'not_spam' and ${sender} = ${value})`,
375
+ domainReports: query<number>`count(*) filter (where ${label} <> 'not_spam')`,
376
+ })
377
+ .from(senderFeedback)
378
+ .where(eq(senderFeedback.domain, patternDomain(value)))
379
+ .all();
380
+
381
+ return counts;
344
382
  }
345
383
 
346
384
  export type SenderFeedbackSummary = ReturnType<typeof senderFeedbackSummary>;
@@ -0,0 +1,138 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ import { inJsonList } from "@open-workspace/core/module";
4
+ import { count } from "drizzle-orm";
5
+
6
+ import type { MailboxState } from "../../shared/mail";
7
+ import { emails, folders } from "./schema";
8
+ import type { MailboxContext } from "./support";
9
+
10
+ type Thread = {
11
+ id: string;
12
+ mailbox_state: MailboxState;
13
+ folder_id: string | null;
14
+ state_changed_at: number | null;
15
+ latest_email_id: string;
16
+ timeline_at: number;
17
+ has_incoming: number;
18
+ has_outgoing: number;
19
+ count: number;
20
+ };
21
+
22
+ export type SpamFiling = {
23
+ messages: ReturnType<typeof filingMessages>;
24
+ threadsBefore: Thread[];
25
+ threadsAfter: Thread[];
26
+ threadIds: string[];
27
+ };
28
+
29
+ export function threads(m: MailboxContext, ids: string[]) {
30
+ return m.state.storage.sql
31
+ .exec<Thread>(
32
+ `select id, mailbox_state, folder_id, state_changed_at, latest_email_id, timeline_at, has_incoming, has_outgoing,
33
+ (select count(*) from emails where conversation_id = c.id) as count from conversations c
34
+ where id in (select value from json_each(?)) order by id`,
35
+ JSON.stringify(ids)
36
+ )
37
+ .toArray();
38
+ }
39
+
40
+ export function filingMessages(m: MailboxContext, ids: string[]) {
41
+ return m.db
42
+ .select({
43
+ id: emails.id,
44
+ conversation_id: emails.conversationId,
45
+ split_from_conversation_id: emails.splitFromConversationId,
46
+ report_label: emails.reportLabel,
47
+ })
48
+ .from(emails)
49
+ .where(inJsonList(emails.conversationId, ids))
50
+ .all();
51
+ }
52
+
53
+ export function canRestoreFiling(m: MailboxContext, receipt: SpamFiling) {
54
+ if (!isDeepStrictEqual(threads(m, receipt.threadIds), receipt.threadsAfter)) {
55
+ return false;
56
+ }
57
+
58
+ const previousFolders = [
59
+ ...new Set(
60
+ receipt.threadsBefore.flatMap((thread) =>
61
+ thread.folder_id ? [thread.folder_id] : []
62
+ )
63
+ ),
64
+ ];
65
+
66
+ if (!previousFolders.length) return true;
67
+
68
+ const existing = m.db
69
+ .select({ count: count() })
70
+ .from(folders)
71
+ .where(inJsonList(folders.id, previousFolders))
72
+ .get();
73
+
74
+ return existing?.count === previousFolders.length;
75
+ }
76
+
77
+ /** Restore the exact messages that split or rejoined, including search and open reply drafts. */
78
+ export function restoreFiling(m: MailboxContext, receipt: SpamFiling) {
79
+ const { sql } = m.state.storage;
80
+ const messages = JSON.stringify(receipt.messages);
81
+ const afterIds = new Set(receipt.threadsAfter.map((t) => t.id));
82
+ const priorIds = new Set(receipt.threadsBefore.map((t) => t.id));
83
+
84
+ const regrouped =
85
+ afterIds.size !== priorIds.size ||
86
+ [...afterIds].some((id) => !priorIds.has(id));
87
+
88
+ sql.exec(
89
+ `with prior as (select value ->> '$.id' as id, value ->> '$.conversation_id' as thread,
90
+ value ->> '$.split_from_conversation_id' as split, value ->> '$.report_label' as label from json_each(?))
91
+ update emails set conversation_id = prior.thread, split_from_conversation_id = prior.split, report_label = prior.label
92
+ from prior where emails.id = prior.id and (emails.conversation_id is not prior.thread or emails.split_from_conversation_id is not prior.split or emails.report_label is not prior.label)`,
93
+ messages
94
+ );
95
+ sql.exec(
96
+ `insert into conversations(id, latest_email_id, timeline_at, has_incoming, has_outgoing, mailbox_state, folder_id, state_changed_at)
97
+ select value ->> '$.id', value ->> '$.latest_email_id', value ->> '$.timeline_at', value ->> '$.has_incoming',
98
+ value ->> '$.has_outgoing', value ->> '$.mailbox_state', value ->> '$.folder_id', value ->> '$.state_changed_at'
99
+ from json_each(?) where true on conflict(id) do update set latest_email_id=excluded.latest_email_id,
100
+ timeline_at=excluded.timeline_at, has_incoming=excluded.has_incoming, has_outgoing=excluded.has_outgoing,
101
+ mailbox_state=excluded.mailbox_state, folder_id=excluded.folder_id, state_changed_at=excluded.state_changed_at`,
102
+ JSON.stringify(receipt.threadsBefore)
103
+ );
104
+
105
+ // Search and reply drafts follow the source message only when Undo changes its thread.
106
+ if (!regrouped) return;
107
+
108
+ for (const thread of receipt.threadsAfter) {
109
+ if (!priorIds.has(thread.id)) {
110
+ sql.exec("delete from conversations where id = ?", thread.id);
111
+ }
112
+ }
113
+
114
+ const sources = new Map<string, string[]>();
115
+
116
+ for (const message of receipt.messages) {
117
+ const group = sources.get(message.conversation_id);
118
+
119
+ if (group) group.push(message.id);
120
+ else sources.set(message.conversation_id, [message.id]);
121
+ }
122
+
123
+ for (const [threadId, group] of sources) {
124
+ const ids = JSON.stringify(group);
125
+ sql.exec(
126
+ `update email_search set conversation_id = ? where conversation_id <> ? and email_id in (select value from json_each(?))`,
127
+ threadId,
128
+ threadId,
129
+ ids
130
+ );
131
+ sql.exec(
132
+ `update drafts set conversation_id = ?, version = version + 1 where conversation_id <> ? and source_email_id in (select value from json_each(?))`,
133
+ threadId,
134
+ threadId,
135
+ ids
136
+ );
137
+ }
138
+ }