@rapidmx/web-client 0.18.0 → 0.20.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 (131) hide show
  1. package/README.md +381 -381
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -482
  4. package/apps/admin/domains/[uid].tsx +166 -166
  5. package/apps/admin/escrow-scopes/[uid].tsx +350 -350
  6. package/apps/admin/index.tsx +129 -129
  7. package/apps/admin/mailboxes/[uid].tsx +271 -271
  8. package/apps/admin/mailboxes/new/index.tsx +30 -30
  9. package/apps/admin/plugins/index.tsx +15 -15
  10. package/apps/admin/retention-policy/index.tsx +39 -39
  11. package/apps/admin/signing-certificates/index.tsx +343 -343
  12. package/apps/escrow/audit-log/index.tsx +196 -196
  13. package/apps/escrow/matters/[uid].tsx +621 -621
  14. package/apps/shared/auth/adminAccess.ts +99 -99
  15. package/apps/shared/components/admin/diagnostics/HostCard.tsx +2 -0
  16. package/apps/shared/components/admin/diagnostics/PressureTiles.tsx +108 -0
  17. package/apps/shared/components/admin/diagnostics/PvcTable.tsx +20 -6
  18. package/apps/shared/components/admin/diagnostics/diagnosticsApi.ts +21 -2
  19. package/apps/shared/components/admin/layout/AdminShell.tsx +384 -384
  20. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -238
  21. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  22. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -194
  23. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  25. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  26. package/apps/shared/components/admin/settings/PluginsManager.tsx +2093 -1545
  27. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  28. package/apps/shared/components/admin/settings/pluginPreferences.ts +34 -0
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +446 -446
  31. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  32. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  33. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  34. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  39. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -103
  40. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  41. package/apps/shared/components/layout/AppShell.tsx +461 -461
  42. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  43. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  44. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  45. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  46. package/apps/shared/components/layout/UserMenu.tsx +439 -439
  47. package/apps/shared/components/mail/ConversationList.tsx +332 -323
  48. package/apps/shared/components/mail/ConversationThreadPane.tsx +613 -613
  49. package/apps/shared/components/mail/MailSelectionBar.tsx +240 -240
  50. package/apps/shared/components/mail/MenuButton.tsx +404 -404
  51. package/apps/shared/components/mail/MessageDetailPane.tsx +1757 -1757
  52. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  53. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  54. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1681
  55. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  57. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  58. package/apps/shared/components/mail/listPreferences.ts +3 -3
  59. package/apps/shared/components/mail/reading/MessageMoreMenu.tsx +258 -258
  60. package/apps/shared/components/mail/reading/MessageSourceDialog.tsx +79 -79
  61. package/apps/shared/components/mail/reading/messageExport.ts +59 -59
  62. package/apps/shared/components/mail/reading/printMessage.ts +99 -99
  63. package/apps/shared/components/mail/reading/useMessageActions.ts +443 -443
  64. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  65. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  66. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  67. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  68. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  69. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  70. package/apps/shared/keyboard/dispatch.ts +124 -124
  71. package/apps/shared/keyboard/format.ts +89 -89
  72. package/apps/shared/keyboard/keymap.ts +114 -114
  73. package/apps/shared/keyboard/registry.ts +65 -65
  74. package/apps/shared/keyboard/targets.ts +79 -79
  75. package/apps/shared/mail/folderOfType.ts +49 -49
  76. package/apps/shared/mail/folderTree.ts +143 -143
  77. package/apps/shared/mail/listAllPages.ts +39 -39
  78. package/apps/shared/mail/newMailNotifications.ts +171 -171
  79. package/apps/shared/mail/outbox/sendJob.ts +445 -445
  80. package/apps/shared/mail/outbox/sendOutcomes.ts +155 -155
  81. package/apps/shared/mail/reportNotices.ts +66 -66
  82. package/apps/shared/mail/senderBlocking.ts +141 -141
  83. package/apps/shared/mail/useMailConnection.ts +205 -205
  84. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  85. package/apps/shared/mail/useMailboxUpdateAccess.ts +60 -60
  86. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  87. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  88. package/apps/shared/notifications/store.ts +560 -560
  89. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  90. package/apps/shared/search/localIndexBuilder.ts +481 -481
  91. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  92. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  93. package/apps/shared/signing/enrollmentView.ts +251 -251
  94. package/apps/shared/signing/useNow.ts +19 -19
  95. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  96. package/apps/shared/styles/app.css +396 -396
  97. package/apps/www/calendar/index.tsx +581 -581
  98. package/apps/www/contacts/[uid].tsx +112 -112
  99. package/apps/www/index.tsx +3012 -2962
  100. package/apps/www/messages/[uid].tsx +139 -139
  101. package/apps/www/settings/auto-reply/index.tsx +136 -136
  102. package/apps/www/settings/blocked-senders/index.tsx +303 -303
  103. package/apps/www/settings/encryption/index.tsx +1290 -1290
  104. package/apps/www/settings/filters/[uid].tsx +179 -179
  105. package/apps/www/settings/filters/index.tsx +105 -105
  106. package/apps/www/settings/filters/new/index.tsx +165 -165
  107. package/apps/www/settings/labels/index.tsx +207 -207
  108. package/apps/www/settings/privacy/index.tsx +495 -495
  109. package/apps/www/settings/profile/index.tsx +251 -251
  110. package/apps/www/settings/read-receipts/index.tsx +150 -150
  111. package/apps/www/settings/sharing/index.tsx +259 -259
  112. package/apps/www/settings/signatures/[uid].tsx +175 -175
  113. package/apps/www/settings/signatures/index.tsx +91 -91
  114. package/apps/www/settings/signatures/new/index.tsx +138 -138
  115. package/apps/www/tasks/index.tsx +654 -654
  116. package/dist/apps/shared/components/admin/diagnostics/HostCard.js +2 -1
  117. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.d.ts +22 -0
  118. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.js +52 -0
  119. package/dist/apps/shared/components/admin/diagnostics/PvcTable.js +9 -4
  120. package/dist/apps/shared/components/admin/diagnostics/diagnosticsApi.d.ts +35 -2
  121. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  122. package/dist/apps/shared/components/admin/settings/PluginsManager.js +328 -48
  123. package/dist/apps/shared/components/admin/settings/pluginPreferences.d.ts +2 -0
  124. package/dist/apps/shared/components/admin/settings/pluginPreferences.js +35 -0
  125. package/dist/apps/shared/components/mail/ConversationList.d.ts +10 -3
  126. package/dist/apps/shared/components/mail/ConversationList.js +9 -5
  127. package/dist/apps/shared/components/mail/listPreferences.d.ts +1 -1
  128. package/dist/apps/shared/components/mail/reading/printMessage.js +11 -11
  129. package/dist/apps/shared/styles/app.css +396 -396
  130. package/dist/apps/www/index.js +51 -10
  131. package/package.json +2 -2
@@ -1,445 +1,445 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
6
- import {
7
- Attachment,
8
- ComposeRecipientInput,
9
- DraftThreading,
10
- Mailbox,
11
- Message,
12
- assembleDraft,
13
- assembleDraftRaw,
14
- getMailbox,
15
- getMessage,
16
- queueMessageSend,
17
- sendMessage,
18
- setMessageRequestReceipt,
19
- } from "@rapidmx/react-shared/mail/mailApi.js";
20
- import { describeSendFailure } from "@rapidmx/react-shared/mail/sendFailure.js";
21
- import { RecipientEncryptionStatus, resolveRecipientEncryption } from "@rapidmx/react-shared/crypto/composeSecurity.js";
22
- import { getUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
23
- import { EncryptionPolicy, findActivePublicKey, getEncryptionPolicy, lookupKeys } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
24
- import { fromBase64 } from "@rapidmx/react-shared/crypto/encoding.js";
25
- import type { ProtectedHeaders } from "@rapidmx/react-shared/crypto/smimeMessage.js";
26
- import { policyCanAutoEncrypt } from "../../components/mail/compose/encryptionRequirement.js";
27
- import { NotificationAction, dismiss, notify } from "../../notifications/store.js";
28
- import { INLINE_IMAGE_PATTERN, SendBlock, SendDecisionInput, decideSend } from "./sendDecision.js";
29
- import { beginPendingSend, finishPendingSend, setPendingStage } from "./pendingSends.js";
30
- import { failOutgoing, forgetOutgoing, markOutgoingSending, markOutgoingSent, trackOutgoing } from "./outgoingReplies.js";
31
- import { openComposeFromOutside, requestUnlockFromOutside } from "./composeBridge.js";
32
- import { OutboxCountTracker, sendState } from "./sendState.js";
33
-
34
- /** Everything the background send needs, captured when Send is clicked: the window it came from is gone by the time it runs. */
35
- export interface SendRequest {
36
- /** The window's server draft. */
37
- draft: Message;
38
- mailboxUid: string;
39
- /** The sender's mailbox as the window had loaded it - `undefined` when that load had not succeeded (the send then tries again itself). */
40
- mailbox: Mailbox | undefined;
41
- /** The encryption policy as the window had loaded it, `undefined` likewise. */
42
- policy: EncryptionPolicy | undefined;
43
- /** The window's To/Cc/Bcc field text, kept so "Open draft" restores them exactly. */
44
- toText: string;
45
- ccText: string;
46
- bccText: string;
47
- to: ComposeRecipientInput[];
48
- cc: ComposeRecipientInput[];
49
- bcc: ComposeRecipientInput[];
50
- subject: string;
51
- html: string;
52
- attachments: Attachment[];
53
- requestReceipt: boolean;
54
- /** Send later: an ISO time in the future. Absent for an immediate send. */
55
- scheduledSendTime?: string;
56
- signEnabled: boolean;
57
- /** The sign / encrypt options were shown to the sender at some point this compose session (their keys were unlocked). */
58
- offeredSign: boolean;
59
- offeredEncrypt: boolean;
60
- encryptRequested: boolean;
61
- /** The sender's explicit choice to send without encryption/signing checks (an override). */
62
- forcePlaintext: boolean;
63
- /** Settles when the window's own autosaves have landed, so none can overwrite the assembly below. */
64
- saved?: Promise<unknown>;
65
- /** The thread this message continues (a reply or forward), as the compose session was opened with it - what lets the conversation on screen
66
- * show the message as soon as it is sent (see `outgoingReplies.ts`). Absent for a new message, and for a draft opened again, which the draft's own
67
- * `inReplyTo`/`references` stand in for. */
68
- threading?: DraftThreading;
69
- }
70
-
71
- /** How long a background send waits for the mailbox / encryption policy it did not have, before it goes ahead treating them as unknown. Nobody waits for it. */
72
- export const CONTEXT_GRACE_MS = 4_000;
73
-
74
- export function registerOutboxCounter(tracker: (mailboxUid: string) => OutboxCountTracker, onQueued: (mailboxUid: string) => void): () => void {
75
- sendState.countTracker = tracker;
76
- sendState.queuedListener = onQueued;
77
- return () => {
78
- if (sendState.countTracker === tracker) {
79
- sendState.countTracker = undefined;
80
- sendState.queuedListener = undefined;
81
- }
82
- };
83
- }
84
-
85
- const RETAINED_LIMIT = 25;
86
-
87
- /** The request a message was queued from, while this tab still holds it: what lets "Open draft" and "Retry" work on a failure the server reports later. */
88
- export function retainedRequest(draftUid: string): SendRequest | undefined {
89
- return sendState.retained.get(draftUid);
90
- }
91
-
92
- export function forgetRetainedRequest(draftUid: string): void {
93
- sendState.retained.delete(draftUid);
94
- }
95
-
96
- function retain(request: SendRequest): void {
97
- sendState.retained.delete(request.draft.uid);
98
- sendState.retained.set(request.draft.uid, request);
99
- if (sendState.retained.size > RETAINED_LIMIT) {
100
- sendState.retained.delete(sendState.retained.keys().next().value!);
101
- }
102
- }
103
-
104
- const UNSAFE_DISPLAY_NAME_PATTERN = /[@@﹫\r\n]/;
105
-
106
- /** The sender's signing/encryption key state right now, read from the tab's key session (they can lock mid-send). */
107
- export function readSendKeys(mailboxUid: string, signEnabled: boolean, mailbox: Mailbox | undefined) {
108
- const stored = getUnlockedKeys(mailboxUid);
109
- const unlocked = stored?.destroyed ? undefined : stored;
110
- return {
111
- unlocked,
112
- canSign: signEnabled && !!mailbox && !!unlocked?.signingPrivateKey && !!unlocked.signingCertDer,
113
- canEncryptSelf: !!unlocked?.encryptionPrivateKey && !!unlocked.encryptionCertDer,
114
- };
115
- }
116
-
117
- /** Whether this sender could encrypt at all: an encryption key unlocked here, enrolled on the mailbox, or offered earlier this session. */
118
- export function senderHasEncryptionKey(request: Pick<SendRequest, "mailbox" | "offeredEncrypt">, canEncryptSelf: boolean): boolean {
119
- return canEncryptSelf || request.offeredEncrypt || !!findActivePublicKey(request.mailbox?.keys ?? [], "encrypt");
120
- }
121
-
122
- /** The input `decideSend()` reads, from a request and what has been looked up. */
123
- export function sendDecisionInput(
124
- request: SendRequest,
125
- mailbox: Mailbox | undefined,
126
- policy: EncryptionPolicy | undefined,
127
- recipients: (RecipientEncryptionStatus | undefined)[],
128
- lookupsComplete: boolean,
129
- ): SendDecisionInput {
130
- const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
131
- return {
132
- forcePlaintext: request.forcePlaintext,
133
- signEnabled: request.signEnabled,
134
- offeredSign: request.offeredSign,
135
- encryptRequested: request.encryptRequested,
136
- policy,
137
- mailboxLoaded: !!mailbox,
138
- hasEncryptionKey: senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keys.canEncryptSelf),
139
- keys: { canSign: keys.canSign, canEncryptSelf: keys.canEncryptSelf, unlocked: !!keys.unlocked },
140
- recipients,
141
- lookupsComplete,
142
- hasBcc: request.bcc.length > 0,
143
- hasAttachments: request.attachments.length > 0,
144
- hasInlineImages: INLINE_IMAGE_PATTERN.test(request.html),
145
- };
146
- }
147
-
148
- /** A send that did not go: the plain reason, the technical lines, and - for a refusal the sender can override - which. */
149
- interface Failure {
150
- message: string;
151
- details: string[];
152
- block?: SendBlock;
153
- }
154
-
155
- type Outcome = { kind: "queued" | "sent" | "scheduled" } | { kind: "failed"; failure: Failure };
156
-
157
- const OPEN_POLICY: EncryptionPolicy = { encryptSameOrg: "optional", encryptFederated: "optional", encryptExternal: "optional" };
158
-
159
- /** The mailbox and policy this send is missing, loaded now: the sender is not waiting, so a slow answer costs nothing - but it is not waited on for ever. */
160
- async function completeContext(request: SendRequest): Promise<{ mailbox: Mailbox | undefined; policy: EncryptionPolicy | undefined }> {
161
- let mailbox = request.mailbox;
162
- let policy = request.policy;
163
- const keysNow = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
164
- const loads: Promise<unknown>[] = [];
165
- if (!mailbox) {
166
- loads.push(getMailbox(request.mailboxUid).then((loaded) => void (mailbox = loaded)));
167
- }
168
- if (!policy && (!mailbox || senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keysNow.canEncryptSelf))) {
169
- loads.push(getEncryptionPolicy().then((loaded) => void (policy = loaded)));
170
- }
171
- if (loads.length > 0) {
172
- let timer: ReturnType<typeof setTimeout> | undefined;
173
- const grace = new Promise<void>((resolve) => {
174
- timer = setTimeout(resolve, CONTEXT_GRACE_MS);
175
- });
176
- await Promise.race([Promise.allSettled(loads), grace]);
177
- clearTimeout(timer);
178
- }
179
- return { mailbox, policy };
180
- }
181
-
182
- /** Builds the message's final content into the draft (plain, signed, or signed and encrypted in this browser) and returns the stored message. */
183
- async function assemble(
184
- request: SendRequest,
185
- mailbox: Mailbox | undefined,
186
- mode: "plain" | "sign" | "encrypt",
187
- statuses: (RecipientEncryptionStatus | undefined)[],
188
- withSignature: boolean,
189
- ): Promise<Message> {
190
- const { draft, to, cc, bcc, subject, html } = request;
191
- if (mode === "plain") {
192
- return assembleDraft(draft.uid, { to, cc, bcc, subject, html });
193
- }
194
- const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
195
- const own = mailbox!;
196
- const domain = own.primarySmtpAddress.split("@")[1] ?? "localhost";
197
- const displayName = own.displayName && !UNSAFE_DISPLAY_NAME_PATTERN.test(own.displayName) ? own.displayName : "";
198
- const protectedHeaders: ProtectedHeaders = {
199
- from: displayName ? `"${displayName.replace(/"/g, '\\"')}" <${own.primarySmtpAddress}>` : own.primarySmtpAddress,
200
- to: to.map((r) => r.address).join(", "),
201
- cc: cc.length > 0 ? cc.map((r) => r.address).join(", ") : undefined,
202
- date: new Date().toUTCString(),
203
- subject,
204
- messageId: `<${crypto.randomUUID()}@${domain}>`,
205
- };
206
- const bodyContentType = 'text/html; charset="utf-8"';
207
- const signing = withSignature ? { certDer: keys.unlocked!.signingCertDer!, privateKey: keys.unlocked!.signingPrivateKey! } : undefined;
208
- // The S/MIME code (PKI.js and the ASN.1/X.509 libraries, over half a megabyte) is only needed here, to sign or encrypt - a plain message
209
- // never loads it, and it is kept out of the compose window's own chunk.
210
- const { applyBaselineOuterHeaders, assembleOutboundMime, buildEncryptedMessage, buildSignedOnlyMessage } = await import(
211
- "@rapidmx/react-shared/crypto/smimeMessage.js"
212
- );
213
- const encrypt = mode === "encrypt";
214
- const outerHeaders = encrypt ? applyBaselineOuterHeaders(protectedHeaders) : protectedHeaders;
215
- const mimePart = encrypt
216
- ? await buildEncryptedMessage(
217
- bodyContentType,
218
- html,
219
- protectedHeaders,
220
- outerHeaders,
221
- [keys.unlocked!.encryptionCertDer!, ...statuses.map((status) => fromBase64(status!.encryptCert!.publicKey))],
222
- signing,
223
- )
224
- : await buildSignedOnlyMessage(bodyContentType, html, protectedHeaders, signing!.certDer, signing!.privateKey);
225
- const rawMime = assembleOutboundMime(outerHeaders, mimePart);
226
- return assembleDraftRaw(draft.uid, { to, cc, bcc, subject: outerHeaders.subject, rawMime });
227
- }
228
-
229
- function failureOf(err: unknown, fallback: string): Failure {
230
- const failure = describeSendFailure(err, fallback);
231
- return { message: failure.message, details: failure.lines };
232
- }
233
-
234
- /** Whether the server already holds `request`'s message as accepted (out of Drafts, or leased) - the answer to "did that request that never returned actually land?". */
235
- async function alreadyAccepted(request: SendRequest): Promise<boolean> {
236
- try {
237
- const fresh = await getMessage(request.draft.uid);
238
- return fresh.folderUid !== request.draft.folderUid || !!fresh.scheduledSendLeaseExpiresAt || !!fresh.scheduledSendRelayedAt;
239
- } catch {
240
- return false;
241
- }
242
- }
243
-
244
- /** The whole client-side path of one send: settle, decide, assemble, hand over. Never rejects. */
245
- async function attempt(request: SendRequest): Promise<Outcome> {
246
- try {
247
- await request.saved?.catch(() => undefined);
248
- const all = [...request.to, ...request.cc, ...request.bcc];
249
- let mailbox = request.mailbox;
250
- let policy = request.policy;
251
- let statuses: (RecipientEncryptionStatus | undefined)[] = all.map(() => undefined);
252
- let lookupsComplete = false;
253
-
254
- if (!request.forcePlaintext) {
255
- ({ mailbox, policy } = await completeContext(request));
256
- const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
257
- const hasKey = senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keys.canEncryptSelf);
258
- // Recipients' keys are only looked up when the answer can matter: encryption was asked for, or the loaded policy auto-applies.
259
- if (mailbox && hasKey && (request.encryptRequested || (policy && policyCanAutoEncrypt(policy)))) {
260
- const own = mailbox;
261
- const ownPrefersMutual = own.encryptPreference?.preferEncrypt === "mutual";
262
- const lookups = await Promise.all(
263
- all.map((recipient) =>
264
- lookupKeys(request.mailboxUid, recipient.address).then(
265
- (lookup) => ({ lookup }),
266
- () => null,
267
- ),
268
- ),
269
- );
270
- statuses = all.map((recipient, index) => {
271
- const found = lookups[index];
272
- return found ? resolveRecipientEncryption(own.primarySmtpAddress, ownPrefersMutual, policy ?? OPEN_POLICY, recipient.address, found.lookup) : undefined;
273
- });
274
- }
275
- lookupsComplete = true;
276
- }
277
-
278
- const decision = decideSend(sendDecisionInput(request, mailbox, policy, statuses, lookupsComplete));
279
- if (decision.action === "blocked") {
280
- return { kind: "failed", failure: { message: decision.block.message, details: [], block: decision.block } };
281
- }
282
- if (decision.action === "rejected") {
283
- return { kind: "failed", failure: { message: decision.message, details: [] } };
284
- }
285
-
286
- const assembled = await assemble(request, mailbox, decision.action, statuses, decision.action === "sign" || (decision.action === "encrypt" && decision.sign));
287
- const withReceipt = request.requestReceipt ? await setMessageRequestReceipt(assembled, true) : assembled;
288
- setPendingStage(request.draft.uid, "queuing");
289
- try {
290
- if (request.scheduledSendTime) {
291
- await sendMessage(withReceipt.uid, { scheduledSendTime: request.scheduledSendTime });
292
- return { kind: "scheduled" };
293
- }
294
- const result = await queueMessageSend(withReceipt.uid);
295
- return { kind: result.queued ? "queued" : "sent" };
296
- } catch (err) {
297
- // A request that never came back may still have landed: never offer to send it twice if it did.
298
- if (!(err instanceof ApiRequestError) && (await alreadyAccepted(request))) {
299
- return { kind: request.scheduledSendTime ? "scheduled" : "queued" };
300
- }
301
- throw err;
302
- }
303
- } catch (err) {
304
- return { kind: "failed", failure: failureOf(err, request.scheduledSendTime ? "Could not schedule this message." : "Could not send this message.") };
305
- }
306
- }
307
-
308
- function recipientSummary(request: SendRequest): string {
309
- const all = [...request.to, ...request.cc, ...request.bcc].map((recipient) => recipient.address);
310
- return all.length <= 2 ? all.join(" and ") : `${all[0]} and ${all.length - 1} others`;
311
- }
312
-
313
- /** "Message to a@b.c and 2 others (\"Subject\")" - which message a pop-up is about. */
314
- export function describeMessage(subject: string, recipients: string): string {
315
- return `${recipients ? `To ${recipients}` : "Message"}${subject ? ` - "${subject}"` : ""}`;
316
- }
317
-
318
- /** Re-opens the compose window around a request's message, with everything as it was typed. */
319
- export function openDraftFromRequest(request: SendRequest): boolean {
320
- const opened = openComposeFromOutside({
321
- mailboxUid: request.mailboxUid,
322
- resume: {
323
- draft: request.draft,
324
- mailboxUid: request.mailboxUid,
325
- to: request.toText,
326
- cc: request.ccText,
327
- bcc: request.bccText,
328
- subject: request.subject,
329
- html: request.html,
330
- attachments: request.attachments,
331
- requestReceipt: request.requestReceipt,
332
- signEnabled: request.signEnabled,
333
- encryptRequested: request.encryptRequested,
334
- },
335
- });
336
- // Being edited again, it is no longer a message on its way in the conversation.
337
- if (opened) {
338
- forgetOutgoing(request.draft.uid);
339
- }
340
- return opened;
341
- }
342
-
343
- function failureNotificationId(draftUid: string): string {
344
- return `send-failed:${draftUid}`;
345
- }
346
-
347
- /** The sticky "This message wasn't sent" pop-up for a send that failed on this side, with what can be done about it. */
348
- function notifyFailure(request: SendRequest, failure: Failure): void {
349
- const uid = request.draft.uid;
350
- const actions: NotificationAction[] = [];
351
- const { block } = failure;
352
- if (block?.keysLocked && request.mailbox?.keys?.length) {
353
- actions.push({
354
- label: "Unlock",
355
- onClick: () => {
356
- void requestUnlockFromOutside(request.mailboxUid, request.mailbox!.keys!).then(
357
- () => void retrySend(request),
358
- () => undefined,
359
- );
360
- },
361
- });
362
- }
363
- if (block) {
364
- actions.push({ label: block.overrideLabel, onClick: () => void retrySend({ ...request, forcePlaintext: true }) });
365
- } else {
366
- actions.push({ label: "Retry", onClick: () => void retrySend(request) });
367
- }
368
- actions.push({ label: "Open draft", onClick: () => void openDraftFromRequest(request) });
369
- notify({
370
- id: failureNotificationId(uid),
371
- kind: "error",
372
- title: "This message wasn't sent",
373
- message: `${describeMessage(request.subject, recipientSummary(request))}: ${failure.message}`,
374
- details: failure.details,
375
- actions,
376
- });
377
- // The conversation on screen shows the same failure under the message, with the same ways out.
378
- failOutgoing(uid, failure.message, actions);
379
- }
380
-
381
- const SENT_BURST_MS = 6_000;
382
-
383
- /** The short "Message sent" confirmation - several sent close together are one pop-up counting up, never a stack of them. */
384
- export function notifySent(message = "Message sent"): void {
385
- const now = Date.now();
386
- const { sentBurst } = sendState;
387
- sendState.sentBurst = { count: now - sentBurst.at > SENT_BURST_MS ? 1 : sentBurst.count + 1, at: now };
388
- notify({ id: "message-sent", kind: "success", title: sendState.sentBurst.count > 1 ? `${sendState.sentBurst.count} messages sent` : message, timeoutMs: 4_000 });
389
- }
390
-
391
- /**
392
- * Sends `request`'s draft in the background and returns at once, `true` - or `false` (doing nothing) when a send of this draft is already
393
- * under way here. The outcome is shown as pop-ups and the Outbox indicator, never as a window that waits: a failure at any stage (assembling,
394
- * encrypting, the request) is a sticky "This message wasn't sent" with the reason, and Retry / Open draft; the server's own later outcome
395
- * (`send-succeeded`, `send-failed`, `send-retrying`) is `handleSendEvent()`'s.
396
- */
397
- export function startSend(request: SendRequest): boolean {
398
- const uid = request.draft.uid;
399
- const recipients = [...request.to, ...request.cc, ...request.bcc].map((recipient) => recipient.address);
400
- if (!beginPendingSend({ draftUid: uid, mailboxUid: request.mailboxUid, subject: request.subject, recipients, scheduled: !!request.scheduledSendTime })) {
401
- return false;
402
- }
403
- // The failure of an earlier attempt is resolved by trying again.
404
- dismiss(failureNotificationId(uid));
405
- // A reply or forward is on screen in its conversation from this moment, before any of the work below.
406
- trackOutgoing(request);
407
- const tracker = sendState.countTracker?.(request.mailboxUid);
408
- void attempt(request).then((outcome) => {
409
- finishPendingSend(uid);
410
- if (outcome.kind === "failed") {
411
- tracker?.revert();
412
- notifyFailure(request, outcome.failure);
413
- return;
414
- }
415
- tracker?.settle();
416
- if (outcome.kind === "queued") {
417
- retain(request);
418
- sendState.queuedListener?.(request.mailboxUid);
419
- } else if (outcome.kind === "sent") {
420
- // A server with no queue relayed it before answering: the Sent Items copy exists already.
421
- markOutgoingSent(uid);
422
- notifySent();
423
- } else {
424
- notify({
425
- id: `scheduled:${uid}`,
426
- kind: "success",
427
- title: "Message scheduled",
428
- message: `It will be sent ${new Date(request.scheduledSendTime!).toLocaleString()}.`,
429
- timeoutMs: 5_000,
430
- });
431
- }
432
- });
433
- return true;
434
- }
435
-
436
- /** Tries a failed send again - unless the server already has the message (an earlier request that seemed to fail did land), which it must not send twice. */
437
- export async function retrySend(request: SendRequest): Promise<void> {
438
- if (await alreadyAccepted(request)) {
439
- dismiss(failureNotificationId(request.draft.uid));
440
- markOutgoingSending(request.draft.uid);
441
- notify({ id: `already-sent:${request.draft.uid}`, kind: "info", title: "This message is already on its way", timeoutMs: 5_000 });
442
- return;
443
- }
444
- startSend({ ...request, saved: undefined });
445
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
6
+ import {
7
+ Attachment,
8
+ ComposeRecipientInput,
9
+ DraftThreading,
10
+ Mailbox,
11
+ Message,
12
+ assembleDraft,
13
+ assembleDraftRaw,
14
+ getMailbox,
15
+ getMessage,
16
+ queueMessageSend,
17
+ sendMessage,
18
+ setMessageRequestReceipt,
19
+ } from "@rapidmx/react-shared/mail/mailApi.js";
20
+ import { describeSendFailure } from "@rapidmx/react-shared/mail/sendFailure.js";
21
+ import { RecipientEncryptionStatus, resolveRecipientEncryption } from "@rapidmx/react-shared/crypto/composeSecurity.js";
22
+ import { getUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
23
+ import { EncryptionPolicy, findActivePublicKey, getEncryptionPolicy, lookupKeys } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
24
+ import { fromBase64 } from "@rapidmx/react-shared/crypto/encoding.js";
25
+ import type { ProtectedHeaders } from "@rapidmx/react-shared/crypto/smimeMessage.js";
26
+ import { policyCanAutoEncrypt } from "../../components/mail/compose/encryptionRequirement.js";
27
+ import { NotificationAction, dismiss, notify } from "../../notifications/store.js";
28
+ import { INLINE_IMAGE_PATTERN, SendBlock, SendDecisionInput, decideSend } from "./sendDecision.js";
29
+ import { beginPendingSend, finishPendingSend, setPendingStage } from "./pendingSends.js";
30
+ import { failOutgoing, forgetOutgoing, markOutgoingSending, markOutgoingSent, trackOutgoing } from "./outgoingReplies.js";
31
+ import { openComposeFromOutside, requestUnlockFromOutside } from "./composeBridge.js";
32
+ import { OutboxCountTracker, sendState } from "./sendState.js";
33
+
34
+ /** Everything the background send needs, captured when Send is clicked: the window it came from is gone by the time it runs. */
35
+ export interface SendRequest {
36
+ /** The window's server draft. */
37
+ draft: Message;
38
+ mailboxUid: string;
39
+ /** The sender's mailbox as the window had loaded it - `undefined` when that load had not succeeded (the send then tries again itself). */
40
+ mailbox: Mailbox | undefined;
41
+ /** The encryption policy as the window had loaded it, `undefined` likewise. */
42
+ policy: EncryptionPolicy | undefined;
43
+ /** The window's To/Cc/Bcc field text, kept so "Open draft" restores them exactly. */
44
+ toText: string;
45
+ ccText: string;
46
+ bccText: string;
47
+ to: ComposeRecipientInput[];
48
+ cc: ComposeRecipientInput[];
49
+ bcc: ComposeRecipientInput[];
50
+ subject: string;
51
+ html: string;
52
+ attachments: Attachment[];
53
+ requestReceipt: boolean;
54
+ /** Send later: an ISO time in the future. Absent for an immediate send. */
55
+ scheduledSendTime?: string;
56
+ signEnabled: boolean;
57
+ /** The sign / encrypt options were shown to the sender at some point this compose session (their keys were unlocked). */
58
+ offeredSign: boolean;
59
+ offeredEncrypt: boolean;
60
+ encryptRequested: boolean;
61
+ /** The sender's explicit choice to send without encryption/signing checks (an override). */
62
+ forcePlaintext: boolean;
63
+ /** Settles when the window's own autosaves have landed, so none can overwrite the assembly below. */
64
+ saved?: Promise<unknown>;
65
+ /** The thread this message continues (a reply or forward), as the compose session was opened with it - what lets the conversation on screen
66
+ * show the message as soon as it is sent (see `outgoingReplies.ts`). Absent for a new message, and for a draft opened again, which the draft's own
67
+ * `inReplyTo`/`references` stand in for. */
68
+ threading?: DraftThreading;
69
+ }
70
+
71
+ /** How long a background send waits for the mailbox / encryption policy it did not have, before it goes ahead treating them as unknown. Nobody waits for it. */
72
+ export const CONTEXT_GRACE_MS = 4_000;
73
+
74
+ export function registerOutboxCounter(tracker: (mailboxUid: string) => OutboxCountTracker, onQueued: (mailboxUid: string) => void): () => void {
75
+ sendState.countTracker = tracker;
76
+ sendState.queuedListener = onQueued;
77
+ return () => {
78
+ if (sendState.countTracker === tracker) {
79
+ sendState.countTracker = undefined;
80
+ sendState.queuedListener = undefined;
81
+ }
82
+ };
83
+ }
84
+
85
+ const RETAINED_LIMIT = 25;
86
+
87
+ /** The request a message was queued from, while this tab still holds it: what lets "Open draft" and "Retry" work on a failure the server reports later. */
88
+ export function retainedRequest(draftUid: string): SendRequest | undefined {
89
+ return sendState.retained.get(draftUid);
90
+ }
91
+
92
+ export function forgetRetainedRequest(draftUid: string): void {
93
+ sendState.retained.delete(draftUid);
94
+ }
95
+
96
+ function retain(request: SendRequest): void {
97
+ sendState.retained.delete(request.draft.uid);
98
+ sendState.retained.set(request.draft.uid, request);
99
+ if (sendState.retained.size > RETAINED_LIMIT) {
100
+ sendState.retained.delete(sendState.retained.keys().next().value!);
101
+ }
102
+ }
103
+
104
+ const UNSAFE_DISPLAY_NAME_PATTERN = /[@@﹫\r\n]/;
105
+
106
+ /** The sender's signing/encryption key state right now, read from the tab's key session (they can lock mid-send). */
107
+ export function readSendKeys(mailboxUid: string, signEnabled: boolean, mailbox: Mailbox | undefined) {
108
+ const stored = getUnlockedKeys(mailboxUid);
109
+ const unlocked = stored?.destroyed ? undefined : stored;
110
+ return {
111
+ unlocked,
112
+ canSign: signEnabled && !!mailbox && !!unlocked?.signingPrivateKey && !!unlocked.signingCertDer,
113
+ canEncryptSelf: !!unlocked?.encryptionPrivateKey && !!unlocked.encryptionCertDer,
114
+ };
115
+ }
116
+
117
+ /** Whether this sender could encrypt at all: an encryption key unlocked here, enrolled on the mailbox, or offered earlier this session. */
118
+ export function senderHasEncryptionKey(request: Pick<SendRequest, "mailbox" | "offeredEncrypt">, canEncryptSelf: boolean): boolean {
119
+ return canEncryptSelf || request.offeredEncrypt || !!findActivePublicKey(request.mailbox?.keys ?? [], "encrypt");
120
+ }
121
+
122
+ /** The input `decideSend()` reads, from a request and what has been looked up. */
123
+ export function sendDecisionInput(
124
+ request: SendRequest,
125
+ mailbox: Mailbox | undefined,
126
+ policy: EncryptionPolicy | undefined,
127
+ recipients: (RecipientEncryptionStatus | undefined)[],
128
+ lookupsComplete: boolean,
129
+ ): SendDecisionInput {
130
+ const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
131
+ return {
132
+ forcePlaintext: request.forcePlaintext,
133
+ signEnabled: request.signEnabled,
134
+ offeredSign: request.offeredSign,
135
+ encryptRequested: request.encryptRequested,
136
+ policy,
137
+ mailboxLoaded: !!mailbox,
138
+ hasEncryptionKey: senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keys.canEncryptSelf),
139
+ keys: { canSign: keys.canSign, canEncryptSelf: keys.canEncryptSelf, unlocked: !!keys.unlocked },
140
+ recipients,
141
+ lookupsComplete,
142
+ hasBcc: request.bcc.length > 0,
143
+ hasAttachments: request.attachments.length > 0,
144
+ hasInlineImages: INLINE_IMAGE_PATTERN.test(request.html),
145
+ };
146
+ }
147
+
148
+ /** A send that did not go: the plain reason, the technical lines, and - for a refusal the sender can override - which. */
149
+ interface Failure {
150
+ message: string;
151
+ details: string[];
152
+ block?: SendBlock;
153
+ }
154
+
155
+ type Outcome = { kind: "queued" | "sent" | "scheduled" } | { kind: "failed"; failure: Failure };
156
+
157
+ const OPEN_POLICY: EncryptionPolicy = { encryptSameOrg: "optional", encryptFederated: "optional", encryptExternal: "optional" };
158
+
159
+ /** The mailbox and policy this send is missing, loaded now: the sender is not waiting, so a slow answer costs nothing - but it is not waited on for ever. */
160
+ async function completeContext(request: SendRequest): Promise<{ mailbox: Mailbox | undefined; policy: EncryptionPolicy | undefined }> {
161
+ let mailbox = request.mailbox;
162
+ let policy = request.policy;
163
+ const keysNow = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
164
+ const loads: Promise<unknown>[] = [];
165
+ if (!mailbox) {
166
+ loads.push(getMailbox(request.mailboxUid).then((loaded) => void (mailbox = loaded)));
167
+ }
168
+ if (!policy && (!mailbox || senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keysNow.canEncryptSelf))) {
169
+ loads.push(getEncryptionPolicy().then((loaded) => void (policy = loaded)));
170
+ }
171
+ if (loads.length > 0) {
172
+ let timer: ReturnType<typeof setTimeout> | undefined;
173
+ const grace = new Promise<void>((resolve) => {
174
+ timer = setTimeout(resolve, CONTEXT_GRACE_MS);
175
+ });
176
+ await Promise.race([Promise.allSettled(loads), grace]);
177
+ clearTimeout(timer);
178
+ }
179
+ return { mailbox, policy };
180
+ }
181
+
182
+ /** Builds the message's final content into the draft (plain, signed, or signed and encrypted in this browser) and returns the stored message. */
183
+ async function assemble(
184
+ request: SendRequest,
185
+ mailbox: Mailbox | undefined,
186
+ mode: "plain" | "sign" | "encrypt",
187
+ statuses: (RecipientEncryptionStatus | undefined)[],
188
+ withSignature: boolean,
189
+ ): Promise<Message> {
190
+ const { draft, to, cc, bcc, subject, html } = request;
191
+ if (mode === "plain") {
192
+ return assembleDraft(draft.uid, { to, cc, bcc, subject, html });
193
+ }
194
+ const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
195
+ const own = mailbox!;
196
+ const domain = own.primarySmtpAddress.split("@")[1] ?? "localhost";
197
+ const displayName = own.displayName && !UNSAFE_DISPLAY_NAME_PATTERN.test(own.displayName) ? own.displayName : "";
198
+ const protectedHeaders: ProtectedHeaders = {
199
+ from: displayName ? `"${displayName.replace(/"/g, '\\"')}" <${own.primarySmtpAddress}>` : own.primarySmtpAddress,
200
+ to: to.map((r) => r.address).join(", "),
201
+ cc: cc.length > 0 ? cc.map((r) => r.address).join(", ") : undefined,
202
+ date: new Date().toUTCString(),
203
+ subject,
204
+ messageId: `<${crypto.randomUUID()}@${domain}>`,
205
+ };
206
+ const bodyContentType = 'text/html; charset="utf-8"';
207
+ const signing = withSignature ? { certDer: keys.unlocked!.signingCertDer!, privateKey: keys.unlocked!.signingPrivateKey! } : undefined;
208
+ // The S/MIME code (PKI.js and the ASN.1/X.509 libraries, over half a megabyte) is only needed here, to sign or encrypt - a plain message
209
+ // never loads it, and it is kept out of the compose window's own chunk.
210
+ const { applyBaselineOuterHeaders, assembleOutboundMime, buildEncryptedMessage, buildSignedOnlyMessage } = await import(
211
+ "@rapidmx/react-shared/crypto/smimeMessage.js"
212
+ );
213
+ const encrypt = mode === "encrypt";
214
+ const outerHeaders = encrypt ? applyBaselineOuterHeaders(protectedHeaders) : protectedHeaders;
215
+ const mimePart = encrypt
216
+ ? await buildEncryptedMessage(
217
+ bodyContentType,
218
+ html,
219
+ protectedHeaders,
220
+ outerHeaders,
221
+ [keys.unlocked!.encryptionCertDer!, ...statuses.map((status) => fromBase64(status!.encryptCert!.publicKey))],
222
+ signing,
223
+ )
224
+ : await buildSignedOnlyMessage(bodyContentType, html, protectedHeaders, signing!.certDer, signing!.privateKey);
225
+ const rawMime = assembleOutboundMime(outerHeaders, mimePart);
226
+ return assembleDraftRaw(draft.uid, { to, cc, bcc, subject: outerHeaders.subject, rawMime });
227
+ }
228
+
229
+ function failureOf(err: unknown, fallback: string): Failure {
230
+ const failure = describeSendFailure(err, fallback);
231
+ return { message: failure.message, details: failure.lines };
232
+ }
233
+
234
+ /** Whether the server already holds `request`'s message as accepted (out of Drafts, or leased) - the answer to "did that request that never returned actually land?". */
235
+ async function alreadyAccepted(request: SendRequest): Promise<boolean> {
236
+ try {
237
+ const fresh = await getMessage(request.draft.uid);
238
+ return fresh.folderUid !== request.draft.folderUid || !!fresh.scheduledSendLeaseExpiresAt || !!fresh.scheduledSendRelayedAt;
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
243
+
244
+ /** The whole client-side path of one send: settle, decide, assemble, hand over. Never rejects. */
245
+ async function attempt(request: SendRequest): Promise<Outcome> {
246
+ try {
247
+ await request.saved?.catch(() => undefined);
248
+ const all = [...request.to, ...request.cc, ...request.bcc];
249
+ let mailbox = request.mailbox;
250
+ let policy = request.policy;
251
+ let statuses: (RecipientEncryptionStatus | undefined)[] = all.map(() => undefined);
252
+ let lookupsComplete = false;
253
+
254
+ if (!request.forcePlaintext) {
255
+ ({ mailbox, policy } = await completeContext(request));
256
+ const keys = readSendKeys(request.mailboxUid, request.signEnabled, mailbox);
257
+ const hasKey = senderHasEncryptionKey({ mailbox, offeredEncrypt: request.offeredEncrypt }, keys.canEncryptSelf);
258
+ // Recipients' keys are only looked up when the answer can matter: encryption was asked for, or the loaded policy auto-applies.
259
+ if (mailbox && hasKey && (request.encryptRequested || (policy && policyCanAutoEncrypt(policy)))) {
260
+ const own = mailbox;
261
+ const ownPrefersMutual = own.encryptPreference?.preferEncrypt === "mutual";
262
+ const lookups = await Promise.all(
263
+ all.map((recipient) =>
264
+ lookupKeys(request.mailboxUid, recipient.address).then(
265
+ (lookup) => ({ lookup }),
266
+ () => null,
267
+ ),
268
+ ),
269
+ );
270
+ statuses = all.map((recipient, index) => {
271
+ const found = lookups[index];
272
+ return found ? resolveRecipientEncryption(own.primarySmtpAddress, ownPrefersMutual, policy ?? OPEN_POLICY, recipient.address, found.lookup) : undefined;
273
+ });
274
+ }
275
+ lookupsComplete = true;
276
+ }
277
+
278
+ const decision = decideSend(sendDecisionInput(request, mailbox, policy, statuses, lookupsComplete));
279
+ if (decision.action === "blocked") {
280
+ return { kind: "failed", failure: { message: decision.block.message, details: [], block: decision.block } };
281
+ }
282
+ if (decision.action === "rejected") {
283
+ return { kind: "failed", failure: { message: decision.message, details: [] } };
284
+ }
285
+
286
+ const assembled = await assemble(request, mailbox, decision.action, statuses, decision.action === "sign" || (decision.action === "encrypt" && decision.sign));
287
+ const withReceipt = request.requestReceipt ? await setMessageRequestReceipt(assembled, true) : assembled;
288
+ setPendingStage(request.draft.uid, "queuing");
289
+ try {
290
+ if (request.scheduledSendTime) {
291
+ await sendMessage(withReceipt.uid, { scheduledSendTime: request.scheduledSendTime });
292
+ return { kind: "scheduled" };
293
+ }
294
+ const result = await queueMessageSend(withReceipt.uid);
295
+ return { kind: result.queued ? "queued" : "sent" };
296
+ } catch (err) {
297
+ // A request that never came back may still have landed: never offer to send it twice if it did.
298
+ if (!(err instanceof ApiRequestError) && (await alreadyAccepted(request))) {
299
+ return { kind: request.scheduledSendTime ? "scheduled" : "queued" };
300
+ }
301
+ throw err;
302
+ }
303
+ } catch (err) {
304
+ return { kind: "failed", failure: failureOf(err, request.scheduledSendTime ? "Could not schedule this message." : "Could not send this message.") };
305
+ }
306
+ }
307
+
308
+ function recipientSummary(request: SendRequest): string {
309
+ const all = [...request.to, ...request.cc, ...request.bcc].map((recipient) => recipient.address);
310
+ return all.length <= 2 ? all.join(" and ") : `${all[0]} and ${all.length - 1} others`;
311
+ }
312
+
313
+ /** "Message to a@b.c and 2 others (\"Subject\")" - which message a pop-up is about. */
314
+ export function describeMessage(subject: string, recipients: string): string {
315
+ return `${recipients ? `To ${recipients}` : "Message"}${subject ? ` - "${subject}"` : ""}`;
316
+ }
317
+
318
+ /** Re-opens the compose window around a request's message, with everything as it was typed. */
319
+ export function openDraftFromRequest(request: SendRequest): boolean {
320
+ const opened = openComposeFromOutside({
321
+ mailboxUid: request.mailboxUid,
322
+ resume: {
323
+ draft: request.draft,
324
+ mailboxUid: request.mailboxUid,
325
+ to: request.toText,
326
+ cc: request.ccText,
327
+ bcc: request.bccText,
328
+ subject: request.subject,
329
+ html: request.html,
330
+ attachments: request.attachments,
331
+ requestReceipt: request.requestReceipt,
332
+ signEnabled: request.signEnabled,
333
+ encryptRequested: request.encryptRequested,
334
+ },
335
+ });
336
+ // Being edited again, it is no longer a message on its way in the conversation.
337
+ if (opened) {
338
+ forgetOutgoing(request.draft.uid);
339
+ }
340
+ return opened;
341
+ }
342
+
343
+ function failureNotificationId(draftUid: string): string {
344
+ return `send-failed:${draftUid}`;
345
+ }
346
+
347
+ /** The sticky "This message wasn't sent" pop-up for a send that failed on this side, with what can be done about it. */
348
+ function notifyFailure(request: SendRequest, failure: Failure): void {
349
+ const uid = request.draft.uid;
350
+ const actions: NotificationAction[] = [];
351
+ const { block } = failure;
352
+ if (block?.keysLocked && request.mailbox?.keys?.length) {
353
+ actions.push({
354
+ label: "Unlock",
355
+ onClick: () => {
356
+ void requestUnlockFromOutside(request.mailboxUid, request.mailbox!.keys!).then(
357
+ () => void retrySend(request),
358
+ () => undefined,
359
+ );
360
+ },
361
+ });
362
+ }
363
+ if (block) {
364
+ actions.push({ label: block.overrideLabel, onClick: () => void retrySend({ ...request, forcePlaintext: true }) });
365
+ } else {
366
+ actions.push({ label: "Retry", onClick: () => void retrySend(request) });
367
+ }
368
+ actions.push({ label: "Open draft", onClick: () => void openDraftFromRequest(request) });
369
+ notify({
370
+ id: failureNotificationId(uid),
371
+ kind: "error",
372
+ title: "This message wasn't sent",
373
+ message: `${describeMessage(request.subject, recipientSummary(request))}: ${failure.message}`,
374
+ details: failure.details,
375
+ actions,
376
+ });
377
+ // The conversation on screen shows the same failure under the message, with the same ways out.
378
+ failOutgoing(uid, failure.message, actions);
379
+ }
380
+
381
+ const SENT_BURST_MS = 6_000;
382
+
383
+ /** The short "Message sent" confirmation - several sent close together are one pop-up counting up, never a stack of them. */
384
+ export function notifySent(message = "Message sent"): void {
385
+ const now = Date.now();
386
+ const { sentBurst } = sendState;
387
+ sendState.sentBurst = { count: now - sentBurst.at > SENT_BURST_MS ? 1 : sentBurst.count + 1, at: now };
388
+ notify({ id: "message-sent", kind: "success", title: sendState.sentBurst.count > 1 ? `${sendState.sentBurst.count} messages sent` : message, timeoutMs: 4_000 });
389
+ }
390
+
391
+ /**
392
+ * Sends `request`'s draft in the background and returns at once, `true` - or `false` (doing nothing) when a send of this draft is already
393
+ * under way here. The outcome is shown as pop-ups and the Outbox indicator, never as a window that waits: a failure at any stage (assembling,
394
+ * encrypting, the request) is a sticky "This message wasn't sent" with the reason, and Retry / Open draft; the server's own later outcome
395
+ * (`send-succeeded`, `send-failed`, `send-retrying`) is `handleSendEvent()`'s.
396
+ */
397
+ export function startSend(request: SendRequest): boolean {
398
+ const uid = request.draft.uid;
399
+ const recipients = [...request.to, ...request.cc, ...request.bcc].map((recipient) => recipient.address);
400
+ if (!beginPendingSend({ draftUid: uid, mailboxUid: request.mailboxUid, subject: request.subject, recipients, scheduled: !!request.scheduledSendTime })) {
401
+ return false;
402
+ }
403
+ // The failure of an earlier attempt is resolved by trying again.
404
+ dismiss(failureNotificationId(uid));
405
+ // A reply or forward is on screen in its conversation from this moment, before any of the work below.
406
+ trackOutgoing(request);
407
+ const tracker = sendState.countTracker?.(request.mailboxUid);
408
+ void attempt(request).then((outcome) => {
409
+ finishPendingSend(uid);
410
+ if (outcome.kind === "failed") {
411
+ tracker?.revert();
412
+ notifyFailure(request, outcome.failure);
413
+ return;
414
+ }
415
+ tracker?.settle();
416
+ if (outcome.kind === "queued") {
417
+ retain(request);
418
+ sendState.queuedListener?.(request.mailboxUid);
419
+ } else if (outcome.kind === "sent") {
420
+ // A server with no queue relayed it before answering: the Sent Items copy exists already.
421
+ markOutgoingSent(uid);
422
+ notifySent();
423
+ } else {
424
+ notify({
425
+ id: `scheduled:${uid}`,
426
+ kind: "success",
427
+ title: "Message scheduled",
428
+ message: `It will be sent ${new Date(request.scheduledSendTime!).toLocaleString()}.`,
429
+ timeoutMs: 5_000,
430
+ });
431
+ }
432
+ });
433
+ return true;
434
+ }
435
+
436
+ /** Tries a failed send again - unless the server already has the message (an earlier request that seemed to fail did land), which it must not send twice. */
437
+ export async function retrySend(request: SendRequest): Promise<void> {
438
+ if (await alreadyAccepted(request)) {
439
+ dismiss(failureNotificationId(request.draft.uid));
440
+ markOutgoingSending(request.draft.uid);
441
+ notify({ id: `already-sent:${request.draft.uid}`, kind: "info", title: "This message is already on its way", timeoutMs: 5_000 });
442
+ return;
443
+ }
444
+ startSend({ ...request, saved: undefined });
445
+ }