@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
@@ -0,0 +1,52 @@
1
+ import { eq } from "drizzle-orm";
2
+
3
+ import { mergeConversation } from "./email-index";
4
+ import { conversations } from "./schema";
5
+ import type { MailboxContext } from "./support";
6
+
7
+ function existingThread(m: MailboxContext, id: string | undefined) {
8
+ if (!id) return undefined;
9
+
10
+ return m.db
11
+ .select({ id: conversations.id })
12
+ .from(conversations)
13
+ .where(eq(conversations.id, id))
14
+ .get()?.id;
15
+ }
16
+
17
+ /** A snapshot's original thread, or the local thread identified by a duplicate. */
18
+ export function restoredThread(m: MailboxContext, source: string) {
19
+ return (
20
+ existingThread(m, source) ??
21
+ existingThread(
22
+ m,
23
+ m.state.storage.kv.get<string>(`restore-thread:${source}`)
24
+ )
25
+ );
26
+ }
27
+
28
+ export function rememberRestoredThread(
29
+ m: MailboxContext,
30
+ source: string,
31
+ provisional: string,
32
+ matched: string
33
+ ) {
34
+ if (matched === provisional) return;
35
+
36
+ // A second match in another local thread must not merge two existing threads.
37
+ const target = restoredThread(m, source);
38
+
39
+ if (target && target !== matched) return;
40
+
41
+ const merged = m.state.storage.transactionSync(() => {
42
+ if (!target) m.state.storage.kv.put(`restore-thread:${source}`, matched);
43
+
44
+ // Earlier snapshot lines may already have created a temporary thread.
45
+ if (!existingThread(m, provisional)) return false;
46
+ mergeConversation(m.state.storage.sql, provisional, matched);
47
+
48
+ return true;
49
+ });
50
+
51
+ if (merged) void m.announce({ push: false });
52
+ }
@@ -0,0 +1,36 @@
1
+ import type { MailboxState } from "./folder-model";
2
+
3
+ export type RetentionFolder = "trash" | "spam";
4
+
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+
7
+ export function isRetentionFolder(
8
+ state: string | null | undefined
9
+ ): state is RetentionFolder {
10
+ return state === "trash" || state === "spam";
11
+ }
12
+
13
+ /** Days from `Email({ retention })` (alchemy/index.ts); null keeps mail until emptied. */
14
+ export function retentionDays(
15
+ env: Pick<Env, "TRASH_RETENTION_DAYS" | "SPAM_RETENTION_DAYS">
16
+ ) {
17
+ return {
18
+ trash: Number(env.TRASH_RETENTION_DAYS) || null,
19
+ spam: Number(env.SPAM_RETENTION_DAYS) || null,
20
+ };
21
+ }
22
+
23
+ /** The folders that delete mail, with how long it stays in milliseconds. */
24
+ export function retentionRules(
25
+ env: Pick<Env, "TRASH_RETENTION_DAYS" | "SPAM_RETENTION_DAYS">
26
+ ) {
27
+ const days = retentionDays(env);
28
+
29
+ return (["trash", "spam"] as const satisfies MailboxState[]).flatMap(
30
+ (state) => {
31
+ const limit = days[state];
32
+
33
+ return limit ? [{ state, ms: limit * DAY_MS }] : [];
34
+ }
35
+ );
36
+ }
@@ -7,7 +7,10 @@ import {
7
7
  uniqueIndex,
8
8
  } from "drizzle-orm/sqlite-core";
9
9
 
10
- import { transportStates } from "../../shared/mail";
10
+ import { replyActionModes, transportStates } from "../../shared/mail";
11
+ import type { AutoReplyAudience } from "../../shared/mail";
12
+ import type { RichImage, StoredImageRef } from "../../shared/rich-content";
13
+ import type { RuleAction, RuleCondition } from "../mail/rules";
11
14
  import { mailboxStates } from "./folder-model";
12
15
  import type {
13
16
  DeliveryFacts,
@@ -20,6 +23,7 @@ import type {
20
23
  StoredAttachment,
21
24
  StoredEmailAuthentication,
22
25
  } from "./model";
26
+ import type { SpamUndoReceipt } from "./spam-undo";
23
27
 
24
28
  /**
25
29
  * Only custom classification folders are stored. Inbox, Sent, Archive, Spam,
@@ -64,6 +68,12 @@ export const pendingInbound = sqliteTable(
64
68
  receivedAt: integer("received_at", { mode: "timestamp_ms" }).notNull(),
65
69
  attempts: integer("attempts").notNull().default(0),
66
70
  aiAttempts: integer("ai_attempts").notNull().default(0),
71
+ /**
72
+ * Attempts that ended without an outcome: counted before parsing and
73
+ * given back when the attempt stores the message or records a failure,
74
+ * so only attempts whose alarm was killed (CPU, memory) remain.
75
+ */
76
+ unfinishedAttempts: integer("unfinished_attempts").notNull().default(0),
67
77
  nextAttemptAt: integer("next_attempt_at", {
68
78
  mode: "timestamp_ms",
69
79
  }).notNull(),
@@ -159,6 +169,8 @@ export const emails = sqliteTable(
159
169
  quotedText: text("quoted_text"),
160
170
  bodyHtmlR2Key: text("body_html_r2_key"),
161
171
  rawMimeR2Key: text("raw_mime_r2_key"),
172
+ rawSize: integer("raw_size"),
173
+ sentAt: integer("sent_at", { mode: "timestamp_ms" }),
162
174
  /** Header-derived sender authentication for incoming mail. */
163
175
  authenticationResultsJson: text("authentication_results_json", {
164
176
  mode: "json",
@@ -186,6 +198,11 @@ export const emails = sqliteTable(
186
198
  }).$type<EmailScreening>(),
187
199
  /** Set to "spam" when someone in this mailbox reported the message; only its presence is read. */
188
200
  reportLabel: text("report_label", { enum: ["spam"] }),
201
+ /**
202
+ * The conversation this spam message named but was kept out of (#25).
203
+ * It rejoins that conversation when it leaves Spam; cleared then.
204
+ */
205
+ splitFromConversationId: text("split_from_conversation_id"),
189
206
  attachmentsJson: text("attachments_json", { mode: "json" })
190
207
  .$type<StoredAttachment[]>()
191
208
  .notNull()
@@ -203,6 +220,12 @@ export const emails = sqliteTable(
203
220
  .$type<RecipientDeliveryStatus[]>()
204
221
  .notNull()
205
222
  .default([]),
223
+ /**
224
+ * The sha256 of the message's object in the backup bucket, once a
225
+ * snapshot stored it (worker/backups/mail-backup.ts). A message never
226
+ * changes, so later snapshots list it without reading it again.
227
+ */
228
+ backupSha256: text("backup_sha256"),
206
229
  },
207
230
  (table) => [
208
231
  index("emails_conversation_timeline_idx").on(
@@ -238,8 +261,17 @@ export const conversations = sqliteTable(
238
261
  hasOutgoing: integer("has_outgoing", { mode: "boolean" })
239
262
  .notNull()
240
263
  .default(false),
264
+ /**
265
+ * When the conversation entered Trash or Spam, which retention counts
266
+ * from. Set only by moves into those two; stale anywhere else.
267
+ */
268
+ stateChangedAt: integer("state_changed_at", { mode: "timestamp_ms" }),
241
269
  },
242
270
  (table) => [
271
+ index("conversations_state_changed_idx").on(
272
+ table.mailboxState,
273
+ table.stateChangedAt
274
+ ),
243
275
  index("conversations_timeline_idx").on(
244
276
  table.timelineAt,
245
277
  table.latestEmailId
@@ -310,6 +342,23 @@ export const senderFeedback = sqliteTable(
310
342
  ]
311
343
  );
312
344
 
345
+ /**
346
+ * What Undo puts back after someone reports spam or rescues mail from it:
347
+ * the filing and sender state before and after. Kept until `expiresAt`.
348
+ */
349
+ export const spamUndoReceipts = sqliteTable(
350
+ "spam_undo_receipts",
351
+ {
352
+ id: text("id").primaryKey(),
353
+ userId: text("user_id").notNull(),
354
+ receipt: text("receipt", { mode: "json" })
355
+ .$type<SpamUndoReceipt>()
356
+ .notNull(),
357
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
358
+ },
359
+ (table) => [index("spam_undo_receipts_expires_at_idx").on(table.expiresAt)]
360
+ );
361
+
313
362
  /** Latest unsubscribe attempt per list (List-Id, else the From organizational domain). */
314
363
  export const unsubscriptions = sqliteTable("unsubscriptions", {
315
364
  listKey: text("list_key").primaryKey(),
@@ -324,6 +373,47 @@ export const unsubscriptions = sqliteTable("unsubscriptions", {
324
373
  createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
325
374
  });
326
375
 
376
+ /** One of an auto-reply's two messages; its images are under `autoReplyImagePrefix`. */
377
+ export type AutoReplyMessage = {
378
+ enabled: boolean;
379
+ /** Null for "Auto: <original subject>". */
380
+ subject: string | null;
381
+ html: string;
382
+ text: string;
383
+ images: RichImage[];
384
+ };
385
+
386
+ /** One row (id 1): this mailbox's auto-reply. */
387
+ export const autoReplySettings = sqliteTable("auto_reply_settings", {
388
+ id: integer("id").primaryKey(),
389
+ enabled: integer("enabled", { mode: "boolean" }).notNull(),
390
+ startsAt: integer("starts_at", { mode: "timestamp_ms" }),
391
+ endsAt: integer("ends_at", { mode: "timestamp_ms" }),
392
+ replyIntervalDays: integer("reply_interval_days").notNull(),
393
+ /** For senders in the workspace's mail domains. */
394
+ inside: text("inside", { mode: "json" }).$type<AutoReplyMessage>().notNull(),
395
+ /** For everyone else, or only people this mailbox has written to. */
396
+ outside: text("outside", { mode: "json" })
397
+ .$type<AutoReplyMessage & { audience: AutoReplyAudience }>()
398
+ .notNull(),
399
+ updatedBy: text("updated_by").notNull(),
400
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
401
+ });
402
+
403
+ /** One row per sender answered during the current absence. */
404
+ export const autoReplyLog = sqliteTable(
405
+ "auto_reply_log",
406
+ {
407
+ senderAddress: text("sender_address").primaryKey(),
408
+ lastRepliedAt: integer("last_replied_at", {
409
+ mode: "timestamp_ms",
410
+ }).notNull(),
411
+ lastOriginalEmailId: text("last_original_email_id").notNull(),
412
+ lastOutboundMessageId: text("last_outbound_message_id"),
413
+ },
414
+ (table) => [index("auto_reply_log_replied_idx").on(table.lastRepliedAt)]
415
+ );
416
+
327
417
  export const mailboxAiConfiguration = sqliteTable("mailbox_ai_configuration", {
328
418
  id: text("id").primaryKey(),
329
419
  instructions: text("instructions").notNull().default(""),
@@ -351,8 +441,100 @@ export const emailReadStates = sqliteTable(
351
441
  ]
352
442
  );
353
443
 
444
+ /**
445
+ * A file a draft keeps at `r2Key` (see `draftFileKey`), under its upload's id,
446
+ * so the composer gets the same upload back when the draft reopens.
447
+ */
448
+ export type DraftAttachment = {
449
+ /** The composer's asset id, which the saved editor HTML refers to. */
450
+ assetId: string;
451
+ uploadId: string;
452
+ disposition: "attachment" | "inline";
453
+ contentId: string | null;
454
+ filename: string;
455
+ contentType: string;
456
+ size: number;
457
+ r2Key: string;
458
+ /**
459
+ * The signature image this is the draft's copy of, while the editor still
460
+ * shows it as one; a reopened draft turns it into an ordinary inline image.
461
+ */
462
+ storedImage?: StoredImageRef;
463
+ };
464
+
465
+ /**
466
+ * A composer's autosaved state. A draft belongs to its author, even in a
467
+ * shared mailbox, so the key starts with the user. `version` counts saves:
468
+ * a save names the version it was based on, so two windows editing one draft
469
+ * can't silently overwrite each other.
470
+ */
471
+ export const drafts = sqliteTable(
472
+ "drafts",
473
+ {
474
+ userId: text("user_id").notNull(),
475
+ id: text("id").notNull(),
476
+ kind: text("kind", { enum: ["compose", "reply", "forward"] }).notNull(),
477
+ /** The message replied to or forwarded. */
478
+ sourceEmailId: text("source_email_id"),
479
+ /** Null forwards all source files; an empty selection forwards none. */
480
+ forwardedAttachmentIds: text("forwarded_attachment_ids", {
481
+ mode: "json",
482
+ }).$type<string[]>(),
483
+ /** Its conversation, where a reply draft reopens. */
484
+ conversationId: text("conversation_id"),
485
+ replyMode: text("reply_mode", { enum: replyActionModes }),
486
+ to: text("to_json", { mode: "json" }).$type<string[]>().notNull(),
487
+ cc: text("cc_json", { mode: "json" }).$type<string[]>().notNull(),
488
+ bcc: text("bcc_json", { mode: "json" }).$type<string[]>().notNull(),
489
+ replyTo: text("reply_to"),
490
+ subject: text("subject").notNull(),
491
+ bodyText: text("body_text").notNull(),
492
+ /** The HTML as it would be sent: inline images are `cid:` attachments. */
493
+ bodyHtml: text("body_html"),
494
+ /**
495
+ * The web composer's own HTML, asset references included, which it
496
+ * reopens; null for a draft a mail app made over JMAP.
497
+ */
498
+ editorHtml: text("editor_html"),
499
+ /** Files the draft holds outside the expiring upload prefix. */
500
+ attachments: text("attachments_json", { mode: "json" })
501
+ .$type<DraftAttachment[]>()
502
+ .notNull()
503
+ .default([]),
504
+ version: integer("version").notNull(),
505
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
506
+ },
507
+ (table) => [
508
+ primaryKey({ columns: [table.userId, table.id] }),
509
+ index("drafts_user_updated_idx").on(table.userId, table.updatedAt),
510
+ ]
511
+ );
512
+
354
513
  export type Email = typeof emails.$inferSelect;
355
514
 
515
+ /** Ordered rules run on live deliveries; see worker/mail/rules.ts. */
516
+ export const mailRules = sqliteTable(
517
+ "mail_rules",
518
+ {
519
+ id: text("id").primaryKey(),
520
+ position: integer("position").notNull(),
521
+ name: text("name").notNull(),
522
+ enabled: integer("enabled", { mode: "boolean" }).notNull(),
523
+ match: text("match", { enum: ["all", "any"] }).notNull(),
524
+ conditionsJson: text("conditions_json", { mode: "json" })
525
+ .$type<RuleCondition[]>()
526
+ .notNull(),
527
+ actionsJson: text("actions_json", { mode: "json" })
528
+ .$type<RuleAction[]>()
529
+ .notNull(),
530
+ stopProcessing: integer("stop_processing", { mode: "boolean" }).notNull(),
531
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
532
+ },
533
+ (table) => [index("mail_rules_position_idx").on(table.position)]
534
+ );
535
+
536
+ export type MailRule = typeof mailRules.$inferSelect;
537
+
356
538
  export type SenderRecord = typeof senders.$inferSelect;
357
539
 
358
540
  export type UnsubscriptionRecord = typeof unsubscriptions.$inferSelect;
@@ -369,6 +551,34 @@ export type NewPendingInbound = typeof pendingInbound.$inferInsert;
369
551
 
370
552
  export type ConversationRecord = typeof conversations.$inferSelect;
371
553
 
554
+ export type AutoReplySettings = typeof autoReplySettings.$inferSelect;
555
+
372
556
  export type FolderRecord = typeof folders.$inferSelect;
373
557
 
374
558
  export type NewFolder = typeof folders.$inferInsert;
559
+
560
+ export type Draft = typeof drafts.$inferSelect;
561
+
562
+ /**
563
+ * What changed in the mailbox, for JMAP's Foo/changes: one row an object
564
+ * created, updated or destroyed, written by triggers on the tables JMAP
565
+ * reads (migration 0008). `seq` orders them and is the JMAP state;
566
+ * `user_id` limits a row to one person (their drafts, their read state).
567
+ * Old rows are pruned; a state from before the oldest left can't be
568
+ * answered (jmap-change-log.ts, jmapChanges).
569
+ */
570
+ export const jmapChanges = sqliteTable(
571
+ "jmap_changes",
572
+ {
573
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
574
+ type: text("type", {
575
+ enum: ["Email", "Thread", "Mailbox", "State"],
576
+ }).notNull(),
577
+ id: text("id").notNull(),
578
+ kind: text("kind", {
579
+ enum: ["created", "updated", "destroyed"],
580
+ }).notNull(),
581
+ userId: text("user_id"),
582
+ },
583
+ (table) => [index("jmap_changes_type_seq_idx").on(table.type, table.seq)]
584
+ );