@open-workspace/email 0.4.2 → 0.5.1

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 (268) 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-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -13,18 +13,20 @@ import {
13
13
  overRateLimit,
14
14
  } from "@open-workspace/core/module";
15
15
  import type { AppEnv } from "@open-workspace/core/module";
16
+ import { waitUntil } from "cloudflare:workers";
16
17
  import { Hono } from "hono";
17
- import type { Context } from "hono";
18
+ import type { Context, ErrorHandler } from "hono";
18
19
  import { z } from "zod";
19
20
 
20
21
  import { attachmentPreview } from "../../shared/attachment-preview";
22
+ import { DRAFTS_FOLDER_ID } from "../../shared/folder-order";
21
23
  import {
22
24
  baseSubject,
25
+ EmailSizeLimitError,
23
26
  isComposerInlineImageContentType,
24
27
  } from "../../shared/mail";
25
28
  import { remoteImageUrls } from "../../shared/mail-remote";
26
29
  import { MAX_TRANSLATION_CHARACTERS } from "../../shared/mail-translation";
27
- import { officePreviewKey } from "../../shared/office-preview";
28
30
  import {
29
31
  MAIL_ORGANIZE_SCOPE,
30
32
  MAIL_READ_SCOPE,
@@ -32,7 +34,9 @@ import {
32
34
  } from "../../shared/permissions";
33
35
  import { mailboxStub } from "../mailbox";
34
36
  import type { MailboxDO } from "../mailbox";
37
+ import { isRetentionFolder } from "../mailbox/retention";
35
38
  import type { Email } from "../mailbox/schema";
39
+ import type { ConversationPage, ListEmail } from "../mailbox/support";
36
40
  import {
37
41
  accessibleMailbox,
38
42
  accessibleMailboxes,
@@ -40,11 +44,15 @@ import {
40
44
  } from "./access";
41
45
  import type { MailboxListRow } from "./access";
42
46
  import { translateEmailSegments } from "./ai-translation";
47
+ import { autoReplyRoutes } from "./auto-reply-routes";
43
48
  import { BIMI_LOGO_HEADERS, bimiLogoPath, bimiObjectKey } from "./bimi";
49
+ import { mayOrganizeMailbox, organizeRefusal } from "./capabilities";
44
50
  import {
45
51
  decodeConversationCursor,
46
52
  encodeConversationCursor,
47
53
  } from "./conversation-cursor";
54
+ import { draftView, mailDraftRoutes } from "./draft-routes";
55
+ import { mailboxDraftSenders } from "./draft-sender";
48
56
  import { readStoredBody } from "./edge-cache";
49
57
  import {
50
58
  headerAuthentication,
@@ -59,20 +67,22 @@ import {
59
67
  ComposerAttachmentLimitError,
60
68
  preflightOutgoingAttachments,
61
69
  } from "./outbound";
70
+ import { separateHtmlQuote } from "./outbound-content";
62
71
  import {
63
72
  deferEmailSentWebhook,
64
73
  OutgoingRequestConflictError,
65
- submitOutgoing,
66
74
  } from "./outbound-service";
67
75
  import {
68
76
  OutgoingContextError,
69
77
  resolveForwardContext,
78
+ mailboxAliases,
70
79
  resolveReplyContext,
71
80
  } from "./outgoing-context";
72
81
  import { participantLabels } from "./participants";
73
82
  import { signR2GetUrl } from "./r2-presigned-urls";
74
83
  import { signRemoteToken } from "./remote-token";
75
84
  import { buildReplyPlan } from "./reply-plan";
85
+ import { ruleInputSchema, ruleTestSchema } from "./rules";
76
86
  import { mailSafetyRoutes } from "./safety-routes";
77
87
  import {
78
88
  attachmentPreflightSchema,
@@ -90,19 +100,28 @@ import {
90
100
  recipientSuggestionQuerySchema,
91
101
  renameFolderSchema,
92
102
  reorderFoldersSchema,
103
+ retentionFolderSchema,
93
104
  replySchema,
94
105
  uploadIdSchema,
95
106
  } from "./schemas";
96
107
  import { cachedWorkspaceIdentity, spamhausDqsKey } from "./security-settings";
97
108
  import type { WorkspaceIdentity } from "./security-settings";
109
+ import { sendMessage } from "./send-message";
110
+ import type { SendRequest } from "./send-message";
98
111
  import { storedSenderIntel } from "./sender-intel";
112
+ import { signatureRoutes } from "./signature-routes";
113
+ import { withSignature } from "./signatures";
114
+ import { officePreviewKey } from "./storage-keys";
99
115
  import {
100
116
  createComposerUploadIntent,
101
117
  discardComposerUploads,
102
118
  finalizeComposerUpload,
103
119
  UploadValidationError,
104
120
  } from "./uploads";
105
- import { cachedWorkspaceBlockPatterns } from "./workspace-safety";
121
+ import {
122
+ cachedWorkspaceBlockPatterns,
123
+ shareSpamVerdicts,
124
+ } from "./workspace-safety";
106
125
 
107
126
  function mediaType(contentType: string) {
108
127
  return contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
@@ -180,7 +199,7 @@ function getStoredObject(
180
199
  }
181
200
 
182
201
  /** Our own route for a BIMI logo, when DMARC allowed one for this message. */
183
- function senderLogoUrl(email: Email) {
202
+ function senderLogoUrl(email: ListEmail) {
184
203
  const bimi =
185
204
  email.direction === "incoming"
186
205
  ? storedSenderIntel(email.senderIntelJson)?.bimi
@@ -189,21 +208,27 @@ function senderLogoUrl(email: Email) {
189
208
  return bimi?.status === "ok" ? bimiLogoPath(bimi.domain) : null;
190
209
  }
191
210
 
192
- function toMessageSummary(email: Email) {
211
+ function messagePreview(email: ListEmail) {
193
212
  const from = email.fromJson[0] ?? { address: "unknown@invalid", name: null };
194
213
 
195
214
  return {
196
215
  id: email.id,
197
216
  conversationId: email.conversationId,
198
- direction: email.direction,
199
217
  fromAddress: from.address,
200
218
  fromName: from.name,
219
+ subject: email.subject,
220
+ preview: email.preview,
221
+ };
222
+ }
223
+
224
+ function toMessageSummary(email: ListEmail) {
225
+ return {
226
+ ...messagePreview(email),
227
+ direction: email.direction,
201
228
  toAddresses: email.toJson.map((item) => item.address),
202
229
  ccAddresses: email.ccJson.map((item) => item.address),
203
230
  bccAddresses: email.bccJson.map((item) => item.address),
204
231
  replyToAddresses: email.replyToJson.map((item) => item.address),
205
- subject: email.subject,
206
- preview: email.preview,
207
232
  transportState: email.transportState,
208
233
  transportError: email.transportError,
209
234
  deliveryStatuses: email.deliveryStatusJson,
@@ -224,7 +249,7 @@ function workspaceListAddress(email: Email) {
224
249
 
225
250
  function toMessageDetail(
226
251
  email: Email,
227
- ownAddress: string,
252
+ ownAddresses: readonly string[],
228
253
  identity: WorkspaceIdentity,
229
254
  history: Record<string, SenderHistory>,
230
255
  safety: MessageSafetyContext,
@@ -242,6 +267,7 @@ function toMessageDetail(
242
267
  ...toMessageSummary(email),
243
268
  bodyText: email.bodyText,
244
269
  quotedText: email.quotedText,
270
+ hasSeparateHtmlQuote: Boolean(separateHtmlQuote(email)),
245
271
  bodyHtml,
246
272
  aiClassification: email.aiClassificationJson,
247
273
  security: emailSecurity(email, identity, history, safety),
@@ -255,7 +281,8 @@ function toMessageDetail(
255
281
  email.direction === "incoming"
256
282
  ? storedSenderIntel(email.senderIntelJson)
257
283
  : null,
258
- hasOriginal: Boolean(email.rawMimeR2Key),
284
+ // "Show original" explains how received mail got here.
285
+ hasOriginal: email.direction === "incoming" && Boolean(email.rawMimeR2Key),
259
286
  attachments: email.attachmentsJson.map((file) => ({
260
287
  id: file.id,
261
288
  filename: file.filename,
@@ -265,14 +292,31 @@ function toMessageDetail(
265
292
  disposition: file.disposition,
266
293
  pdfPreviewStatus: file.pdfPreviewStatus ?? null,
267
294
  })),
268
- replyPlan: buildReplyPlan(ownAddress, email),
295
+ replyPlan: buildReplyPlan(ownAddresses, email),
269
296
  ...readReceipt,
270
297
  };
271
298
  }
272
299
 
273
- function conversationLabel(ownAddress: string, latest: Email) {
300
+ /**
301
+ * Who a row is with, by the latest message's people; those it names by
302
+ * address only take the names their own mail in the thread gave
303
+ * (`senderNames`).
304
+ */
305
+ function conversationLabel(
306
+ ownAddress: string,
307
+ latest: ListEmail,
308
+ senderNames: Record<string, string>
309
+ ) {
274
310
  const labels = participantLabels(
275
- [...latest.fromJson, ...latest.toJson, ...latest.ccJson],
311
+ [...latest.fromJson, ...latest.toJson, ...latest.ccJson].map(
312
+ (participant) => ({
313
+ address: participant.address,
314
+ name:
315
+ participant.name?.trim() ||
316
+ senderNames[participant.address.toLowerCase()] ||
317
+ null,
318
+ })
319
+ ),
276
320
  ownAddress
277
321
  );
278
322
 
@@ -301,17 +345,21 @@ function outboundTransportState(email: Email) {
301
345
  return email.transportState;
302
346
  }
303
347
 
348
+ /** Where permanently deleted conversations are: nowhere. */
349
+ function deletedPlaces(conversationIds: readonly string[]) {
350
+ return conversationIds.map((id) => ({
351
+ from: id,
352
+ conversationId: id,
353
+ folder: null,
354
+ left: true,
355
+ }));
356
+ }
357
+
304
358
  /** Keeps `work` running after the response; failures are only logged. */
305
- function runInBackground(c: Context<AppEnv>, work: Promise<unknown>) {
306
- const guarded = work.catch((error) =>
307
- console.error("Background work failed", error)
359
+ function runInBackground(work: Promise<unknown>) {
360
+ waitUntil(
361
+ work.catch((error) => console.error("Background work failed", error))
308
362
  );
309
-
310
- try {
311
- c.executionCtx.waitUntil(guarded);
312
- } catch {
313
- // No execution context (in-process calls): the promise still runs.
314
- }
315
363
  }
316
364
 
317
365
  function outgoingResponse(email: Email, detached: boolean) {
@@ -328,36 +376,90 @@ function outgoingResponse(email: Email, detached: boolean) {
328
376
  };
329
377
  }
330
378
 
331
- function outgoingFailure(c: Parameters<typeof apiError>[0], cause: unknown) {
379
+ /** The mail routes' `onError`: what sending and uploading refuse, else thrown on. */
380
+ const outgoingError: ErrorHandler<AppEnv> = (error, c) => {
381
+ if (error instanceof EmailSizeLimitError) {
382
+ return apiError(c, 413, "TOO_LARGE", error.message);
383
+ }
384
+
332
385
  if (
333
- cause instanceof ComposerAttachmentLimitError ||
334
- cause instanceof UploadValidationError
386
+ error instanceof ComposerAttachmentLimitError ||
387
+ error instanceof UploadValidationError
335
388
  ) {
336
- return apiError(c, 400, "BAD_REQUEST", cause.message);
389
+ return apiError(c, 400, "BAD_REQUEST", error.message);
337
390
  }
338
391
 
339
- if (cause instanceof OutgoingRequestConflictError) {
340
- return apiError(c, 409, "CONFLICT", cause.message);
392
+ if (error instanceof OutgoingRequestConflictError) {
393
+ return apiError(c, 409, "CONFLICT", error.message);
341
394
  }
342
395
 
343
- if (cause instanceof OutgoingContextError) {
344
- return apiError(c, cause.status, cause.code, cause.message);
396
+ if (error instanceof OutgoingContextError) {
397
+ return apiError(c, error.status, error.code, error.message);
345
398
  }
346
399
 
347
- throw cause;
400
+ throw error;
401
+ };
402
+
403
+ /** Sends what the request asks from its mailbox (`sendMessage`), answering as the send routes do. */
404
+ async function sendRoute(c: Context<AppEnv>, request: SendRequest) {
405
+ const access = await accessibleMailbox(c, request.message.mailboxId, "send");
406
+
407
+ if (!access) {
408
+ return apiError(c, 403, "FORBIDDEN", "Send access is required");
409
+ }
410
+
411
+ const sent = await sendMessage({
412
+ env: c.env,
413
+ requestUrl: c.req.url,
414
+ sender: c.get("user"),
415
+ mailbox: access,
416
+ request,
417
+ });
418
+
419
+ return c.json(
420
+ outgoingResponse(sent.email, sent.detached),
421
+ sent.inserted ? 201 : 200
422
+ );
348
423
  }
349
424
 
350
425
  /**
351
426
  * GET /mailboxes without `ok`. Each mailbox's `version` is the change
352
- * counter its `unreadCount` reflects; see `update:<version>`.
427
+ * counter its `unreadCount` reflects; see `update:<version>`. Whether this
428
+ * request may organize each one (capabilities.ts) is its `canOrganize`, so
429
+ * the app hides what the Worker would refuse.
353
430
  */
354
- export function mailboxListView(rows: MailboxListRow[]) {
431
+ export function mailboxListView(c: Context<AppEnv>, rows: MailboxListRow[]) {
355
432
  return {
356
433
  mailboxes: rows.map(
357
- ({ ownerUserId, isPrimary: _isPrimary, ...mailbox }) => ({
358
- ...mailbox,
359
- kind: mailboxKind(ownerUserId),
360
- })
434
+ ({
435
+ ownerUserId,
436
+ isPrimary: _isPrimary,
437
+ signatureUserId,
438
+ signatureMailboxId,
439
+ signatureHtml,
440
+ signatureUseOnNew,
441
+ signatureUseOnReply,
442
+ ...mailbox
443
+ }) => {
444
+ const signatureOwnerId = signatureUserId ?? signatureMailboxId;
445
+
446
+ return {
447
+ ...mailbox,
448
+ kind: mailboxKind(ownerUserId),
449
+ /** Its folders, rules and AI sorting (capabilities.ts). */
450
+ canOrganize: mayOrganizeMailbox(c, { ownerUserId }),
451
+ /** The signature sending from here adds (signatures.ts), if any. */
452
+ signature:
453
+ signatureOwnerId && signatureHtml !== null
454
+ ? {
455
+ ownerId: signatureOwnerId,
456
+ html: signatureHtml,
457
+ useOnNew: signatureUseOnNew ?? true,
458
+ useOnReply: signatureUseOnReply ?? true,
459
+ }
460
+ : null,
461
+ };
462
+ }
361
463
  ),
362
464
  };
363
465
  }
@@ -375,10 +477,69 @@ export function folderListView(view: ReturnType<MailboxDO["folderView"]>) {
375
477
  sortOrder: folder.sortOrder,
376
478
  totalCount: folder.totalCount,
377
479
  unreadCount: folder.unreadCount,
480
+ /** Days mail stays in Trash or Spam before it is deleted; null keeps it. */
481
+ retentionDays: isRetentionFolder(folder.systemType)
482
+ ? view.retention[folder.systemType]
483
+ : null,
378
484
  })),
379
485
  };
380
486
  }
381
487
 
488
+ const NO_DELIVERY_STATUSES: Email["deliveryStatusJson"] = [];
489
+
490
+ /**
491
+ * A Drafts folder row, in a conversation row's shape. A reply draft stands
492
+ * for its conversation, which the row opens; a new message or forward is its
493
+ * own row (`conversationId` is the draft's id) and opens the composer.
494
+ */
495
+ function draftRowView(
496
+ draft: ConversationPage["drafts"][number],
497
+ mailboxAddress: string
498
+ ) {
499
+ const conversationId =
500
+ draft.kind === "reply" && draft.conversationId
501
+ ? draft.conversationId
502
+ : draft.id;
503
+
504
+ const recipients =
505
+ draft.to.length || draft.cc.length ? [...draft.to, ...draft.cc] : draft.bcc;
506
+
507
+ const labels = participantLabels(
508
+ recipients.map((address) => ({ address, name: null })),
509
+ mailboxAddress
510
+ );
511
+
512
+ return {
513
+ id: draft.id,
514
+ conversationId,
515
+ direction: "outgoing" as const,
516
+ fromAddress: draft.sender?.address ?? mailboxAddress,
517
+ fromName: draft.sender?.displayName ?? null,
518
+ toAddresses: draft.to,
519
+ ccAddresses: draft.cc,
520
+ bccAddresses: draft.bcc,
521
+ replyToAddresses: draft.replyTo ? [draft.replyTo] : [],
522
+ subject: conversationSubject(draft.subject),
523
+ preview: draft.preview,
524
+ searchMatch: null,
525
+ transportState: null,
526
+ transportError: null,
527
+ deliveryStatuses: NO_DELIVERY_STATUSES,
528
+ timelineAt: draft.updatedAt,
529
+ senderLogoUrl: null,
530
+ conversationLabel: labels.length
531
+ ? labels.slice(0, 3).join(", ")
532
+ : (recipients[0] ?? "(no recipients)"),
533
+ messageCount: 1,
534
+ unreadCount: 0,
535
+ isUnread: false,
536
+ hasIncoming: false,
537
+ draft: true,
538
+ draftId: draft.id,
539
+ draftVersion: draft.version,
540
+ };
541
+ }
542
+
382
543
  /** GET /conversations without `ok`. */
383
544
  export function conversationPageView(
384
545
  page: NonNullable<ReturnType<MailboxDO["listConversations"]>>,
@@ -386,15 +547,31 @@ export function conversationPageView(
386
547
  ) {
387
548
  return {
388
549
  version: page.version,
389
- conversations: page.items.map((item) => ({
390
- ...toMessageSummary(item.email),
391
- subject: conversationSubject(item.email.subject),
392
- conversationLabel: conversationLabel(mailboxAddress, item.email),
393
- messageCount: item.messageCount,
394
- unreadCount: item.unreadCount,
395
- isUnread: item.unreadCount > 0,
396
- hasIncoming: item.hasIncoming,
397
- })),
550
+ conversations: [
551
+ ...page.items.map((item) => ({
552
+ ...toMessageSummary(item.email),
553
+ searchMatch: item.searchMatch,
554
+ subject: conversationSubject(item.email.subject),
555
+ conversationLabel: conversationLabel(
556
+ mailboxAddress,
557
+ item.email,
558
+ item.senderNames
559
+ ),
560
+ messageCount: item.messageCount,
561
+ unreadCount: item.unreadCount,
562
+ isUnread: item.unreadCount > 0,
563
+ hasIncoming: item.hasIncoming,
564
+ hasOutgoing: item.hasOutgoing,
565
+ mailboxState: item.mailboxState,
566
+ folderId: item.folderId,
567
+ /** The caller has a reply draft here; shown as "Draft". */
568
+ draft: item.hasDraft,
569
+ /** Set on Drafts folder rows only: the draft the row is. */
570
+ draftId: null,
571
+ draftVersion: null,
572
+ })),
573
+ ...page.drafts.map((draft) => draftRowView(draft, mailboxAddress)),
574
+ ],
398
575
  nextCursor: page.next ? encodeConversationCursor(page.next) : null,
399
576
  };
400
577
  }
@@ -404,7 +581,10 @@ export const mailRoutes = new Hono<AppEnv>()
404
581
  .get("/mailboxes", oauthScope(MAIL_READ_SCOPE), async (c) => {
405
582
  const rows = await accessibleMailboxes(c);
406
583
 
407
- return c.json({ ok: true as const, ...mailboxListView(rows) });
584
+ return c.json({
585
+ ok: true as const,
586
+ ...mailboxListView(c, rows),
587
+ });
408
588
  })
409
589
  .get("/mailboxes/:id/realtime", oauthScope(MAIL_READ_SCOPE), async (c) => {
410
590
  if (c.get("authKind") !== "session") {
@@ -434,6 +614,8 @@ export const mailRoutes = new Hono<AppEnv>()
434
614
  }
435
615
 
436
616
  const headers = new Headers(c.req.raw.headers);
617
+ // Only the Worker's JMAP stream may ask for a socket nothing re-checks.
618
+ headers.delete("x-openworkspace-jmap");
437
619
  headers.set("x-openworkspace-user-id", user.id);
438
620
  headers.set("x-openworkspace-session-id", c.get("sessionId"));
439
621
  headers.set(
@@ -475,20 +657,16 @@ export const mailRoutes = new Hono<AppEnv>()
475
657
  return apiError(c, 429, "RATE_LIMITED", "Too many attachment uploads");
476
658
  }
477
659
 
478
- try {
479
- const upload = await createComposerUploadIntent({
480
- env: c.env,
481
- mailboxId,
482
- userId: user.id,
483
- filename: body.filename,
484
- contentType: body.contentType,
485
- size: body.size,
486
- });
660
+ const upload = await createComposerUploadIntent({
661
+ env: c.env,
662
+ mailboxId,
663
+ userId: user.id,
664
+ filename: body.filename,
665
+ contentType: body.contentType,
666
+ size: body.size,
667
+ });
487
668
 
488
- return c.json({ ok: true as const, upload }, 201);
489
- } catch (error) {
490
- return outgoingFailure(c, error);
491
- }
669
+ return c.json({ ok: true as const, upload }, 201);
492
670
  }
493
671
  )
494
672
  .post(
@@ -506,19 +684,14 @@ export const mailRoutes = new Hono<AppEnv>()
506
684
  return apiError(c, 403, "FORBIDDEN", "Send access is required");
507
685
  }
508
686
 
509
- try {
510
- const upload = await finalizeComposerUpload({
511
- env: c.env,
512
- mailboxId,
513
- userId: user.id,
514
- uploadId,
515
- defer: (task) => c.executionCtx.waitUntil(task),
516
- });
687
+ const upload = await finalizeComposerUpload({
688
+ env: c.env,
689
+ mailboxId,
690
+ userId: user.id,
691
+ uploadId,
692
+ });
517
693
 
518
- return c.json({ ok: true as const, upload });
519
- } catch (error) {
520
- return outgoingFailure(c, error);
521
- }
694
+ return c.json({ ok: true as const, upload });
522
695
  }
523
696
  )
524
697
  .delete(
@@ -603,9 +776,9 @@ export const mailRoutes = new Hono<AppEnv>()
603
776
  async (c) => {
604
777
  const mailboxId = c.req.param("id");
605
778
 
606
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
607
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
608
- }
779
+ const refused = await organizeRefusal(c, mailboxId);
780
+
781
+ if (refused) return refused;
609
782
 
610
783
  return c.json({
611
784
  ok: true as const,
@@ -615,10 +788,58 @@ export const mailRoutes = new Hono<AppEnv>()
615
788
  });
616
789
  }
617
790
  )
791
+ // Rules are mailbox organization, like folders and AI sorting.
792
+ .get("/mailboxes/:id/rules", oauthScope(MAIL_READ_SCOPE), async (c) => {
793
+ const mailboxId = c.req.param("id");
794
+
795
+ const access = await accessibleMailbox(c, mailboxId, "read");
796
+
797
+ if (!access) {
798
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
799
+ }
800
+
801
+ return c.json({
802
+ ok: true as const,
803
+ /** Whether the signed-in person may change them (capabilities.ts). */
804
+ canEdit: mayOrganizeMailbox(c, access),
805
+ rules: await mailboxStub(c.env, mailboxId).listRules(),
806
+ });
807
+ })
618
808
  .post(
619
- "/mailboxes/:id/folders",
809
+ "/mailboxes/:id/rules",
620
810
  oauthScope(MAIL_ORGANIZE_SCOPE),
621
- zValidator("json", createFolderSchema),
811
+ zValidator("json", ruleInputSchema),
812
+ async (c) => {
813
+ const mailboxId = c.req.param("id");
814
+
815
+ const refused = await organizeRefusal(c, mailboxId);
816
+
817
+ if (refused) return refused;
818
+
819
+ const result = await mailboxStub(c.env, mailboxId).createRule(
820
+ c.req.valid("json")
821
+ );
822
+
823
+ if (result.status === "invalid") {
824
+ return apiError(c, 400, "BAD_REQUEST", result.error);
825
+ }
826
+
827
+ if (result.status === "limit") {
828
+ return apiError(
829
+ c,
830
+ 409,
831
+ "CONFLICT",
832
+ "A mailbox can have at most 100 rules"
833
+ );
834
+ }
835
+
836
+ return c.json({ ok: true as const, rule: result.rule }, 201);
837
+ }
838
+ )
839
+ .post(
840
+ "/mailboxes/:id/rules/test",
841
+ oauthScope(MAIL_READ_SCOPE),
842
+ zValidator("json", ruleTestSchema),
622
843
  async (c) => {
623
844
  const mailboxId = c.req.param("id");
624
845
 
@@ -626,6 +847,151 @@ export const mailRoutes = new Hono<AppEnv>()
626
847
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
627
848
  }
628
849
 
850
+ return c.json({
851
+ ok: true as const,
852
+ ...(await mailboxStub(c.env, mailboxId).testRule(c.req.valid("json"))),
853
+ });
854
+ }
855
+ )
856
+ .put(
857
+ "/mailboxes/:id/rules/order",
858
+ oauthScope(MAIL_ORGANIZE_SCOPE),
859
+ zValidator(
860
+ "json",
861
+ z.object({ ruleIds: z.array(z.string().min(1).max(80)).max(100) })
862
+ ),
863
+ async (c) => {
864
+ const mailboxId = c.req.param("id");
865
+
866
+ const refused = await organizeRefusal(c, mailboxId);
867
+
868
+ if (refused) return refused;
869
+
870
+ if (
871
+ !(await mailboxStub(c.env, mailboxId).reorderRules(
872
+ c.req.valid("json").ruleIds
873
+ ))
874
+ ) {
875
+ return apiError(
876
+ c,
877
+ 409,
878
+ "CONFLICT",
879
+ "Rules changed; refresh and try again"
880
+ );
881
+ }
882
+
883
+ return c.json({ ok: true as const });
884
+ }
885
+ )
886
+ .patch(
887
+ "/mailboxes/:id/rules/:ruleId",
888
+ oauthScope(MAIL_ORGANIZE_SCOPE),
889
+ zValidator("json", z.object({ enabled: z.boolean() })),
890
+ async (c) => {
891
+ const mailboxId = c.req.param("id");
892
+ const refused = await organizeRefusal(c, mailboxId);
893
+
894
+ if (refused) return refused;
895
+
896
+ const updated = await mailboxStub(c.env, mailboxId).setRuleEnabled(
897
+ c.req.param("ruleId"),
898
+ c.req.valid("json").enabled
899
+ );
900
+
901
+ if (!updated) return apiError(c, 404, "NOT_FOUND", "Rule not found");
902
+
903
+ return c.json({ ok: true as const });
904
+ }
905
+ )
906
+ .put(
907
+ "/mailboxes/:id/rules/:ruleId",
908
+ oauthScope(MAIL_ORGANIZE_SCOPE),
909
+ zValidator("json", ruleInputSchema.omit({ enabled: true }).strict()),
910
+ async (c) => {
911
+ const mailboxId = c.req.param("id");
912
+
913
+ const refused = await organizeRefusal(c, mailboxId);
914
+
915
+ if (refused) return refused;
916
+
917
+ const result = await mailboxStub(c.env, mailboxId).updateRule(
918
+ c.req.param("ruleId"),
919
+ c.req.valid("json")
920
+ );
921
+
922
+ if (result.status === "invalid") {
923
+ return apiError(c, 400, "BAD_REQUEST", result.error);
924
+ }
925
+
926
+ if (result.status === "not_found") {
927
+ return apiError(c, 404, "NOT_FOUND", "Rule not found");
928
+ }
929
+
930
+ return c.json({ ok: true as const, rule: result.rule });
931
+ }
932
+ )
933
+ .delete(
934
+ "/mailboxes/:id/rules/:ruleId",
935
+ oauthScope(MAIL_ORGANIZE_SCOPE),
936
+ async (c) => {
937
+ const mailboxId = c.req.param("id");
938
+
939
+ const refused = await organizeRefusal(c, mailboxId);
940
+
941
+ if (refused) return refused;
942
+
943
+ if (
944
+ !(await mailboxStub(c.env, mailboxId).deleteRule(c.req.param("ruleId")))
945
+ ) {
946
+ return apiError(c, 404, "NOT_FOUND", "Rule not found");
947
+ }
948
+
949
+ return c.json({ ok: true as const });
950
+ }
951
+ )
952
+ .post(
953
+ "/mailboxes/:id/folders/:folder/empty",
954
+ oauthScope(MAIL_ORGANIZE_SCOPE),
955
+ zValidator(
956
+ "param",
957
+ z.object({ id: z.string(), folder: retentionFolderSchema })
958
+ ),
959
+ async (c) => {
960
+ const { id: mailboxId, folder } = c.req.valid("param");
961
+
962
+ if (!(await accessibleMailbox(c, mailboxId, "send"))) {
963
+ return apiError(
964
+ c,
965
+ 403,
966
+ "FORBIDDEN",
967
+ "Send access is required to delete conversations permanently"
968
+ );
969
+ }
970
+
971
+ const { deletedIds, remaining } = await mailboxStub(
972
+ c.env,
973
+ mailboxId
974
+ ).emptyFolder(folder);
975
+
976
+ return c.json({
977
+ ok: true as const,
978
+ deleted: deletedIds.length,
979
+ remaining,
980
+ places: deletedPlaces(deletedIds),
981
+ });
982
+ }
983
+ )
984
+ .post(
985
+ "/mailboxes/:id/folders",
986
+ oauthScope(MAIL_ORGANIZE_SCOPE),
987
+ zValidator("json", createFolderSchema),
988
+ async (c) => {
989
+ const mailboxId = c.req.param("id");
990
+
991
+ const refused = await organizeRefusal(c, mailboxId);
992
+
993
+ if (refused) return refused;
994
+
629
995
  const result = await mailboxStub(c.env, mailboxId).createFolder(
630
996
  createId("fld"),
631
997
  c.req.valid("json").name
@@ -653,9 +1019,9 @@ export const mailRoutes = new Hono<AppEnv>()
653
1019
  async (c) => {
654
1020
  const mailboxId = c.req.param("id");
655
1021
 
656
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
657
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
658
- }
1022
+ const refused = await organizeRefusal(c, mailboxId);
1023
+
1024
+ if (refused) return refused;
659
1025
 
660
1026
  const result = await mailboxStub(c.env, mailboxId).reorderFolders(
661
1027
  c.req.valid("json").folderIds
@@ -680,9 +1046,9 @@ export const mailRoutes = new Hono<AppEnv>()
680
1046
  async (c) => {
681
1047
  const mailboxId = c.req.param("id");
682
1048
 
683
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
684
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
685
- }
1049
+ const refused = await organizeRefusal(c, mailboxId);
1050
+
1051
+ if (refused) return refused;
686
1052
 
687
1053
  const result = await mailboxStub(c.env, mailboxId).renameFolder(
688
1054
  c.req.param("folderId"),
@@ -710,9 +1076,9 @@ export const mailRoutes = new Hono<AppEnv>()
710
1076
  async (c) => {
711
1077
  const mailboxId = c.req.param("id");
712
1078
 
713
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
714
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
715
- }
1079
+ const refused = await organizeRefusal(c, mailboxId);
1080
+
1081
+ if (refused) return refused;
716
1082
 
717
1083
  const result = await mailboxStub(c.env, mailboxId).deleteFolder(
718
1084
  c.req.param("folderId")
@@ -750,6 +1116,11 @@ export const mailRoutes = new Hono<AppEnv>()
750
1116
  );
751
1117
  }
752
1118
 
1119
+ const senders =
1120
+ query.folder === DRAFTS_FOLDER_ID
1121
+ ? await mailboxDraftSenders(c.env.DB, access)
1122
+ : undefined;
1123
+
753
1124
  const page = await timed(c, "do", "conversations", () =>
754
1125
  mailboxStub(c.env, query.mailboxId).listConversations(
755
1126
  c.get("user").id,
@@ -757,7 +1128,8 @@ export const mailRoutes = new Hono<AppEnv>()
757
1128
  query.limit,
758
1129
  cursor,
759
1130
  query.search,
760
- query.unreadOnly === "true"
1131
+ query.unreadOnly === "true",
1132
+ senders
761
1133
  )
762
1134
  );
763
1135
 
@@ -769,6 +1141,38 @@ export const mailRoutes = new Hono<AppEnv>()
769
1141
  });
770
1142
  }
771
1143
  )
1144
+ .post(
1145
+ "/conversations/undo-spam",
1146
+ oauthScope(MAIL_ORGANIZE_SCOPE),
1147
+ zValidator("query", mailboxQuerySchema),
1148
+ zValidator(
1149
+ "json",
1150
+ z.object({ undoId: z.string().regex(/^undo_[\da-f]{32}$/u) })
1151
+ ),
1152
+ async (c) => {
1153
+ const { mailboxId } = c.req.valid("query");
1154
+
1155
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) {
1156
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1157
+ }
1158
+
1159
+ const restored = await mailboxStub(c.env, mailboxId).undoSpamDecision(
1160
+ c.get("user").id,
1161
+ c.req.valid("json").undoId
1162
+ );
1163
+
1164
+ if (!restored) {
1165
+ return apiError(
1166
+ c,
1167
+ 409,
1168
+ "CONFLICT",
1169
+ "Could not undo this spam decision. The mail or sender changed, or Undo expired."
1170
+ );
1171
+ }
1172
+
1173
+ return c.json({ ok: true as const });
1174
+ }
1175
+ )
772
1176
  .patch(
773
1177
  "/conversations/bulk",
774
1178
  oauthScope(MAIL_ORGANIZE_SCOPE),
@@ -793,17 +1197,28 @@ export const mailRoutes = new Hono<AppEnv>()
793
1197
  input.isRead
794
1198
  );
795
1199
 
796
- return c.json({ ok: true as const, updatedCount });
1200
+ // Marked read or unread, they stay where they are.
1201
+ return c.json({ ok: true as const, updatedCount, places: [] });
797
1202
  }
798
1203
 
799
1204
  if (input.type === "update") {
800
- const updatedCount = await stub.bulkUpdateConversations(
1205
+ const placed = await stub.bulkUpdateConversations(
801
1206
  input.conversationIds,
802
1207
  input.sourceFolderId,
803
- input.update
1208
+ input.update,
1209
+ // Out of Spam it is a verdict for anyone who reads the mailbox;
1210
+ // trusting its senders, only for those who may organize it. An
1211
+ // Undo only puts them back: no verdict, nobody trusted.
1212
+ input.undo
1213
+ ? { userId: null, trustSenders: false, undo: true }
1214
+ : {
1215
+ userId: user.id,
1216
+ trustSenders: mayOrganizeMailbox(c, access),
1217
+ offerUndo: input.offerUndo,
1218
+ }
804
1219
  );
805
1220
 
806
- if (updatedCount === null) {
1221
+ if (placed === null) {
807
1222
  return apiError(
808
1223
  c,
809
1224
  404,
@@ -812,7 +1227,17 @@ export const mailRoutes = new Hono<AppEnv>()
812
1227
  );
813
1228
  }
814
1229
 
815
- return c.json({ ok: true as const, updatedCount });
1230
+ if (!placed.undoId) {
1231
+ await shareSpamVerdicts(c.env.DB, mailboxId, placed.verdicts);
1232
+ }
1233
+
1234
+ return c.json({
1235
+ ok: true as const,
1236
+ updatedCount: placed.moved.length,
1237
+ undoId: placed.undoId ?? undefined,
1238
+ /** Where each conversation is now, and whether it left where it was. */
1239
+ places: placed.places,
1240
+ });
816
1241
  }
817
1242
 
818
1243
  if (!access.canSend) {
@@ -824,26 +1249,15 @@ export const mailRoutes = new Hono<AppEnv>()
824
1249
  );
825
1250
  }
826
1251
 
1252
+ // Those still in Trash go; the person hears how many.
827
1253
  const result = await stub.permanentlyDeleteConversations(
828
1254
  input.conversationIds
829
1255
  );
830
1256
 
831
- if (result.outcome === "not_found") {
832
- return apiError(c, 404, "NOT_FOUND", "Conversations not found");
833
- }
834
-
835
- if (result.outcome === "not_in_trash") {
836
- return apiError(
837
- c,
838
- 409,
839
- "CONFLICT",
840
- "Only conversations in Trash can be deleted permanently"
841
- );
842
- }
843
-
844
1257
  return c.json({
845
1258
  ok: true as const,
846
- updatedCount: result.deletedCount,
1259
+ updatedCount: result.deletedIds.length,
1260
+ places: deletedPlaces(result.deletedIds),
847
1261
  });
848
1262
  }
849
1263
  )
@@ -887,7 +1301,9 @@ export const mailRoutes = new Hono<AppEnv>()
887
1301
  c.req.param("id"),
888
1302
  currentUserId,
889
1303
  query.limit,
890
- cursor
1304
+ cursor,
1305
+ c.get("authKind") === "session" && access.canSend,
1306
+ query.match
891
1307
  )
892
1308
  );
893
1309
 
@@ -898,21 +1314,23 @@ export const mailRoutes = new Hono<AppEnv>()
898
1314
  ...new Set(view.readStates.map((readState) => readState.userId)),
899
1315
  ].filter((userId) => userId !== currentUserId);
900
1316
 
901
- const [readers, [identity, workspaceBlocks], bodies] = await Promise.all([
902
- otherReaderIds.length
903
- ? timed(c, "d1", "readers", () =>
904
- listMailboxUsersByIds(c.env.DB, mailboxId, otherReaderIds)
1317
+ const [readers, [identity, workspaceBlocks], bodies, aliases] =
1318
+ await Promise.all([
1319
+ otherReaderIds.length
1320
+ ? timed(c, "d1", "readers", () =>
1321
+ listMailboxUsersByIds(c.env.DB, mailboxId, otherReaderIds)
1322
+ )
1323
+ : [],
1324
+ workspace,
1325
+ Promise.all(
1326
+ view.messages.map((stored) =>
1327
+ stored.bodyHtmlR2Key
1328
+ ? readStoredBody(c, stored.bodyHtmlR2Key)
1329
+ : null
905
1330
  )
906
- : [],
907
- workspace,
908
- Promise.all(
909
- view.messages.map((stored) =>
910
- stored.bodyHtmlR2Key
911
- ? readStoredBody(c, stored.bodyHtmlR2Key)
912
- : null
913
- )
914
- ),
915
- ]);
1331
+ ),
1332
+ timed(c, "d1", "aliases", () => mailboxAliases(c.env.DB, mailboxId)),
1333
+ ]);
916
1334
 
917
1335
  /** One proxy token per remote image URL in the HTML (remote-token.ts). */
918
1336
  const remoteTokens = async (bodyHtml: string) =>
@@ -960,6 +1378,11 @@ export const mailRoutes = new Hono<AppEnv>()
960
1378
  const inline = c.get("authKind") !== "session";
961
1379
  const now = Date.now();
962
1380
 
1381
+ const ownAddresses = [
1382
+ access.address,
1383
+ ...aliases.map((alias) => alias.address),
1384
+ ];
1385
+
963
1386
  const messages = await Promise.all(
964
1387
  view.messages.map(async (stored, index) => {
965
1388
  const bodyHtml = bodies[index] ?? null;
@@ -974,7 +1397,6 @@ export const mailRoutes = new Hono<AppEnv>()
974
1397
  } else {
975
1398
  intelPending = true;
976
1399
  runInBackground(
977
- c,
978
1400
  withSenderIntel(c.env, mailbox, stored, intelContext(bodyHtml))
979
1401
  );
980
1402
  }
@@ -985,15 +1407,18 @@ export const mailRoutes = new Hono<AppEnv>()
985
1407
  return {
986
1408
  ...toMessageDetail(
987
1409
  email,
988
- access.address,
1410
+ ownAddresses,
989
1411
  identity,
990
1412
  view.history,
991
1413
  safety,
992
1414
  bodyHtml,
993
1415
  {
994
- isRead: readStates.some(
995
- (readState) => readState.userId === currentUserId
996
- ),
1416
+ isRead:
1417
+ (email.direction === "outgoing" &&
1418
+ access.kind === "personal") ||
1419
+ readStates.some(
1420
+ (readState) => readState.userId === currentUserId
1421
+ ),
997
1422
  viewedBy: readStates.flatMap((readState) => {
998
1423
  const reader = readerById.get(readState.userId);
999
1424
 
@@ -1024,13 +1449,25 @@ export const mailRoutes = new Hono<AppEnv>()
1024
1449
  })
1025
1450
  );
1026
1451
 
1452
+ const source = view.replyDraftSource;
1453
+
1454
+ const replyDraftSource = source && {
1455
+ ...messagePreview(source),
1456
+ security: emailSecurity(source, identity, view.history, safety),
1457
+ replyPlan: buildReplyPlan(ownAddresses, source),
1458
+ };
1459
+
1027
1460
  return c.json({
1028
1461
  ok: true as const,
1029
1462
  version: view.version,
1463
+ replyDraftSource,
1464
+ pinnedMessageId: view.pinnedMessageId,
1465
+ replyDraft: view.replyDraft ? draftView(view.replyDraft) : null,
1030
1466
  mailboxState: view.mailboxState,
1031
1467
  folderId: view.folderId,
1032
1468
  hasIncoming: view.hasIncoming,
1033
1469
  hasOutgoing: view.hasOutgoing,
1470
+ translationEnabled: aiFeatureEnabled("translation"),
1034
1471
  messageCount: view.messageCount,
1035
1472
  unreadCount: view.unreadCount,
1036
1473
  nextCursor: view.next ? encodeConversationCursor(view.next) : null,
@@ -1038,6 +1475,49 @@ export const mailRoutes = new Hono<AppEnv>()
1038
1475
  });
1039
1476
  }
1040
1477
  )
1478
+ .get(
1479
+ "/messages/:id/forward-source",
1480
+ oauthScope(MAIL_READ_SCOPE),
1481
+ zValidator("query", mailboxQuerySchema),
1482
+ async (c) => {
1483
+ const { mailboxId } = c.req.valid("query");
1484
+
1485
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) {
1486
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1487
+ }
1488
+
1489
+ const view = await mailboxStub(c.env, mailboxId).getMessageSenderView(
1490
+ c.req.param("id")
1491
+ );
1492
+
1493
+ if (!view) {
1494
+ return apiError(c, 404, "NOT_FOUND", "Forwarded message not found");
1495
+ }
1496
+
1497
+ const { email } = view;
1498
+
1499
+ const [identity, workspaceBlocks] = await Promise.all([
1500
+ cachedWorkspaceIdentity(c.env.DB),
1501
+ cachedWorkspaceBlockPatterns(c.env.DB),
1502
+ ]);
1503
+
1504
+ return c.json({
1505
+ ok: true as const,
1506
+ message: {
1507
+ ...messagePreview(email),
1508
+ attachments: email.attachmentsJson.map(({ id, filename, size }) => ({
1509
+ id,
1510
+ filename,
1511
+ size,
1512
+ })),
1513
+ security: emailSecurity(email, identity, view.history, {
1514
+ ...view.safety,
1515
+ workspaceBlocks,
1516
+ }),
1517
+ },
1518
+ });
1519
+ }
1520
+ )
1041
1521
  .get(
1042
1522
  "/messages/:id/sender-intel",
1043
1523
  oauthScope(MAIL_READ_SCOPE),
@@ -1111,21 +1591,27 @@ export const mailRoutes = new Hono<AppEnv>()
1111
1591
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1112
1592
  }
1113
1593
 
1114
- const version = await timed(c, "do", "read", async () => {
1115
- const updated = await mailboxStub(c.env, mailboxId).setMessageRead(
1594
+ const updated = await timed(c, "do", "read", async () => {
1595
+ const result = await mailboxStub(c.env, mailboxId).setMessageRead(
1116
1596
  user.id,
1117
1597
  c.req.param("id"),
1118
1598
  c.req.valid("json").isRead
1119
1599
  );
1120
1600
 
1121
- return updated ? updated.version : null;
1601
+ return result
1602
+ ? { previousVersion: result.previousVersion, version: result.version }
1603
+ : null;
1122
1604
  });
1123
1605
 
1124
- if (version === null) {
1606
+ if (!updated) {
1125
1607
  return apiError(c, 404, "NOT_FOUND", "Message not found");
1126
1608
  }
1127
1609
 
1128
- return c.json({ ok: true as const, version });
1610
+ return c.json({
1611
+ ok: true as const,
1612
+ previousVersion: updated.previousVersion,
1613
+ version: updated.version,
1614
+ });
1129
1615
  }
1130
1616
  )
1131
1617
  .post(
@@ -1282,11 +1768,10 @@ export const mailRoutes = new Hono<AppEnv>()
1282
1768
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1283
1769
  }
1284
1770
 
1285
- const message = await mailboxStub(c.env, mailboxId).getEmail(
1286
- c.req.param("messageId")
1287
- );
1771
+ const messageId = c.req.param("messageId");
1772
+ const key = await mailboxStub(c.env, mailboxId).getRawMimeKey(messageId);
1288
1773
 
1289
- if (!message?.rawMimeR2Key) {
1774
+ if (!key) {
1290
1775
  return apiError(c, 404, "NOT_FOUND", "Original message not found");
1291
1776
  }
1292
1777
 
@@ -1294,7 +1779,7 @@ export const mailRoutes = new Hono<AppEnv>()
1294
1779
 
1295
1780
  const object = await getStoredObject(
1296
1781
  c.env.MAIL_STORAGE,
1297
- message.rawMimeR2Key,
1782
+ key,
1298
1783
  requestedRange
1299
1784
  );
1300
1785
 
@@ -1304,7 +1789,7 @@ export const mailRoutes = new Hono<AppEnv>()
1304
1789
 
1305
1790
  return storedObjectResponse({
1306
1791
  object,
1307
- contentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(`${message.id}.eml`)}`,
1792
+ contentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(`${messageId}.eml`)}`,
1308
1793
  contentType: "text/plain; charset=utf-8",
1309
1794
  totalBytes: object.size,
1310
1795
  rangeRequested: Boolean(requestedRange),
@@ -1519,7 +2004,7 @@ export const mailRoutes = new Hono<AppEnv>()
1519
2004
  return apiError(c, 404, "NOT_FOUND", "Outgoing message not found");
1520
2005
  }
1521
2006
 
1522
- const resent = await stub.resendOutgoing(message.id);
2007
+ const resent = await stub.resendOutgoing(message.id, c.req.url);
1523
2008
 
1524
2009
  if (!resent) {
1525
2010
  return apiError(
@@ -1534,7 +2019,6 @@ export const mailRoutes = new Hono<AppEnv>()
1534
2019
  env: c.env,
1535
2020
  mailboxId,
1536
2021
  email: resent,
1537
- defer: (task) => c.executionCtx.waitUntil(task),
1538
2022
  });
1539
2023
 
1540
2024
  return c.json({
@@ -1569,195 +2053,105 @@ export const mailRoutes = new Hono<AppEnv>()
1569
2053
  return apiError(c, 429, "RATE_LIMITED", "Too many attachment checks");
1570
2054
  }
1571
2055
 
1572
- try {
1573
- let subject = input.kind === "compose" ? input.subject : "";
1574
- let related: Email | null = null;
1575
- let forwarded: Email | null = null;
1576
- let includeRelatedContext = false;
1577
-
1578
- if (input.kind === "forward") {
1579
- const context = await resolveForwardContext({
1580
- env: c.env,
1581
- mailboxId: input.mailboxId,
1582
- sourceEmailId: input.sourceEmailId,
1583
- });
1584
-
1585
- forwarded = context.source;
1586
- subject = context.subject;
1587
- } else if (input.kind === "reply") {
1588
- const context = await resolveReplyContext({
1589
- env: c.env,
1590
- mailboxId: input.mailboxId,
1591
- ownAddress: access.address,
1592
- sourceEmailId: input.sourceEmailId,
1593
- mode: input.mode,
1594
- cc: input.cc,
1595
- bcc: input.bcc,
1596
- });
1597
-
1598
- related = context.source;
1599
- subject = context.subject;
1600
- includeRelatedContext = context.includeRelatedContext;
1601
- }
2056
+ let subject = input.kind === "compose" ? input.subject : "";
2057
+ let related: Email | null = null;
2058
+ let forwarded: Email | null = null;
2059
+ let includeRelatedContext = false;
1602
2060
 
1603
- const result = await preflightOutgoingAttachments({
2061
+ if (input.kind === "forward") {
2062
+ const context = await resolveForwardContext({
1604
2063
  env: c.env,
1605
- compose: {
1606
- mailboxId: input.mailboxId,
1607
- userId: user.id,
1608
- subject,
1609
- bodyText: input.bodyText,
1610
- bodyHtml: input.bodyHtml,
1611
- attachments: input.attachments,
1612
- },
1613
- related,
1614
- forwarded,
1615
- includeRelatedContext,
2064
+ mailboxId: input.mailboxId,
2065
+ sourceEmailId: input.sourceEmailId,
2066
+ });
2067
+
2068
+ forwarded = context.source;
2069
+ subject = context.subject;
2070
+ } else if (input.kind === "reply") {
2071
+ const context = await resolveReplyContext({
2072
+ env: c.env,
2073
+ mailboxId: input.mailboxId,
2074
+ ownAddress: access.address,
2075
+ sourceEmailId: input.sourceEmailId,
2076
+ mode: input.mode,
2077
+ cc: input.cc,
2078
+ bcc: input.bcc,
1616
2079
  });
1617
2080
 
1618
- return c.json({ ok: true as const, ...result });
1619
- } catch (error) {
1620
- return outgoingFailure(c, error);
2081
+ related = context.source;
2082
+ subject = context.subject;
2083
+ includeRelatedContext = context.includeRelatedContext;
1621
2084
  }
2085
+
2086
+ const message = await withSignature({
2087
+ env: c.env,
2088
+ sender: user,
2089
+ mailbox: access,
2090
+ kind: input.kind === "compose" ? "new" : "reply",
2091
+ message: input,
2092
+ });
2093
+
2094
+ const result = await preflightOutgoingAttachments({
2095
+ env: c.env,
2096
+ compose: {
2097
+ mailboxId: input.mailboxId,
2098
+ userId: user.id,
2099
+ subject,
2100
+ bodyText: message.bodyText,
2101
+ bodyHtml: message.bodyHtml,
2102
+ inlineImages: message.inlineImages,
2103
+ attachments: message.attachments,
2104
+ forwardedAttachmentIds:
2105
+ input.kind === "forward" ? input.forwardedAttachmentIds : undefined,
2106
+ },
2107
+ related,
2108
+ forwarded,
2109
+ includeRelatedContext,
2110
+ });
2111
+
2112
+ return c.json({ ok: true as const, ...result });
1622
2113
  }
1623
2114
  )
1624
2115
  .post(
1625
2116
  "/messages",
1626
2117
  oauthScope(MAIL_SEND_SCOPE),
1627
2118
  zValidator("json", composeSchema),
1628
- async (c) => {
1629
- const input = c.req.valid("json");
1630
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1631
-
1632
- if (!access) {
1633
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1634
- }
1635
-
1636
- try {
1637
- const submission = await submitOutgoing({
1638
- env: c.env,
1639
- requestUrl: c.req.url,
1640
- compose: {
1641
- ...input,
1642
- userId: c.get("user").id,
1643
- },
1644
- conversationId: createId("conv"),
1645
- related: null,
1646
- forwarded: null,
1647
- includeRelatedContext: false,
1648
- fromAddress: access.address,
1649
- fromName: access.displayName,
1650
- defer: (task) => c.executionCtx.waitUntil(task),
1651
- });
2119
+ (c) => {
2120
+ const message = c.req.valid("json");
1652
2121
 
1653
- return c.json(
1654
- outgoingResponse(submission.email, false),
1655
- submission.inserted ? 201 : 200
1656
- );
1657
- } catch (error) {
1658
- return outgoingFailure(c, error);
1659
- }
2122
+ return sendRoute(c, { kind: "new", message });
1660
2123
  }
1661
2124
  )
1662
2125
  .post(
1663
2126
  "/messages/:id/replies",
1664
2127
  oauthScope(MAIL_SEND_SCOPE),
1665
2128
  zValidator("json", replySchema),
1666
- async (c) => {
1667
- const input = c.req.valid("json");
1668
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1669
-
1670
- if (!access) {
1671
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1672
- }
1673
-
1674
- try {
1675
- const context = await resolveReplyContext({
1676
- env: c.env,
1677
- mailboxId: input.mailboxId,
1678
- ownAddress: access.address,
1679
- sourceEmailId: c.req.param("id"),
1680
- mode: input.mode,
1681
- cc: input.cc,
1682
- bcc: input.bcc,
1683
- });
1684
-
1685
- const submission = await submitOutgoing({
1686
- env: c.env,
1687
- requestUrl: c.req.url,
1688
- compose: {
1689
- requestId: input.requestId,
1690
- mailboxId: input.mailboxId,
1691
- userId: c.get("user").id,
1692
- ...context.recipients,
1693
- subject: context.subject,
1694
- bodyText: input.bodyText,
1695
- bodyHtml: input.bodyHtml,
1696
- attachments: input.attachments,
1697
- },
1698
- conversationId: context.detached
1699
- ? createId("conv")
1700
- : context.source.conversationId,
1701
- related: context.source,
1702
- forwarded: null,
1703
- includeRelatedContext: context.includeRelatedContext,
1704
- fromAddress: access.address,
1705
- fromName: access.displayName,
1706
- defer: (task) => c.executionCtx.waitUntil(task),
1707
- });
2129
+ (c) => {
2130
+ const message = c.req.valid("json");
1708
2131
 
1709
- return c.json(
1710
- outgoingResponse(submission.email, context.detached),
1711
- submission.inserted ? 201 : 200
1712
- );
1713
- } catch (error) {
1714
- return outgoingFailure(c, error);
1715
- }
2132
+ return sendRoute(c, {
2133
+ kind: "reply",
2134
+ sourceEmailId: c.req.param("id"),
2135
+ message,
2136
+ });
1716
2137
  }
1717
2138
  )
1718
2139
  .post(
1719
2140
  "/messages/:id/forward",
1720
2141
  oauthScope(MAIL_SEND_SCOPE),
1721
2142
  zValidator("json", forwardSchema),
1722
- async (c) => {
1723
- const input = c.req.valid("json");
1724
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1725
-
1726
- if (!access) {
1727
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1728
- }
2143
+ (c) => {
2144
+ const message = c.req.valid("json");
1729
2145
 
1730
- try {
1731
- const context = await resolveForwardContext({
1732
- env: c.env,
1733
- mailboxId: input.mailboxId,
1734
- sourceEmailId: c.req.param("id"),
1735
- });
1736
-
1737
- const submission = await submitOutgoing({
1738
- env: c.env,
1739
- requestUrl: c.req.url,
1740
- compose: {
1741
- ...input,
1742
- userId: c.get("user").id,
1743
- subject: context.subject,
1744
- },
1745
- conversationId: createId("conv"),
1746
- related: null,
1747
- forwarded: context.source,
1748
- includeRelatedContext: false,
1749
- fromAddress: access.address,
1750
- fromName: access.displayName,
1751
- defer: (task) => c.executionCtx.waitUntil(task),
1752
- });
1753
-
1754
- return c.json(
1755
- outgoingResponse(submission.email, false),
1756
- submission.inserted ? 201 : 200
1757
- );
1758
- } catch (error) {
1759
- return outgoingFailure(c, error);
1760
- }
2146
+ return sendRoute(c, {
2147
+ kind: "forward",
2148
+ sourceEmailId: c.req.param("id"),
2149
+ message,
2150
+ });
1761
2151
  }
1762
2152
  )
1763
- .route("/", mailSafetyRoutes);
2153
+ .route("/drafts", mailDraftRoutes)
2154
+ .route("/", mailSafetyRoutes)
2155
+ .route("/", signatureRoutes)
2156
+ .route("/", autoReplyRoutes)
2157
+ .onError(outgoingError);