@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,562 @@
1
+ import { useEffect, useState, useSyncExternalStore } from "react";
2
+ import { toast } from "sonner";
3
+
4
+ import {
5
+ composerAttachmentLimitError,
6
+ EMAIL_SERVICE_MAX_BYTES,
7
+ } from "../../shared/mail";
8
+ import {
9
+ completeComposerUpload,
10
+ createComposerUploadIntent,
11
+ discardComposerUpload,
12
+ isInlineComposerImage,
13
+ uploadComposerFile,
14
+ uploadContentType,
15
+ } from "./composer-upload-client";
16
+ import { createComposerUploadProgressStore } from "./composer-upload-progress";
17
+
18
+ export type ComposerAssetIntent = "attachment" | "inline";
19
+
20
+ type ComposerAssetStatus = "uploading" | "uploaded" | "error";
21
+
22
+ export type ComposerAsset = {
23
+ id: string;
24
+ uploadId: string | null;
25
+ filename: string;
26
+ contentType: string;
27
+ size: number;
28
+ intent: ComposerAssetIntent;
29
+ contentId: string | null;
30
+ previewUrl: string | null;
31
+ status: ComposerAssetStatus;
32
+ error: string | null;
33
+ };
34
+
35
+ /** An asset whose upload finished, so it has the upload's id. */
36
+ export type UploadedComposerAsset = ComposerAsset & { uploadId: string };
37
+
38
+ export function isUploadedAsset(
39
+ asset: ComposerAsset
40
+ ): asset is UploadedComposerAsset {
41
+ return asset.status === "uploaded" && Boolean(asset.uploadId);
42
+ }
43
+
44
+ export type SubmittedComposerUpload = {
45
+ uploadId: string;
46
+ disposition: ComposerAssetIntent;
47
+ contentId?: string;
48
+ };
49
+
50
+ export type ComposerSessionPhase =
51
+ | "editing"
52
+ | "preflighting"
53
+ | "submitting"
54
+ | "closed";
55
+
56
+ export function isComposerSessionBusy(phase: ComposerSessionPhase) {
57
+ return phase === "preflighting" || phase === "submitting";
58
+ }
59
+
60
+ type ComposerSessionSnapshot = {
61
+ assets: readonly ComposerAsset[];
62
+ phase: ComposerSessionPhase;
63
+ planError: boolean;
64
+ linkedAssetIds: ReadonlySet<string>;
65
+ };
66
+
67
+ type Listener = () => void;
68
+
69
+ const EMPTY_RESERVED_ASSETS: readonly { size: number }[] = [];
70
+ const EMPTY_LINKED_ASSETS: ReadonlySet<string> = new Set();
71
+
72
+ /**
73
+ * Owns every attachment lifecycle transition. React and ProseMirror only read
74
+ * projections of this state; neither keeps a second mutable upload record.
75
+ */
76
+ export class ComposerSession {
77
+ readonly progress = createComposerUploadProgressStore();
78
+
79
+ private snapshot: ComposerSessionSnapshot = {
80
+ assets: [],
81
+ phase: "editing",
82
+ planError: false,
83
+ linkedAssetIds: EMPTY_LINKED_ASSETS,
84
+ };
85
+ private readonly listeners = new Set<Listener>();
86
+ private readonly files = new Map<string, File>();
87
+ private readonly requests = new Map<string, XMLHttpRequest>();
88
+ private readonly operations = new Map<string, string>();
89
+ private claimedAssetIds: ReadonlySet<string> = EMPTY_LINKED_ASSETS;
90
+ private planKey: string | null = null;
91
+ private submissionAttempt: { id: string; key: string } | null = null;
92
+ private owners = 0;
93
+ private disposed = false;
94
+
95
+ constructor(
96
+ readonly mailboxId: string,
97
+ private readonly reservedAssets: readonly {
98
+ size: number;
99
+ }[] = EMPTY_RESERVED_ASSETS
100
+ ) {}
101
+
102
+ getSnapshot = () => this.snapshot;
103
+
104
+ subscribe = (listener: Listener) => {
105
+ this.listeners.add(listener);
106
+
107
+ return () => this.listeners.delete(listener);
108
+ };
109
+
110
+ attach() {
111
+ this.owners += 1;
112
+
113
+ return () => {
114
+ this.owners -= 1;
115
+ queueMicrotask(() => {
116
+ if (this.owners === 0) this.close();
117
+ });
118
+ };
119
+ }
120
+
121
+ getAsset(id: string) {
122
+ return this.snapshot.assets.find((asset) => asset.id === id);
123
+ }
124
+
125
+ isLinked(id: string) {
126
+ return this.snapshot.linkedAssetIds.has(id);
127
+ }
128
+
129
+ limitError() {
130
+ return composerAttachmentLimitError([
131
+ ...this.snapshot.assets,
132
+ ...this.reservedAssets,
133
+ ]);
134
+ }
135
+
136
+ addFiles(
137
+ selected: Iterable<File>,
138
+ intent: ComposerAssetIntent
139
+ ): ComposerAsset[] | null {
140
+ if (this.snapshot.phase !== "editing") {
141
+ toast.error("Wait for the message to finish sending");
142
+
143
+ return null;
144
+ }
145
+
146
+ const incoming = Array.from(selected);
147
+
148
+ if (!incoming.length) return null;
149
+
150
+ const accepted =
151
+ intent === "inline" ? incoming.filter(isInlineComposerImage) : incoming;
152
+
153
+ if (accepted.length !== incoming.length) {
154
+ toast.error("Inline images must be PNG, JPEG, GIF, or WebP");
155
+ }
156
+
157
+ if (!accepted.length) return null;
158
+
159
+ const limitError = composerAttachmentLimitError([
160
+ ...this.snapshot.assets,
161
+ ...this.reservedAssets,
162
+ ...accepted.map((file) => ({ size: file.size })),
163
+ ]);
164
+
165
+ if (limitError) {
166
+ toast.error(limitError);
167
+
168
+ return null;
169
+ }
170
+
171
+ const uploads = accepted.map((file) => {
172
+ const id = crypto.randomUUID();
173
+ this.files.set(id, file);
174
+
175
+ const asset: ComposerAsset = {
176
+ id,
177
+ uploadId: null,
178
+ filename: file.name || "attachment",
179
+ contentType: uploadContentType(file),
180
+ size: file.size,
181
+ intent,
182
+ contentId:
183
+ intent === "inline" ? `inline-${id}@openworkspace.local` : null,
184
+ // Files larger than the transport ceiling can only become links. Do
185
+ // not ask the browser to decode a potentially 500 MB image meanwhile.
186
+ previewUrl:
187
+ intent === "inline" && file.size <= EMAIL_SERVICE_MAX_BYTES
188
+ ? URL.createObjectURL(file)
189
+ : null,
190
+ status: "uploading",
191
+ error: null,
192
+ };
193
+
194
+ return { asset, file };
195
+ });
196
+
197
+ const pending = uploads.map(({ asset }) => asset);
198
+
199
+ this.publish({
200
+ ...this.snapshot,
201
+ assets: [...this.snapshot.assets, ...pending],
202
+ });
203
+
204
+ for (const { asset, file } of uploads) {
205
+ void this.startUpload(asset.id, file);
206
+ }
207
+
208
+ return pending;
209
+ }
210
+
211
+ retry = async (assetId: string) => {
212
+ if (this.snapshot.phase !== "editing") {
213
+ toast.error("Wait for the message to finish sending");
214
+
215
+ return null;
216
+ }
217
+
218
+ const asset = this.getAsset(assetId);
219
+ const file = this.files.get(assetId);
220
+
221
+ if (!asset || !file || this.operations.has(assetId)) return null;
222
+ const operationId = crypto.randomUUID();
223
+ this.operations.set(assetId, operationId);
224
+ this.requests.get(assetId)?.abort();
225
+ this.requests.delete(assetId);
226
+ this.replaceAsset(assetId, {
227
+ ...asset,
228
+ uploadId: null,
229
+ status: "uploading",
230
+ error: null,
231
+ });
232
+
233
+ if (asset.uploadId) await this.safeDiscard(asset.uploadId);
234
+
235
+ if (!this.isCurrent(assetId, operationId)) return null;
236
+ this.operations.delete(assetId);
237
+
238
+ return this.startUpload(assetId, file);
239
+ };
240
+
241
+ remove = (assetId: string) => {
242
+ if (this.snapshot.phase !== "editing") {
243
+ toast.error("Wait for the message to finish sending");
244
+
245
+ return;
246
+ }
247
+
248
+ const asset = this.getAsset(assetId);
249
+
250
+ if (!asset) return;
251
+ this.operations.delete(assetId);
252
+ this.requests.get(assetId)?.abort();
253
+ this.requests.delete(assetId);
254
+ this.files.delete(assetId);
255
+ this.progress.delete(assetId);
256
+
257
+ if (asset.previewUrl) URL.revokeObjectURL(asset.previewUrl);
258
+
259
+ if (asset.uploadId) void this.safeDiscard(asset.uploadId);
260
+ const linkedAssetIds = new Set(this.snapshot.linkedAssetIds);
261
+ linkedAssetIds.delete(assetId);
262
+ this.publish({
263
+ ...this.snapshot,
264
+ assets: this.snapshot.assets.filter(
265
+ (candidate) => candidate.id !== assetId
266
+ ),
267
+ linkedAssetIds,
268
+ });
269
+ };
270
+
271
+ beginPlan(planKey: string) {
272
+ if (
273
+ this.snapshot.phase === "submitting" ||
274
+ this.snapshot.phase === "closed"
275
+ ) {
276
+ return false;
277
+ }
278
+
279
+ this.planKey = planKey;
280
+
281
+ return true;
282
+ }
283
+
284
+ resolvePlan(planKey: string, linkedAssetIds: Iterable<string>) {
285
+ if (this.planKey !== planKey) return false;
286
+ const nextLinkedAssetIds = new Set(linkedAssetIds);
287
+
288
+ const linkedAssetsChanged = !setsEqual(
289
+ this.snapshot.linkedAssetIds,
290
+ nextLinkedAssetIds
291
+ );
292
+
293
+ if (!this.snapshot.planError && !linkedAssetsChanged) return true;
294
+ this.publish({
295
+ ...this.snapshot,
296
+ planError: false,
297
+ linkedAssetIds: linkedAssetsChanged
298
+ ? nextLinkedAssetIds
299
+ : this.snapshot.linkedAssetIds,
300
+ });
301
+
302
+ return true;
303
+ }
304
+
305
+ failPlan(planKey: string) {
306
+ if (this.planKey !== planKey || this.snapshot.planError) return;
307
+ this.publish({ ...this.snapshot, planError: true });
308
+ }
309
+
310
+ beginPreflight() {
311
+ if (this.snapshot.phase !== "editing") return false;
312
+ this.publish({ ...this.snapshot, phase: "preflighting" });
313
+
314
+ return true;
315
+ }
316
+
317
+ cancelPreflight() {
318
+ if (this.snapshot.phase !== "preflighting" || this.disposed) return;
319
+ this.publish({ ...this.snapshot, phase: "editing" });
320
+ }
321
+
322
+ beginSubmission(assetIds: Iterable<string>, submissionKey: string) {
323
+ if (this.snapshot.phase !== "preflighting") return null;
324
+ this.claimedAssetIds = new Set(assetIds);
325
+
326
+ if (this.submissionAttempt?.key !== submissionKey) {
327
+ this.submissionAttempt = {
328
+ id: crypto.randomUUID(),
329
+ key: submissionKey,
330
+ };
331
+ }
332
+
333
+ this.publish({ ...this.snapshot, phase: "submitting" });
334
+
335
+ return this.submissionAttempt.id;
336
+ }
337
+
338
+ releaseSubmission(preserveAttempt = false) {
339
+ const claimed = this.claimedAssetIds;
340
+ this.claimedAssetIds = EMPTY_LINKED_ASSETS;
341
+
342
+ if (!preserveAttempt) this.submissionAttempt = null;
343
+
344
+ if (this.disposed) {
345
+ for (const asset of this.snapshot.assets) {
346
+ if (claimed.has(asset.id) && asset.uploadId) {
347
+ void this.safeDiscard(asset.uploadId);
348
+ }
349
+ }
350
+
351
+ return;
352
+ }
353
+
354
+ this.publish({ ...this.snapshot, phase: "editing" });
355
+ }
356
+
357
+ completeSubmission() {
358
+ const claimed = this.claimedAssetIds;
359
+ this.claimedAssetIds = EMPTY_LINKED_ASSETS;
360
+ this.submissionAttempt = null;
361
+ // Accepted uploads are now Worker-owned. Only retained undo assets that
362
+ // were not part of the frozen submission snapshot are client-cleaned.
363
+ this.disposeAssets((asset) => !claimed.has(asset.id));
364
+ this.publish({ ...this.snapshot, assets: [], phase: "closed" });
365
+ this.disposed = true;
366
+ }
367
+
368
+ close = () => {
369
+ if (this.disposed) return;
370
+ this.disposed = true;
371
+ const claimed = this.claimedAssetIds;
372
+ this.disposeAssets((asset) => !claimed.has(asset.id));
373
+ this.publish({ ...this.snapshot, phase: "closed" });
374
+ };
375
+
376
+ private startUpload = async (
377
+ assetId: string,
378
+ file: File
379
+ ): Promise<ComposerAsset | null> => {
380
+ const operationId = crypto.randomUUID();
381
+ this.operations.set(assetId, operationId);
382
+ let uploadId: string | null = null;
383
+
384
+ try {
385
+ const asset = this.getAsset(assetId);
386
+
387
+ if (!asset) return null;
388
+
389
+ const intent = await createComposerUploadIntent(this.mailboxId, {
390
+ filename: asset.filename,
391
+ contentType: asset.contentType,
392
+ size: asset.size,
393
+ });
394
+
395
+ uploadId = intent.upload.id;
396
+
397
+ if (!this.isCurrent(assetId, operationId)) {
398
+ await this.safeDiscard(uploadId);
399
+
400
+ return null;
401
+ }
402
+
403
+ this.replaceAsset(assetId, { ...asset, uploadId });
404
+ await uploadComposerFile(
405
+ intent.upload.uploadUrl,
406
+ intent.upload.headers,
407
+ file,
408
+ (progress) => {
409
+ if (this.isCurrent(assetId, operationId)) {
410
+ this.progress.set(assetId, progress);
411
+ }
412
+ },
413
+ (request) => {
414
+ if (this.isCurrent(assetId, operationId)) {
415
+ this.requests.set(assetId, request);
416
+ } else {
417
+ request.abort();
418
+ }
419
+ }
420
+ );
421
+ await completeComposerUpload(this.mailboxId, uploadId);
422
+ this.requests.delete(assetId);
423
+
424
+ if (!this.isCurrent(assetId, operationId)) {
425
+ // A DELETE issued during close can finish before /complete seals its
426
+ // immutable object. This second idempotent DELETE closes that race.
427
+ await this.safeDiscard(uploadId);
428
+
429
+ return null;
430
+ }
431
+
432
+ const current = this.getAsset(assetId);
433
+
434
+ if (!current) {
435
+ await this.safeDiscard(uploadId);
436
+
437
+ return null;
438
+ }
439
+
440
+ const completed: ComposerAsset = {
441
+ ...current,
442
+ uploadId,
443
+ status: "uploaded",
444
+ error: null,
445
+ };
446
+
447
+ this.replaceAsset(assetId, completed);
448
+
449
+ return completed;
450
+ } catch (error) {
451
+ this.requests.delete(assetId);
452
+
453
+ if (!this.isCurrent(assetId, operationId)) {
454
+ if (uploadId) await this.safeDiscard(uploadId);
455
+
456
+ return null;
457
+ }
458
+
459
+ if (error instanceof DOMException && error.name === "AbortError") {
460
+ return null;
461
+ }
462
+
463
+ const current = this.getAsset(assetId);
464
+
465
+ if (!current) return null;
466
+ this.replaceAsset(assetId, {
467
+ ...current,
468
+ uploadId,
469
+ status: "error",
470
+ error:
471
+ error instanceof Error ? error.message : "Attachment upload failed",
472
+ });
473
+
474
+ return null;
475
+ } finally {
476
+ if (this.operations.get(assetId) === operationId) {
477
+ this.operations.delete(assetId);
478
+ }
479
+ }
480
+ };
481
+
482
+ private isCurrent(assetId: string, operationId: string) {
483
+ return (
484
+ !this.disposed &&
485
+ this.operations.get(assetId) === operationId &&
486
+ Boolean(this.getAsset(assetId))
487
+ );
488
+ }
489
+
490
+ private replaceAsset(assetId: string, next: ComposerAsset) {
491
+ if (!this.getAsset(assetId)) return;
492
+ this.publish({
493
+ ...this.snapshot,
494
+ assets: this.snapshot.assets.map((asset) =>
495
+ asset.id === assetId ? next : asset
496
+ ),
497
+ });
498
+ }
499
+
500
+ private disposeAssets(shouldDiscard: (asset: ComposerAsset) => boolean) {
501
+ this.operations.clear();
502
+
503
+ for (const request of this.requests.values()) request.abort();
504
+ this.requests.clear();
505
+
506
+ for (const asset of this.snapshot.assets) {
507
+ this.files.delete(asset.id);
508
+ this.progress.delete(asset.id);
509
+
510
+ if (asset.previewUrl) URL.revokeObjectURL(asset.previewUrl);
511
+
512
+ if (shouldDiscard(asset) && asset.uploadId) {
513
+ void this.safeDiscard(asset.uploadId);
514
+ }
515
+ }
516
+ }
517
+
518
+ private async safeDiscard(uploadId: string) {
519
+ try {
520
+ await discardComposerUpload(this.mailboxId, uploadId);
521
+ } catch {
522
+ // R2 lifecycle expiration is the final safety net for failed cleanup.
523
+ }
524
+ }
525
+
526
+ private publish(next: ComposerSessionSnapshot) {
527
+ this.snapshot = next;
528
+
529
+ for (const listener of this.listeners) listener();
530
+ }
531
+ }
532
+
533
+ function setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>) {
534
+ if (left.size !== right.size) return false;
535
+
536
+ for (const value of left) {
537
+ if (!right.has(value)) return false;
538
+ }
539
+
540
+ return true;
541
+ }
542
+
543
+ export function useComposerSession(
544
+ mailboxId: string,
545
+ reservedAssets?: readonly { size: number }[]
546
+ ) {
547
+ // One session for the composer's lifetime: created once, never replaced.
548
+ // oxlint-disable-next-line react/hook-use-state -- the lazy initializer keeps one instance; there is nothing to set
549
+ const [session] = useState(
550
+ () => new ComposerSession(mailboxId, reservedAssets)
551
+ );
552
+
553
+ const snapshot = useSyncExternalStore(
554
+ session.subscribe,
555
+ session.getSnapshot,
556
+ session.getSnapshot
557
+ );
558
+
559
+ useEffect(() => session.attach(), [session]);
560
+
561
+ return { session, snapshot };
562
+ }