@open-workspace/email 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,898 @@
1
+ import { zodResolver } from "@hookform/resolvers/zod";
2
+ import {
3
+ Badge,
4
+ Button,
5
+ Dialog,
6
+ DialogContent,
7
+ DialogDescription,
8
+ DialogHeader,
9
+ DialogTitle,
10
+ FieldError,
11
+ Input,
12
+ Label,
13
+ Select,
14
+ SelectContent,
15
+ SelectItem,
16
+ SelectTrigger,
17
+ SelectValue,
18
+ PlaceholderFrame,
19
+ Skeleton,
20
+ Switch,
21
+ responseJson,
22
+ useDelayedPending,
23
+ } from "@open-workspace/core/ui";
24
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
25
+ import {
26
+ ArrowDown,
27
+ ArrowUp,
28
+ FlaskConical,
29
+ LoaderCircle,
30
+ Pencil,
31
+ Plus,
32
+ Trash2,
33
+ X,
34
+ } from "lucide-react";
35
+ import { useState } from "react";
36
+ import { useFieldArray, useForm, useWatch } from "react-hook-form";
37
+ import { toast } from "sonner";
38
+ import { z } from "zod";
39
+
40
+ import { ruleActionConflict } from "../../shared/mail-rule-actions";
41
+ import { mailApi } from "../lib/mail-api";
42
+ import { mailboxRulesQuery } from "./mail-queries";
43
+ import type {
44
+ MailFolder,
45
+ MailRule,
46
+ MailRuleInput,
47
+ MessageDetail,
48
+ } from "./types";
49
+ import { useFolders } from "./use-mail-data";
50
+
51
+ type Condition = MailRuleInput["conditions"][number];
52
+
53
+ type Action = MailRuleInput["actions"][number];
54
+
55
+ const conditionLabels: Record<Condition["type"], string> = {
56
+ from: "From",
57
+ recipient: "To or Cc",
58
+ subject: "Subject",
59
+ listId: "Mailing list",
60
+ hasAttachment: "Has attachment",
61
+ };
62
+
63
+ const actionLabels: Record<Action["type"], string> = {
64
+ moveToFolder: "Move to folder",
65
+ archive: "Archive",
66
+ trash: "Move to Trash",
67
+ spam: "Move to Spam",
68
+ markRead: "Mark as read",
69
+ notSpam: "Never send to Spam",
70
+ };
71
+
72
+ const opLabels = {
73
+ contains: "contains",
74
+ equals: "is",
75
+ domain: "domain is",
76
+ exists: "exists",
77
+ } as const;
78
+
79
+ type Comparison = Exclude<Condition, { type: "hasAttachment" }>;
80
+
81
+ function comparisonOptions(condition: Comparison) {
82
+ const { type } = condition;
83
+ const value = "value" in condition ? condition.value : "";
84
+
85
+ if (type === "listId") {
86
+ return [
87
+ { type, op: "exists" },
88
+ { type, op: "contains", value },
89
+ ] satisfies Comparison[];
90
+ }
91
+
92
+ const options: Comparison[] = [
93
+ { type, op: "contains", value },
94
+ { type, op: "equals", value },
95
+ ];
96
+
97
+ if (type === "from") options.push({ type, op: "domain", value });
98
+
99
+ return options;
100
+ }
101
+
102
+ function defaultCondition(type: Condition["type"]) {
103
+ switch (type) {
104
+ case "from":
105
+ case "recipient":
106
+ case "subject": {
107
+ return { type, op: "contains", value: "" } satisfies Condition;
108
+ }
109
+
110
+ case "listId": {
111
+ return { type, op: "exists" } satisfies Condition;
112
+ }
113
+
114
+ default: {
115
+ return { type: "hasAttachment" } satisfies Condition;
116
+ }
117
+ }
118
+ }
119
+
120
+ function defaultAction(type: Action["type"], folders: MailFolder[]) {
121
+ return type === "moveToFolder"
122
+ ? ({ type, folderId: folders[0]?.id ?? "" } satisfies Action)
123
+ : ({ type } satisfies Action);
124
+ }
125
+
126
+ function placeholder(condition: Condition) {
127
+ if (condition.type === "subject") return "invoice";
128
+
129
+ if (condition.type === "listId") return "news.example.com";
130
+
131
+ if ("op" in condition && condition.op === "domain") return "example.com";
132
+
133
+ if ("op" in condition && condition.op === "equals") {
134
+ return "name@example.com";
135
+ }
136
+
137
+ return condition.type === "from" ? "@example.com" : "billing@";
138
+ }
139
+
140
+ /** A condition that compares against text the person has to type. */
141
+ function needsValue(
142
+ condition: Condition
143
+ ): condition is Extract<Condition, { value: string }> {
144
+ return "op" in condition && condition.op !== "exists";
145
+ }
146
+
147
+ function describeCondition(condition: Condition) {
148
+ if (condition.type === "hasAttachment") return "it has an attachment";
149
+
150
+ if (condition.type === "listId" && condition.op === "exists") {
151
+ return "it comes from a mailing list";
152
+ }
153
+
154
+ const label = conditionLabels[condition.type].toLowerCase();
155
+
156
+ return `${label} ${opLabels[condition.op]} “${condition.value ?? ""}”`;
157
+ }
158
+
159
+ function describeAction(action: Action, folders: MailFolder[]) {
160
+ if (action.type === "moveToFolder") {
161
+ const folder = folders.find((item) => item.id === action.folderId);
162
+
163
+ return `move to ${folder?.name ?? "a deleted folder"}`;
164
+ }
165
+
166
+ return actionLabels[action.type].toLowerCase();
167
+ }
168
+
169
+ const valueErrors = {
170
+ from: "Enter an address, part of one, or a domain",
171
+ recipient: "Enter an address or part of one",
172
+ subject: "Enter some text",
173
+ listId: "Enter part of the list ID",
174
+ hasAttachment: null,
175
+ };
176
+
177
+ /** A rule the person can save: named, each value typed, each folder picked. */
178
+ function ruleSchema(folders: MailFolder[]) {
179
+ return z.custom<MailRuleInput>().superRefine((draft, context) => {
180
+ if (!draft.name.trim()) {
181
+ context.addIssue({
182
+ code: "custom",
183
+ path: ["name"],
184
+ message: "Give the rule a name",
185
+ });
186
+ }
187
+
188
+ for (const [index, condition] of draft.conditions.entries()) {
189
+ const message = valueErrors[condition.type];
190
+
191
+ if (message && needsValue(condition) && !condition.value?.trim()) {
192
+ context.addIssue({
193
+ code: "custom",
194
+ path: ["conditions", index],
195
+ message,
196
+ });
197
+ }
198
+ }
199
+
200
+ for (const [index, action] of draft.actions.entries()) {
201
+ const message = ruleActionConflict(
202
+ action.type,
203
+ draft.actions.slice(0, index)
204
+ );
205
+
206
+ if (message) {
207
+ context.addIssue({ code: "custom", path: ["actions", index], message });
208
+ }
209
+
210
+ if (
211
+ action.type === "moveToFolder" &&
212
+ !folders.some((folder) => folder.id === action.folderId)
213
+ ) {
214
+ context.addIssue({
215
+ code: "custom",
216
+ path: ["actions", index],
217
+ message: "Pick a folder",
218
+ });
219
+ }
220
+ }
221
+ });
222
+ }
223
+
224
+ /** One of core's Selects over a fixed list of labelled options. */
225
+ function Choice<T extends string>({
226
+ label,
227
+ value,
228
+ options,
229
+ invalid,
230
+ describedBy,
231
+ placeholder: empty,
232
+ onChange,
233
+ }: {
234
+ label: string;
235
+ value: T;
236
+ options: readonly (readonly [T, string])[];
237
+ invalid?: boolean;
238
+ describedBy?: string;
239
+ placeholder?: string;
240
+ onChange: (value: T) => void;
241
+ }) {
242
+ const selected = options.find(([option]) => option === value);
243
+
244
+ return (
245
+ <Select
246
+ value={value}
247
+ onValueChange={(next) => {
248
+ if (next !== null) onChange(next);
249
+ }}
250
+ >
251
+ <SelectTrigger
252
+ size="sm"
253
+ aria-label={label}
254
+ aria-invalid={invalid || undefined}
255
+ aria-describedby={describedBy}
256
+ >
257
+ <SelectValue>
258
+ {selected ? (
259
+ selected[1]
260
+ ) : (
261
+ <span className="text-muted-foreground">{empty}</span>
262
+ )}
263
+ </SelectValue>
264
+ </SelectTrigger>
265
+ <SelectContent align="start">
266
+ {options.map(([option, text]) => (
267
+ <SelectItem key={option} value={option}>
268
+ {text}
269
+ </SelectItem>
270
+ ))}
271
+ </SelectContent>
272
+ </Select>
273
+ );
274
+ }
275
+
276
+ const emptyRule: MailRuleInput = {
277
+ name: "",
278
+ match: "all",
279
+ conditions: [{ type: "from", op: "contains", value: "" }],
280
+ actions: [{ type: "archive" }],
281
+ stopProcessing: false,
282
+ };
283
+
284
+ function ruleInput(rule: MailRule) {
285
+ return {
286
+ name: rule.name,
287
+ match: rule.match,
288
+ conditions: rule.conditions,
289
+ actions: rule.actions,
290
+ stopProcessing: rule.stopProcessing,
291
+ } satisfies MailRuleInput;
292
+ }
293
+
294
+ /** A new rule for mail like this message: its sender, and its list if any. */
295
+ function filterDraft(message: MessageDetail) {
296
+ const conditions: Condition[] = [
297
+ { type: "from", op: "equals", value: message.fromAddress },
298
+ ];
299
+
300
+ if (message.listId) {
301
+ conditions.push({ type: "listId", op: "contains", value: message.listId });
302
+ }
303
+
304
+ return {
305
+ ...emptyRule,
306
+ name: `Mail from ${message.listId ?? message.fromAddress}`,
307
+ conditions,
308
+ } satisfies MailRuleInput;
309
+ }
310
+
311
+ /** Rules tab: ordered deterministic rules for new mail, with an inline editor. */
312
+ export function MailboxRules({
313
+ mailboxId,
314
+ folders,
315
+ active,
316
+ }: {
317
+ mailboxId: string;
318
+ folders: MailFolder[];
319
+ active: boolean;
320
+ }) {
321
+ const client = useQueryClient();
322
+ const [editing, setEditing] = useState<MailRule | "new" | null>(null);
323
+ const customFolders = folders.filter((folder) => folder.kind === "custom");
324
+ const route = mailApi.api.mail.mailboxes[":id"].rules;
325
+ const { queryKey } = mailboxRulesQuery(mailboxId);
326
+ const rules = useQuery({ ...mailboxRulesQuery(mailboxId), enabled: active });
327
+ const skeleton = useDelayedPending(rules.isLoading);
328
+
329
+ const change = useMutation({
330
+ mutationFn: async (
331
+ operation:
332
+ | { type: "toggle"; rule: MailRule; enabled: boolean }
333
+ | { type: "delete"; rule: MailRule }
334
+ | { type: "order"; ruleIds: string[] }
335
+ ) => {
336
+ if (operation.type === "toggle") {
337
+ return responseJson(
338
+ await route[":ruleId"].$patch({
339
+ param: { id: mailboxId, ruleId: operation.rule.id },
340
+ json: { enabled: operation.enabled },
341
+ })
342
+ );
343
+ }
344
+
345
+ if (operation.type === "delete") {
346
+ return responseJson(
347
+ await route[":ruleId"].$delete({
348
+ param: { id: mailboxId, ruleId: operation.rule.id },
349
+ })
350
+ );
351
+ }
352
+
353
+ return responseJson(
354
+ await route.order.$put({
355
+ param: { id: mailboxId },
356
+ json: { ruleIds: operation.ruleIds },
357
+ })
358
+ );
359
+ },
360
+ onError: (error) => toast.error(error.message),
361
+ onSettled: () => client.invalidateQueries({ queryKey }),
362
+ });
363
+
364
+ if (editing) {
365
+ return (
366
+ <RuleEditor
367
+ mailboxId={mailboxId}
368
+ folders={customFolders}
369
+ rule={editing === "new" ? null : editing}
370
+ initial={editing === "new" ? emptyRule : ruleInput(editing)}
371
+ onDone={() => setEditing(null)}
372
+ />
373
+ );
374
+ }
375
+
376
+ if (rules.isLoading || skeleton) {
377
+ return (
378
+ <PlaceholderFrame shown={skeleton}>
379
+ <div className="space-y-2 py-2">
380
+ <Skeleton className="h-12" />
381
+ <Skeleton className="h-12" />
382
+ </div>
383
+ </PlaceholderFrame>
384
+ );
385
+ }
386
+
387
+ if (rules.isError) {
388
+ return (
389
+ <p className="text-muted-foreground border-border/70 border-y py-4 text-sm">
390
+ {rules.error.message}
391
+ </p>
392
+ );
393
+ }
394
+
395
+ const list = rules.data?.rules ?? [];
396
+ const canEdit = rules.data?.canEdit ?? false;
397
+
398
+ function move(index: number, direction: -1 | 1) {
399
+ const ids = list.map((rule) => rule.id);
400
+ const [moved] = ids.splice(index, 1);
401
+
402
+ if (!moved) return;
403
+ ids.splice(index + direction, 0, moved);
404
+ change.mutate({ type: "order", ruleIds: ids });
405
+ }
406
+
407
+ return (
408
+ <div className="space-y-3">
409
+ <div className="flex items-start justify-between gap-3">
410
+ <p className="text-muted-foreground text-xs leading-relaxed">
411
+ Rules run in order on each new message. A matching rule decides the
412
+ folder instead of AI sorting; blocked senders still go to Spam.
413
+ {canEdit || !rules.data
414
+ ? null
415
+ : " Only people who manage teams can change a shared inbox's rules."}
416
+ </p>
417
+ {canEdit ? (
418
+ <Button
419
+ type="button"
420
+ size="sm"
421
+ variant="outline"
422
+ onClick={() => setEditing("new")}
423
+ >
424
+ <Plus />
425
+ New rule
426
+ </Button>
427
+ ) : null}
428
+ </div>
429
+ <div className="border-border/70 max-h-[min(23rem,50vh)] overflow-y-auto border-y">
430
+ {list.length ? (
431
+ <ol aria-label="Rules">
432
+ {list.map((rule, index) => (
433
+ <li
434
+ key={rule.id}
435
+ className="border-border/60 flex items-start gap-3 border-b px-2 py-2.5 last:border-b-0"
436
+ >
437
+ <Switch
438
+ className="mt-0.5"
439
+ checked={rule.enabled}
440
+ aria-label={`${rule.enabled ? "Turn off" : "Turn on"} ${rule.name}`}
441
+ disabled={!canEdit || change.isPending}
442
+ onCheckedChange={(enabled) =>
443
+ change.mutate({ type: "toggle", rule, enabled })
444
+ }
445
+ />
446
+ <div className="min-w-0 flex-1">
447
+ <p className="flex items-center gap-2 text-sm font-medium">
448
+ <span className="truncate">{rule.name}</span>
449
+ {rule.folderDeleted ? (
450
+ <Badge variant="destructive">Folder deleted</Badge>
451
+ ) : null}
452
+ {rule.stopProcessing ? (
453
+ <Badge variant="outline">stops</Badge>
454
+ ) : null}
455
+ </p>
456
+ <p className="text-muted-foreground text-xs leading-relaxed">
457
+ If{" "}
458
+ {rule.conditions
459
+ .map(describeCondition)
460
+ .join(rule.match === "all" ? " and " : " or ")}
461
+ :{" "}
462
+ {rule.actions
463
+ .map((action) => describeAction(action, customFolders))
464
+ .join(", ")}
465
+ .
466
+ </p>
467
+ </div>
468
+ <div className="flex shrink-0 items-center" hidden={!canEdit}>
469
+ <Button
470
+ type="button"
471
+ variant="ghost"
472
+ size="icon-sm"
473
+ aria-label={`Move ${rule.name} up`}
474
+ disabled={index === 0 || change.isPending}
475
+ onClick={() => move(index, -1)}
476
+ >
477
+ <ArrowUp />
478
+ </Button>
479
+ <Button
480
+ type="button"
481
+ variant="ghost"
482
+ size="icon-sm"
483
+ aria-label={`Move ${rule.name} down`}
484
+ disabled={index === list.length - 1 || change.isPending}
485
+ onClick={() => move(index, 1)}
486
+ >
487
+ <ArrowDown />
488
+ </Button>
489
+ <Button
490
+ type="button"
491
+ variant="ghost"
492
+ size="icon-sm"
493
+ aria-label={`Edit ${rule.name}`}
494
+ onClick={() => setEditing(rule)}
495
+ >
496
+ <Pencil />
497
+ </Button>
498
+ <Button
499
+ type="button"
500
+ variant="ghost"
501
+ size="icon-sm"
502
+ aria-label={`Delete ${rule.name}`}
503
+ disabled={change.isPending}
504
+ onClick={() => change.mutate({ type: "delete", rule })}
505
+ >
506
+ <Trash2 />
507
+ </Button>
508
+ </div>
509
+ </li>
510
+ ))}
511
+ </ol>
512
+ ) : (
513
+ <div className="text-muted-foreground grid min-h-28 place-items-center px-6 text-center text-sm">
514
+ No rules yet. Sort or mark read new mail by sender, recipient,
515
+ subject or mailing list.
516
+ </div>
517
+ )}
518
+ </div>
519
+ </div>
520
+ );
521
+ }
522
+
523
+ /** "Filter messages like this": the rule editor, filled in from a message. */
524
+ export function FilterMessagesDialog({
525
+ mailboxId,
526
+ message,
527
+ open,
528
+ onOpenChange,
529
+ }: {
530
+ mailboxId: string;
531
+ message: MessageDetail;
532
+ open: boolean;
533
+ onOpenChange: (open: boolean) => void;
534
+ }) {
535
+ const folders = (useFolders(mailboxId).data?.folders ?? []).filter(
536
+ (folder) => folder.kind === "custom"
537
+ );
538
+
539
+ return (
540
+ <Dialog open={open} onOpenChange={onOpenChange}>
541
+ <DialogContent anchor="top" className="sm:max-w-xl">
542
+ <DialogHeader>
543
+ <DialogTitle>Filter messages like this</DialogTitle>
544
+ <DialogDescription>
545
+ A rule for new mail, shared with everyone who can access this
546
+ mailbox.
547
+ </DialogDescription>
548
+ </DialogHeader>
549
+ <RuleEditor
550
+ mailboxId={mailboxId}
551
+ folders={folders}
552
+ rule={null}
553
+ initial={filterDraft(message)}
554
+ onDone={() => onOpenChange(false)}
555
+ />
556
+ </DialogContent>
557
+ </Dialog>
558
+ );
559
+ }
560
+
561
+ function RuleEditor({
562
+ mailboxId,
563
+ folders,
564
+ rule,
565
+ initial,
566
+ onDone,
567
+ }: {
568
+ mailboxId: string;
569
+ folders: MailFolder[];
570
+ rule: MailRule | null;
571
+ initial: MailRuleInput;
572
+ onDone: () => void;
573
+ }) {
574
+ const client = useQueryClient();
575
+ const route = mailApi.api.mail.mailboxes[":id"].rules;
576
+ const id = (field: string) => `rule-${mailboxId}-${field}`;
577
+
578
+ // Errors show once the person tried to save or test, then follow edits.
579
+ const {
580
+ control,
581
+ formState: { errors, isSubmitted },
582
+ handleSubmit,
583
+ register,
584
+ setValue,
585
+ trigger,
586
+ } = useForm<MailRuleInput>({
587
+ resolver: zodResolver(ruleSchema(folders)),
588
+ defaultValues: initial,
589
+ });
590
+
591
+ const conditionRows = useFieldArray({ control, name: "conditions" });
592
+ const actionRows = useFieldArray({ control, name: "actions" });
593
+
594
+ const draft = useWatch({
595
+ control,
596
+ compute: (values: MailRuleInput) => ({ ...values }),
597
+ });
598
+
599
+ const { conditions, actions } = draft;
600
+
601
+ const save = useMutation({
602
+ mutationFn: async (input: MailRuleInput) =>
603
+ rule
604
+ ? responseJson(
605
+ await route[":ruleId"].$put({
606
+ param: { id: mailboxId, ruleId: rule.id },
607
+ json: input,
608
+ })
609
+ )
610
+ : responseJson(
611
+ await route.$post({ param: { id: mailboxId }, json: input })
612
+ ),
613
+ onSuccess: async () => {
614
+ toast.success(rule ? "Rule updated" : "Rule created");
615
+ await client.invalidateQueries({
616
+ queryKey: ["mailbox-rules", mailboxId],
617
+ });
618
+ onDone();
619
+ },
620
+ onError: (error) => toast.error(error.message),
621
+ });
622
+
623
+ const criteria = { match: draft.match, conditions };
624
+
625
+ const test = useMutation({
626
+ mutationFn: async (input: typeof criteria) =>
627
+ responseJson(
628
+ await route.test.$post({ param: { id: mailboxId }, json: input })
629
+ ),
630
+ });
631
+
632
+ const showTestResult =
633
+ (test.isSuccess || test.isError) &&
634
+ JSON.stringify(test.variables) === JSON.stringify(criteria);
635
+
636
+ // Shown errors follow edits.
637
+ const edit = {
638
+ shouldDirty: true,
639
+ shouldValidate: isSubmitted || Object.keys(errors).length > 0,
640
+ };
641
+
642
+ const setCondition = (index: number, next: Condition) =>
643
+ setValue(`conditions.${index}`, next, edit);
644
+
645
+ const setAction = (index: number, next: Action) =>
646
+ setValue(`actions.${index}`, next, edit);
647
+
648
+ function actionOptions(index?: number) {
649
+ const others = actions.filter((_, i) => i !== index);
650
+
651
+ return Object.entries(actionLabels).flatMap(([value, label]) => {
652
+ // SAFETY: actionLabels' keys are the action types.
653
+ const type = value as Action["type"];
654
+
655
+ return (index !== undefined && type === actions[index]?.type) ||
656
+ (!ruleActionConflict(type, others) &&
657
+ (type !== "moveToFolder" || folders.length))
658
+ ? [[type, label] as const]
659
+ : [];
660
+ });
661
+ }
662
+
663
+ const unusedAction = actionOptions()[0]?.[0];
664
+
665
+ const submit = handleSubmit((input) => save.mutate(input));
666
+
667
+ async function runTest() {
668
+ if (await trigger("conditions")) test.mutate(structuredClone(criteria));
669
+ }
670
+
671
+ return (
672
+ <form className="space-y-4" noValidate onSubmit={submit}>
673
+ <div className="space-y-1.5">
674
+ <Label htmlFor={id("name")}>Name</Label>
675
+ <Input
676
+ id={id("name")}
677
+ maxLength={120}
678
+ placeholder="Receipts to Archive"
679
+ aria-invalid={Boolean(errors.name) || undefined}
680
+ aria-describedby={errors.name ? id("name-error") : undefined}
681
+ {...register("name")}
682
+ />
683
+ <FieldError id={id("name-error")} errors={[errors.name]} />
684
+ </div>
685
+
686
+ <fieldset className="space-y-2">
687
+ <legend className="mb-2 flex items-center gap-2 text-sm">
688
+ When
689
+ <Choice
690
+ label="Match"
691
+ value={draft.match ?? "all"}
692
+ options={
693
+ [
694
+ ["all", "all"],
695
+ ["any", "any"],
696
+ ] as const
697
+ }
698
+ onChange={(match) => setValue("match", match, edit)}
699
+ />
700
+ of these are true:
701
+ </legend>
702
+ {conditionRows.fields.map((row, index) => {
703
+ const condition = conditions[index];
704
+
705
+ if (!condition) return null;
706
+
707
+ const comparisons =
708
+ "op" in condition ? comparisonOptions(condition) : [];
709
+
710
+ const error = errors.conditions?.[index]?.message ?? null;
711
+ const errorId = id(`condition-${index}-error`);
712
+
713
+ return (
714
+ <div key={row.id} className="flex flex-wrap items-center gap-2">
715
+ <Choice
716
+ label="Condition"
717
+ value={condition.type}
718
+ options={Object.entries(conditionLabels).map(
719
+ ([type, label]) =>
720
+ // SAFETY: conditionLabels' keys are the condition types.
721
+ [type as Condition["type"], label] as const
722
+ )}
723
+ onChange={(type) => setCondition(index, defaultCondition(type))}
724
+ />
725
+ {"op" in condition ? (
726
+ <Choice
727
+ label="Comparison"
728
+ value={condition.op}
729
+ options={comparisons.map(
730
+ ({ op }) => [op, opLabels[op]] as const
731
+ )}
732
+ onChange={(op) => {
733
+ const selected = comparisons.find(
734
+ (option) => option.op === op
735
+ );
736
+
737
+ if (selected) setCondition(index, selected);
738
+ }}
739
+ />
740
+ ) : null}
741
+ {needsValue(condition) ? (
742
+ <Input
743
+ aria-label="Value"
744
+ className="h-8 min-w-40 flex-1"
745
+ maxLength={320}
746
+ placeholder={placeholder(condition)}
747
+ value={condition.value ?? ""}
748
+ aria-invalid={Boolean(error) || undefined}
749
+ aria-describedby={error ? errorId : undefined}
750
+ onChange={(event) =>
751
+ setCondition(index, {
752
+ ...condition,
753
+ value: event.target.value,
754
+ })
755
+ }
756
+ />
757
+ ) : null}
758
+ <Button
759
+ type="button"
760
+ variant="ghost"
761
+ size="icon-sm"
762
+ aria-label="Remove condition"
763
+ disabled={conditionRows.fields.length === 1}
764
+ onClick={() => conditionRows.remove(index)}
765
+ >
766
+ <X />
767
+ </Button>
768
+ <FieldError id={errorId} className="w-full">
769
+ {error}
770
+ </FieldError>
771
+ </div>
772
+ );
773
+ })}
774
+ <Button
775
+ type="button"
776
+ variant="outline"
777
+ size="sm"
778
+ disabled={conditionRows.fields.length >= 10}
779
+ onClick={() => conditionRows.append(defaultCondition("subject"))}
780
+ >
781
+ <Plus />
782
+ Condition
783
+ </Button>
784
+ </fieldset>
785
+
786
+ <fieldset className="space-y-2">
787
+ <legend className="mb-2 text-sm">Then:</legend>
788
+ {actionRows.fields.map((row, index) => {
789
+ const action = actions[index];
790
+
791
+ if (!action) return null;
792
+ const error = errors.actions?.[index]?.message ?? null;
793
+ const errorId = id(`action-${index}-error`);
794
+
795
+ return (
796
+ <div key={row.id} className="flex flex-wrap items-center gap-2">
797
+ <Choice
798
+ label="Action"
799
+ value={action.type}
800
+ options={actionOptions(index)}
801
+ invalid={Boolean(error)}
802
+ describedBy={error ? errorId : undefined}
803
+ onChange={(type) =>
804
+ setAction(index, defaultAction(type, folders))
805
+ }
806
+ />
807
+ {action.type === "moveToFolder" ? (
808
+ <Choice
809
+ label="Folder"
810
+ value={action.folderId}
811
+ placeholder="Pick a folder"
812
+ invalid={Boolean(error)}
813
+ describedBy={error ? errorId : undefined}
814
+ options={folders.map(
815
+ (folder) => [folder.id, folder.name] as const
816
+ )}
817
+ onChange={(folderId) =>
818
+ setAction(index, { ...action, folderId })
819
+ }
820
+ />
821
+ ) : null}
822
+ <Button
823
+ type="button"
824
+ variant="ghost"
825
+ size="icon-sm"
826
+ aria-label="Remove action"
827
+ disabled={actionRows.fields.length === 1}
828
+ onClick={() => actionRows.remove(index)}
829
+ >
830
+ <X />
831
+ </Button>
832
+ <FieldError id={errorId} className="w-full">
833
+ {error}
834
+ </FieldError>
835
+ </div>
836
+ );
837
+ })}
838
+ <Button
839
+ type="button"
840
+ variant="outline"
841
+ size="sm"
842
+ disabled={!unusedAction}
843
+ onClick={() =>
844
+ unusedAction &&
845
+ actionRows.append(defaultAction(unusedAction, folders))
846
+ }
847
+ >
848
+ <Plus />
849
+ Action
850
+ </Button>
851
+ <p className="text-muted-foreground text-xs leading-relaxed">
852
+ Moving and archiving apply to new conversations, as AI sorting does.
853
+ </p>
854
+ </fieldset>
855
+
856
+ <label className="flex items-center gap-2 text-sm">
857
+ <Switch
858
+ checked={draft.stopProcessing ?? false}
859
+ onCheckedChange={(stopProcessing) =>
860
+ setValue("stopProcessing", stopProcessing, edit)
861
+ }
862
+ />
863
+ Stop running later rules when this one matches
864
+ </label>
865
+
866
+ {showTestResult ? (
867
+ <p className="bg-muted rounded-md px-3 py-2 text-sm" role="status">
868
+ {test.isError
869
+ ? test.error.message
870
+ : `Matches ${test.data.matches} of the last ${test.data.scanned} incoming messages.`}
871
+ </p>
872
+ ) : null}
873
+
874
+ <div className="flex flex-wrap justify-end gap-2">
875
+ <Button type="button" variant="ghost" onClick={onDone}>
876
+ Cancel
877
+ </Button>
878
+ <Button
879
+ type="button"
880
+ variant="outline"
881
+ disabled={test.isPending}
882
+ onClick={() => void runTest()}
883
+ >
884
+ {test.isPending ? (
885
+ <LoaderCircle className="animate-spin" />
886
+ ) : (
887
+ <FlaskConical />
888
+ )}
889
+ Test on recent mail
890
+ </Button>
891
+ <Button type="submit" disabled={save.isPending}>
892
+ {save.isPending ? <LoaderCircle className="animate-spin" /> : null}
893
+ {rule ? "Save rule" : "Create rule"}
894
+ </Button>
895
+ </div>
896
+ </form>
897
+ );
898
+ }