@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -0,0 +1,60 @@
1
+ import { workspaceIconPath } from "@open-workspace/core/shared";
2
+ import { useWorkspaceBrand } from "@open-workspace/core/ui";
3
+ import { useEffect } from "react";
4
+
5
+ import { useMailboxes } from "./use-mail-data";
6
+
7
+ /** The page's own favicon: the workspace's logo, or the OpenWorkspace icon. */
8
+ const DEFAULT_FAVICON = workspaceIconPath(64);
9
+
10
+ /** The OpenWorkspace icon with a dot; a workspace logo stays as it is, the title carries the count. */
11
+ const UNREAD_FAVICON = "/icons/app-icon-unread.svg";
12
+
13
+ function unreadLabel(count: number) {
14
+ return count > 999 ? "999+" : String(count);
15
+ }
16
+
17
+ function updateAppBadge(count: number) {
18
+ const operation =
19
+ count > 0 ? navigator.setAppBadge?.(count) : navigator.clearAppBadge?.();
20
+
21
+ void operation?.catch(() => {
22
+ // Badging is optional and can be denied independently of notifications.
23
+ });
24
+ }
25
+
26
+ export function UnreadDocumentIndicator() {
27
+ const { name: title, logoUrl } = useWorkspaceBrand();
28
+ const mailboxQuery = useMailboxes();
29
+ let unreadCount = 0;
30
+
31
+ for (const mailbox of mailboxQuery.data?.mailboxes ?? []) {
32
+ unreadCount += mailbox.unreadCount;
33
+ }
34
+
35
+ useEffect(() => {
36
+ document.title =
37
+ unreadCount > 0 ? `(${unreadLabel(unreadCount)}) ${title}` : title;
38
+ const favicon = document.querySelector<HTMLLinkElement>("#app-favicon");
39
+
40
+ if (favicon) {
41
+ favicon.href =
42
+ unreadCount > 0 && !logoUrl ? UNREAD_FAVICON : DEFAULT_FAVICON;
43
+ }
44
+
45
+ updateAppBadge(unreadCount);
46
+ }, [unreadCount, title, logoUrl]);
47
+
48
+ useEffect(
49
+ () => () => {
50
+ document.title = title;
51
+ const favicon = document.querySelector<HTMLLinkElement>("#app-favicon");
52
+
53
+ if (favicon) favicon.href = DEFAULT_FAVICON;
54
+ updateAppBadge(0);
55
+ },
56
+ [title]
57
+ );
58
+
59
+ return null;
60
+ }
@@ -0,0 +1,208 @@
1
+ import type { FormEvent, RefObject } from "react";
2
+
3
+ import type { ComposerContent, ComposerEditorHandle } from "./composer-editor";
4
+ import type { ValidatedComposerRecipients } from "./composer-recipients";
5
+ import { isUploadedAsset } from "./composer-session";
6
+ import type {
7
+ ComposerAsset,
8
+ ComposerSession,
9
+ ComposerSessionPhase,
10
+ } from "./composer-session";
11
+ import { notifyOutboundResult } from "./outbound-notification";
12
+ import type { Mailbox, MessageDetail } from "./types";
13
+ import { resolveComposerAttachmentPlan } from "./use-composer-attachment-preflight";
14
+ import type { PreflightContext } from "./use-composer-attachment-preflight";
15
+ import { useComposerSubmission } from "./use-composer-submission";
16
+ import type { PreparedComposerSubmission } from "./use-composer-submission";
17
+ import type { MailSendDraft } from "./use-mail-send";
18
+
19
+ type ForwardedComposeMessage = Pick<MessageDetail, "id">;
20
+
21
+ type ComposeSubmissionInput = {
22
+ session: ComposerSession;
23
+ phase: ComposerSessionPhase;
24
+ mailbox: Mailbox;
25
+ forwardedMessage?: ForwardedComposeMessage;
26
+ recipients: ValidatedComposerRecipients;
27
+ subject: string;
28
+ content: ComposerContent;
29
+ editor: RefObject<ComposerEditorHandle | null>;
30
+ activeAssets: readonly ComposerAsset[];
31
+ uploadLimitError: string | null;
32
+ uploadsPending: boolean;
33
+ uploadsFailed: boolean;
34
+ onClose: () => void;
35
+ };
36
+
37
+ export function useComposeSubmission(input: ComposeSubmissionInput) {
38
+ const submission = useComposerSubmission({
39
+ session: input.session,
40
+ phase: input.phase,
41
+ validate: () => submissionValidationError(input),
42
+ prepare: (signal) => prepareComposeSubmission(input, signal),
43
+ failureLabel: "Could not send message",
44
+ onSuccess: (result) => {
45
+ notifyOutboundResult(result, "message");
46
+ input.onClose();
47
+ },
48
+ });
49
+
50
+ return {
51
+ busy: submission.busy,
52
+ submit: (event: FormEvent) => {
53
+ event.preventDefault();
54
+ void submission.submit();
55
+ },
56
+ };
57
+ }
58
+
59
+ async function prepareComposeSubmission(
60
+ input: ComposeSubmissionInput,
61
+ signal: AbortSignal
62
+ ): Promise<PreparedComposerSubmission> {
63
+ let content = input.editor.current?.content() ?? input.content;
64
+
65
+ if (!input.forwardedMessage && !hasAuthoredContent(content)) {
66
+ throw new Error("Add text to the message before sending");
67
+ }
68
+
69
+ const activeIds = new Set(
70
+ input.editor.current?.assetIds() ??
71
+ input.activeAssets.map((asset) => asset.id)
72
+ );
73
+
74
+ const assets = input.session
75
+ .getSnapshot()
76
+ .assets.filter((asset) => activeIds.has(asset.id));
77
+
78
+ if (assets.length) {
79
+ await resolveComposerAttachmentPlan(
80
+ input.session,
81
+ preflightContext(input, content),
82
+ assets,
83
+ signal
84
+ );
85
+ // Freeze exactly the same link-card projection that final preflight chose.
86
+ input.editor.current?.reconcileAssets();
87
+ content = input.editor.current?.content() ?? content;
88
+ }
89
+
90
+ if (!input.forwardedMessage && !hasAuthoredContent(content)) {
91
+ throw new Error("Add text to the message before sending");
92
+ }
93
+
94
+ const finalActiveIds = new Set(
95
+ input.editor.current?.assetIds() ?? [...activeIds]
96
+ );
97
+
98
+ const linkedDocumentAssetIds = new Set(content.linkedAssetIds);
99
+
100
+ const submittedAssets = input.session
101
+ .getSnapshot()
102
+ .assets.filter(isUploadedAsset)
103
+ .filter((asset) => finalActiveIds.has(asset.id));
104
+
105
+ const uploadedAttachments = submittedAssets.map((asset) => {
106
+ const linkedInline =
107
+ asset.intent === "inline" && linkedDocumentAssetIds.has(asset.id);
108
+
109
+ return {
110
+ uploadId: asset.uploadId,
111
+ disposition: linkedInline ? ("attachment" as const) : asset.intent,
112
+ // A linked inline image goes as a plain attachment, without its content
113
+ // ID; JSON leaves an undefined one out.
114
+ contentId: (!linkedInline && asset.contentId) || undefined,
115
+ };
116
+ });
117
+
118
+ const common = {
119
+ mailboxId: input.mailbox.id,
120
+ bodyText: content.bodyText,
121
+ bodyHtml:
122
+ content.bodyText.trim() ||
123
+ content.inlineAssetIds.length ||
124
+ content.linkedAssetIds.length
125
+ ? content.bodyHtml
126
+ : undefined,
127
+ uploadedAttachments,
128
+ };
129
+
130
+ const command: MailSendDraft = input.forwardedMessage
131
+ ? {
132
+ ...common,
133
+ kind: "forward",
134
+ sourceEmailId: input.forwardedMessage.id,
135
+ to: input.recipients.to,
136
+ cc: input.recipients.cc,
137
+ bcc: input.recipients.bcc,
138
+ replyTo: input.recipients.replyTo,
139
+ }
140
+ : {
141
+ ...common,
142
+ kind: "compose",
143
+ to: input.recipients.to,
144
+ cc: input.recipients.cc,
145
+ bcc: input.recipients.bcc,
146
+ replyTo: input.recipients.replyTo,
147
+ subject: input.subject,
148
+ };
149
+
150
+ return {
151
+ assetIds: submittedAssets.map((asset) => asset.id),
152
+ command,
153
+ submissionKey: JSON.stringify(command),
154
+ };
155
+ }
156
+
157
+ function submissionValidationError(input: ComposeSubmissionInput) {
158
+ if (input.recipients.error) return input.recipients.error;
159
+
160
+ if (input.recipients.count === 0) {
161
+ return "Add at least one recipient in To, Cc, or Bcc";
162
+ }
163
+
164
+ if (input.uploadLimitError) return input.uploadLimitError;
165
+
166
+ if (input.uploadsPending) {
167
+ return "Wait for attachments to finish uploading";
168
+ }
169
+
170
+ if (input.uploadsFailed) return "Retry or remove failed attachments";
171
+
172
+ if (!input.mailbox.canSend) return "This mailbox is read-only";
173
+ const content = input.editor.current?.content() ?? input.content;
174
+
175
+ if (!input.forwardedMessage && !hasAuthoredContent(content)) {
176
+ return "Add text to the message before sending";
177
+ }
178
+
179
+ return null;
180
+ }
181
+
182
+ function hasAuthoredContent(content: ComposerContent) {
183
+ return Boolean(content.bodyText.trim() || content.inlineAssetIds.length);
184
+ }
185
+
186
+ function preflightContext(
187
+ input: Pick<
188
+ ComposeSubmissionInput,
189
+ "forwardedMessage" | "mailbox" | "subject"
190
+ >,
191
+ content: ComposerContent
192
+ ): PreflightContext {
193
+ return input.forwardedMessage
194
+ ? {
195
+ kind: "forward",
196
+ mailboxId: input.mailbox.id,
197
+ sourceEmailId: input.forwardedMessage.id,
198
+ bodyText: content.bodyText,
199
+ bodyHtml: content.bodyHtml || undefined,
200
+ }
201
+ : {
202
+ kind: "compose",
203
+ mailboxId: input.mailbox.id,
204
+ subject: input.subject,
205
+ bodyText: content.bodyText,
206
+ bodyHtml: content.bodyHtml || undefined,
207
+ };
208
+ }
@@ -0,0 +1,184 @@
1
+ import { required } from "@open-workspace/core/shared";
2
+ import { useDebouncedValue, responseJson } from "@open-workspace/core/ui";
3
+ import { useEffect, useEffectEvent } from "react";
4
+
5
+ import type { ReplyActionMode } from "../../shared/mail";
6
+ import { mailApi } from "../lib/mail-api";
7
+ import type { ComposerAsset, ComposerSession } from "./composer-session";
8
+
9
+ const textEncoder = new TextEncoder();
10
+
11
+ export type PreflightContext =
12
+ | {
13
+ kind: "compose";
14
+ mailboxId: string;
15
+ subject: string;
16
+ bodyText: string;
17
+ bodyHtml?: string;
18
+ }
19
+ | {
20
+ kind: "forward";
21
+ mailboxId: string;
22
+ sourceEmailId: string;
23
+ bodyText: string;
24
+ bodyHtml?: string;
25
+ }
26
+ | {
27
+ kind: "reply";
28
+ mailboxId: string;
29
+ sourceEmailId: string;
30
+ mode: ReplyActionMode;
31
+ cc: string[];
32
+ bcc: string[];
33
+ bodyText: string;
34
+ bodyHtml?: string;
35
+ };
36
+
37
+ function byteLength(value: string | undefined) {
38
+ return value ? textEncoder.encode(value).byteLength : 0;
39
+ }
40
+
41
+ function preflightContextSignature(context: PreflightContext) {
42
+ const content = [
43
+ byteLength(context.bodyText),
44
+ byteLength(context.bodyText.trimEnd()),
45
+ byteLength(context.bodyHtml),
46
+ ];
47
+
48
+ if (context.kind === "compose") {
49
+ return [
50
+ "compose",
51
+ context.mailboxId,
52
+ byteLength(context.subject.trim()),
53
+ ...content,
54
+ ];
55
+ }
56
+
57
+ if (context.kind === "forward") {
58
+ return ["forward", context.mailboxId, context.sourceEmailId, ...content];
59
+ }
60
+
61
+ return [
62
+ "reply",
63
+ context.mailboxId,
64
+ context.sourceEmailId,
65
+ context.mode,
66
+ context.cc,
67
+ context.bcc,
68
+ ...content,
69
+ ];
70
+ }
71
+
72
+ function composerPlanKey(
73
+ context: PreflightContext,
74
+ assets: readonly ComposerAsset[]
75
+ ) {
76
+ return JSON.stringify([
77
+ preflightContextSignature(context),
78
+ assets.map((asset) => [
79
+ asset.id,
80
+ asset.uploadId,
81
+ asset.intent,
82
+ asset.contentId,
83
+ ]),
84
+ ]);
85
+ }
86
+
87
+ async function preflightComposerAttachments(
88
+ context: PreflightContext,
89
+ assets: readonly ComposerAsset[],
90
+ signal?: AbortSignal
91
+ ) {
92
+ return responseJson(
93
+ await mailApi.api.mail["attachment-preflight"].$post(
94
+ {
95
+ json: {
96
+ ...context,
97
+ attachments: assets.map((asset) => ({
98
+ uploadId: required(
99
+ asset.uploadId,
100
+ "Attachments are preflighted once uploaded"
101
+ ),
102
+ disposition: asset.intent,
103
+ // JSON leaves an undefined content ID out.
104
+ contentId: asset.contentId || undefined,
105
+ })),
106
+ },
107
+ },
108
+ { init: { signal } }
109
+ )
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Fetches and publishes one revision-tagged plan. Both the debounced preview
115
+ * and the final send check use this path, so they cannot drift apart.
116
+ */
117
+ export async function resolveComposerAttachmentPlan(
118
+ session: ComposerSession,
119
+ context: PreflightContext,
120
+ assets: readonly ComposerAsset[],
121
+ signal?: AbortSignal
122
+ ) {
123
+ const planKey = composerPlanKey(context, assets);
124
+ session.beginPlan(planKey);
125
+
126
+ if (!assets.length) {
127
+ session.resolvePlan(planKey, []);
128
+
129
+ return;
130
+ }
131
+
132
+ try {
133
+ const result = await preflightComposerAttachments(context, assets, signal);
134
+ const linkedUploadIds = new Set(result.linkedUploadIds);
135
+ session.resolvePlan(
136
+ planKey,
137
+ assets.flatMap((asset) =>
138
+ asset.uploadId && linkedUploadIds.has(asset.uploadId) ? [asset.id] : []
139
+ )
140
+ );
141
+ } catch (error) {
142
+ if (!signal?.aborted) session.failPlan(planKey);
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Preflight only publishes a revision-tagged delivery plan to the session.
149
+ * ProseMirror subscribes to that plan directly, so React never rewrites nodes.
150
+ */
151
+ export function useComposerAttachmentPreflight(
152
+ session: ComposerSession,
153
+ context: PreflightContext,
154
+ assets: readonly ComposerAsset[],
155
+ active = true
156
+ ) {
157
+ const requestKey = composerPlanKey(context, assets);
158
+ const debouncedRequestKey = useDebouncedValue(requestKey, 750);
159
+
160
+ // Reads this render's context and assets, which requestKey names.
161
+ const resolvePlan = useEffectEvent((signal: AbortSignal) => {
162
+ if (!assets.length || assets.some((asset) => !asset.uploadId)) return;
163
+ void resolveComposerAttachmentPlan(session, context, assets, signal).catch(
164
+ () => {
165
+ // Background preflight is advisory. Final submission reports failures.
166
+ }
167
+ );
168
+ });
169
+
170
+ useEffect(() => {
171
+ if (!active) return;
172
+ session.beginPlan(requestKey);
173
+
174
+ if (!assets.length) session.resolvePlan(requestKey, []);
175
+ }, [active, assets.length, requestKey, session]);
176
+
177
+ useEffect(() => {
178
+ if (!active || requestKey !== debouncedRequestKey) return;
179
+ const controller = new AbortController();
180
+ resolvePlan(controller.signal);
181
+
182
+ return () => controller.abort();
183
+ }, [active, debouncedRequestKey, requestKey]);
184
+ }
@@ -0,0 +1,117 @@
1
+ import { ApiError } from "@open-workspace/core/ui";
2
+ import { useEffect, useRef } from "react";
3
+ import { toast } from "sonner";
4
+
5
+ import { isComposerSessionBusy } from "./composer-session";
6
+ import type { ComposerSession, ComposerSessionPhase } from "./composer-session";
7
+ import { useMailSend, withMailSendRequestId } from "./use-mail-send";
8
+ import type { MailSendDraft, SubmittedMessage } from "./use-mail-send";
9
+
10
+ export type PreparedComposerSubmission = {
11
+ assetIds: string[];
12
+ command: MailSendDraft;
13
+ submissionKey: string;
14
+ };
15
+
16
+ /**
17
+ * Owns the shared preflight -> submit -> release/complete transition. Draft
18
+ * preparation remains composer-specific, but transport ownership has one path.
19
+ */
20
+ export function useComposerSubmission(input: {
21
+ session: ComposerSession;
22
+ phase: ComposerSessionPhase;
23
+ validate: () => string | null;
24
+ prepare: (signal: AbortSignal) => Promise<PreparedComposerSubmission>;
25
+ failureLabel: string;
26
+ onSuccess: (result: SubmittedMessage) => void;
27
+ }) {
28
+ const { send } = useMailSend();
29
+ const mounted = useRef(true);
30
+ const preflightRequest = useRef<AbortController | null>(null);
31
+
32
+ useEffect(() => {
33
+ mounted.current = true;
34
+
35
+ return () => {
36
+ mounted.current = false;
37
+ preflightRequest.current?.abort();
38
+ };
39
+ }, []);
40
+
41
+ async function submit() {
42
+ const validationError = input.validate();
43
+
44
+ if (validationError) {
45
+ toast.error(validationError);
46
+
47
+ return;
48
+ }
49
+
50
+ if (!input.session.beginPreflight()) return;
51
+
52
+ const controller = new AbortController();
53
+ preflightRequest.current = controller;
54
+
55
+ const preparation = await input.prepare(controller.signal).then(
56
+ (prepared) => ({ prepared }),
57
+ (cause: unknown) => ({ cause })
58
+ );
59
+
60
+ if (preflightRequest.current === controller) {
61
+ preflightRequest.current = null;
62
+ }
63
+
64
+ if ("cause" in preparation) {
65
+ if (!controller.signal.aborted) input.session.cancelPreflight();
66
+
67
+ if (controller.signal.aborted || !mounted.current) return;
68
+ const { cause } = preparation;
69
+ toast.error(cause instanceof Error ? cause.message : input.failureLabel);
70
+
71
+ return;
72
+ }
73
+
74
+ const { prepared } = preparation;
75
+
76
+ if (controller.signal.aborted || !mounted.current) {
77
+ input.session.cancelPreflight();
78
+
79
+ return;
80
+ }
81
+
82
+ const requestId = input.session.beginSubmission(
83
+ prepared.assetIds,
84
+ prepared.submissionKey
85
+ );
86
+
87
+ if (!requestId) return;
88
+
89
+ let result: SubmittedMessage;
90
+
91
+ try {
92
+ result = await send.mutateAsync(
93
+ withMailSendRequestId(prepared.command, requestId)
94
+ );
95
+ } catch (error) {
96
+ // The continuation can outlive React after a mailbox switch. Session
97
+ // ownership still has to be released even when no UI remains.
98
+ input.session.releaseSubmission(
99
+ !(error instanceof ApiError) || error.status >= 500
100
+ );
101
+
102
+ if (!mounted.current) return;
103
+ toast.error(error instanceof Error ? error.message : input.failureLabel);
104
+
105
+ return;
106
+ }
107
+
108
+ input.session.completeSubmission();
109
+
110
+ if (mounted.current) input.onSuccess(result);
111
+ }
112
+
113
+ return {
114
+ busy: isComposerSessionBusy(input.phase),
115
+ submit,
116
+ };
117
+ }