@open-workspace/email 0.4.1 → 0.4.2

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.
@@ -16,9 +16,11 @@ import {
16
16
  desc,
17
17
  eq,
18
18
  inArray,
19
+ isNotNull,
19
20
  isNull,
20
21
  lt,
21
22
  lte,
23
+ ne,
22
24
  or,
23
25
  sql,
24
26
  } from "drizzle-orm";
@@ -92,7 +94,7 @@ import {
92
94
  workspaceBlockPatterns,
93
95
  workspaceFeedbackSummary,
94
96
  } from "../mail/workspace-safety";
95
- import { indexInsertedEmail } from "./email-index";
97
+ import { indexInsertedEmail, mergeConversation } from "./email-index";
96
98
  import {
97
99
  customFolderPredicate,
98
100
  folderAggregateJoinPredicate,
@@ -178,6 +180,10 @@ const INBOUND_ALARM_BATCH_SIZE = 1;
178
180
  const OBJECT_DELETION_ALARM_BATCH_SIZE = 100;
179
181
  const MAX_RETRY_DELAY_MS = 60 * 60 * 1000;
180
182
  const MAX_INBOUND_RETRY_AGE_MS = 24 * 60 * 60 * 1000;
183
+
184
+ /** Attempts a delivery may end without an outcome (alarm killed) before it is stored unparsed. */
185
+ const MAX_UNFINISHED_INBOUND_ATTEMPTS = 3;
186
+
181
187
  const ALARM_WAKE_DELAY_MS = 1000;
182
188
  const PRESENCE_TTL_MS = 60_000;
183
189
  const AI_CONFIGURATION_ID = "default";
@@ -231,6 +237,24 @@ function retryDelay(attempts: number) {
231
237
  );
232
238
  }
233
239
 
240
+ /**
241
+ * The folder a conversation is listed in, as the app names it: its custom
242
+ * folder or Inbox while active, else Archive, Spam or Trash.
243
+ */
244
+ function conversationFolder(place: {
245
+ mailboxState: MailboxState;
246
+ folderId: string | null;
247
+ }) {
248
+ if (place.mailboxState !== "active") return place.mailboxState;
249
+
250
+ return place.folderId ?? "inbox";
251
+ }
252
+
253
+ /** Whether a delivery has been retried for as long as it may be. */
254
+ function isPastRetryAge(job: PendingInbound, now: number) {
255
+ return now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS;
256
+ }
257
+
234
258
  function stringListJson(values: string[]) {
235
259
  return JSON.stringify([...new Set(values)]);
236
260
  }
@@ -434,6 +458,11 @@ export class MailboxDO extends DurableObject<Env> {
434
458
  private writtenCounts: InboxCounts | null = null;
435
459
  /** The D1 bookmark after that write; realtime messages pass it on. */
436
460
  private countsBookmark: string | null = null;
461
+ /**
462
+ * The wake this alarm set before parsing a delivery, for when it is killed
463
+ * mid-parse; replaced by the real next wake once the attempt finishes.
464
+ */
465
+ private attemptAlarmAt: number | null = null;
437
466
 
438
467
  constructor(ctx: DurableObjectState, env: Env) {
439
468
  super(ctx, env);
@@ -784,7 +813,7 @@ export class MailboxDO extends DurableObject<Env> {
784
813
  now: number,
785
814
  cause: unknown
786
815
  ) {
787
- if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
816
+ if (isPastRetryAge(job, now)) {
788
817
  this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
789
818
  console.error(
790
819
  `Stopped retrying notification for inbound delivery ${job.id}`,
@@ -1257,7 +1286,25 @@ export class MailboxDO extends DurableObject<Env> {
1257
1286
  }
1258
1287
 
1259
1288
  jmapMoveEmails(emailIds: string[], target: string) {
1260
- const moved = jmapMoveEmails(this.state.storage.sql, emailIds, target);
1289
+ const moved = this.db.transaction(() => {
1290
+ const known = jmapMoveEmails(this.state.storage.sql, emailIds, target);
1291
+
1292
+ if (known) {
1293
+ // Mail kept out of a conversation as spam rejoins it once moved out of Junk.
1294
+ this.rejoinSplitConversations(
1295
+ this.db
1296
+ .selectDistinct({ id: emails.conversationId })
1297
+ .from(emails)
1298
+ .where(
1299
+ sql`${emails.id} in (select cast(value as text) from json_each(${stringListJson(emailIds)}))`
1300
+ )
1301
+ .all()
1302
+ .map((row) => row.id)
1303
+ );
1304
+ }
1305
+
1306
+ return known;
1307
+ });
1261
1308
 
1262
1309
  if (moved) this.publishUpdate();
1263
1310
 
@@ -1854,6 +1901,10 @@ export class MailboxDO extends DurableObject<Env> {
1854
1901
  return result.length > 0;
1855
1902
  });
1856
1903
 
1904
+ // An alarm finishing meanwhile may have dropped its own wake (see
1905
+ // `scheduleRemainingWork`) before it could see this row.
1906
+ if (queued) await this.scheduleAlarm(alarmAt);
1907
+
1857
1908
  return { messageId, queued };
1858
1909
  }
1859
1910
 
@@ -2333,9 +2384,31 @@ export class MailboxDO extends DurableObject<Env> {
2333
2384
  classification: EmailAiClassification | null,
2334
2385
  placement: InboundPlacement
2335
2386
  ) {
2336
- const email = prepareOfficePreviews(input);
2387
+ const prepared = prepareOfficePreviews(input);
2337
2388
 
2338
2389
  const stored = this.db.transaction((tx) => {
2390
+ // Threading trusts the sender's In-Reply-To and References, so spam
2391
+ // that names a message here starts its own conversation instead of
2392
+ // moving (or reviving) one with other mail. Spam may join spam.
2393
+ const joined = placement.state
2394
+ ? tx
2395
+ .select({ mailboxState: conversations.mailboxState })
2396
+ .from(conversations)
2397
+ .where(eq(conversations.id, prepared.conversationId))
2398
+ .all()[0]
2399
+ : undefined;
2400
+
2401
+ // The conversation it named is recorded, so the message rejoins it
2402
+ // when it leaves Spam (rejoinSplitConversations).
2403
+ const email =
2404
+ joined && joined.mailboxState !== placement.state
2405
+ ? {
2406
+ ...prepared,
2407
+ conversationId: createId("conv"),
2408
+ splitFromConversationId: prepared.conversationId,
2409
+ }
2410
+ : prepared;
2411
+
2339
2412
  const trustedFolder = placement.folderId
2340
2413
  ? tx
2341
2414
  .select({ id: folders.id })
@@ -2374,12 +2447,29 @@ export class MailboxDO extends DurableObject<Env> {
2374
2447
  eq(conversations.mailboxState, "active")
2375
2448
  );
2376
2449
 
2450
+ // AI sorting files only the first incoming message of a conversation:
2451
+ // a reply to received mail (whose threading headers the sender chose)
2452
+ // leaves the thread where it is. Replies to a thread this mailbox
2453
+ // started are filed like new mail.
2454
+ const startsConversation = !tx
2455
+ .select({ id: emails.id })
2456
+ .from(emails)
2457
+ .where(
2458
+ and(
2459
+ eq(emails.conversationId, email.conversationId),
2460
+ eq(emails.direction, "incoming"),
2461
+ ne(emails.id, inserted.id)
2462
+ )
2463
+ )
2464
+ .limit(1)
2465
+ .all()[0];
2466
+
2377
2467
  if (placement.state) {
2378
2468
  tx.update(conversations)
2379
2469
  .set({ mailboxState: placement.state, folderId: null })
2380
2470
  .where(activeConversation)
2381
2471
  .run();
2382
- } else if (trustedFolder) {
2472
+ } else if (trustedFolder && startsConversation) {
2383
2473
  tx.update(conversations)
2384
2474
  .set({ folderId: trustedFolder.id })
2385
2475
  .where(and(activeConversation, isNull(conversations.folderId)))
@@ -2647,7 +2737,7 @@ export class MailboxDO extends DurableObject<Env> {
2647
2737
  const address = email.fromJson[0]?.address ?? "";
2648
2738
  const label: FeedbackLabel = "not_spam";
2649
2739
 
2650
- const restored = this.db.transaction((tx) => {
2740
+ const outcome = this.db.transaction((tx) => {
2651
2741
  tx.update(emails)
2652
2742
  .set({ reportLabel: null })
2653
2743
  .where(eq(emails.conversationId, email.conversationId))
@@ -2665,7 +2755,7 @@ export class MailboxDO extends DurableObject<Env> {
2665
2755
  setSenderTrusted(this.state.storage.sql, address, true, Date.now());
2666
2756
  }
2667
2757
 
2668
- return (
2758
+ const back =
2669
2759
  tx
2670
2760
  .update(conversations)
2671
2761
  .set({ mailboxState: "active" })
@@ -2676,14 +2766,170 @@ export class MailboxDO extends DurableObject<Env> {
2676
2766
  )
2677
2767
  )
2678
2768
  .returning({ id: conversations.id })
2679
- .all().length > 0
2680
- );
2769
+ .all().length > 0;
2770
+
2771
+ // Spam that named a conversation here was kept out of it; once it is
2772
+ // not spam, it rejoins that conversation.
2773
+ const conversationId = back
2774
+ ? (this.rejoinSplitConversations([email.conversationId]).get(
2775
+ email.conversationId
2776
+ ) ?? email.conversationId)
2777
+ : email.conversationId;
2778
+
2779
+ const place = tx
2780
+ .select({
2781
+ mailboxState: conversations.mailboxState,
2782
+ folderId: conversations.folderId,
2783
+ })
2784
+ .from(conversations)
2785
+ .where(eq(conversations.id, conversationId))
2786
+ .all()[0];
2787
+
2788
+ return {
2789
+ restored: back,
2790
+ conversationId,
2791
+ folder: place ? conversationFolder(place) : "inbox",
2792
+ };
2681
2793
  });
2682
2794
 
2683
2795
  this.recentParticipantSources = null;
2684
2796
  this.publishUpdate();
2685
2797
 
2686
- return { restored, address: address.includes("@") ? address : null };
2798
+ return {
2799
+ restored: outcome.restored,
2800
+ conversationId: outcome.conversationId,
2801
+ rejoined: outcome.conversationId !== email.conversationId,
2802
+ folder: outcome.folder,
2803
+ address: address.includes("@") ? address : null,
2804
+ };
2805
+ }
2806
+
2807
+ /**
2808
+ * Puts mail kept out of a conversation as spam (#25) back into it, once
2809
+ * its own conversation has left Spam: by Not spam, a move in the app or
2810
+ * over JMAP, or a reply sent from here. Call it inside the transaction
2811
+ * that moved `conversationIds`; only those now in Inbox or Archive that
2812
+ * hold a message marked with `split_from_conversation_id` are touched, so
2813
+ * conversations threaded elsewhere (an import's, say) are never merged.
2814
+ *
2815
+ * The marked message names the conversation it was kept out of. When that
2816
+ * conversation is gone, the message's own threading headers are resolved
2817
+ * again. The conversation rejoins its target when the target is in Inbox
2818
+ * or Archive; a target in Trash or Spam is not brought back by it, and the
2819
+ * conversation stays where it was moved. Either way the decision is final
2820
+ * and the mark is cleared.
2821
+ *
2822
+ * The rescued message is placed as a legitimate reply would be: moved to
2823
+ * Inbox (or a custom folder), the target becomes active and takes that
2824
+ * folder (else keeps its own). Moved to Archive, the target stays where it
2825
+ * is. Returns, for each merged conversation, the one its messages are in.
2826
+ */
2827
+ private rejoinSplitConversations(conversationIds: string[]) {
2828
+ const merged = new Map<string, string>();
2829
+
2830
+ if (!conversationIds.length) return merged;
2831
+
2832
+ const marked = this.db
2833
+ .select({
2834
+ emailId: emails.id,
2835
+ conversationId: conversations.id,
2836
+ mailboxState: conversations.mailboxState,
2837
+ folderId: conversations.folderId,
2838
+ splitFrom: emails.splitFromConversationId,
2839
+ inReplyTo: emails.inReplyToJson,
2840
+ references: emails.referencesJson,
2841
+ })
2842
+ .from(emails)
2843
+ .innerJoin(conversations, eq(conversations.id, emails.conversationId))
2844
+ .where(
2845
+ and(
2846
+ sql`${conversations.id} in (select cast(value as text) from json_each(${stringListJson(conversationIds)}))`,
2847
+ inArray(conversations.mailboxState, ["active", "archive"]),
2848
+ isNotNull(emails.splitFromConversationId)
2849
+ )
2850
+ )
2851
+ .all();
2852
+
2853
+ const groups = new Map<string, typeof marked>();
2854
+
2855
+ for (const row of marked) {
2856
+ groups.set(row.conversationId, [
2857
+ ...(groups.get(row.conversationId) ?? []),
2858
+ row,
2859
+ ]);
2860
+ }
2861
+
2862
+ for (const [conversationId, rows] of groups) {
2863
+ const targets = new Set(
2864
+ rows.map((row) => this.splitTarget(conversationId, row))
2865
+ );
2866
+
2867
+ const [target, ...others] = targets;
2868
+
2869
+ this.db
2870
+ .update(emails)
2871
+ .set({ splitFromConversationId: null })
2872
+ .where(
2873
+ and(
2874
+ eq(emails.conversationId, conversationId),
2875
+ isNotNull(emails.splitFromConversationId)
2876
+ )
2877
+ )
2878
+ .run();
2879
+
2880
+ if (!target || others.length) continue;
2881
+ const [moved] = rows;
2882
+
2883
+ if (!moved) continue;
2884
+ mergeConversation(this.state.storage.sql, conversationId, target);
2885
+
2886
+ if (moved.mailboxState === "active") {
2887
+ this.db
2888
+ .update(conversations)
2889
+ .set({
2890
+ mailboxState: "active",
2891
+ folderId: moved.folderId ?? sql`${conversations.folderId}`,
2892
+ })
2893
+ .where(eq(conversations.id, target))
2894
+ .run();
2895
+ }
2896
+
2897
+ merged.set(conversationId, target);
2898
+ }
2899
+
2900
+ return merged;
2901
+ }
2902
+
2903
+ /**
2904
+ * The conversation a marked message rejoins, or null: the one it was kept
2905
+ * out of, else (when that one is gone) its parent's, while that
2906
+ * conversation is in Inbox or Archive.
2907
+ */
2908
+ private splitTarget(
2909
+ conversationId: string,
2910
+ row: { splitFrom: string | null; inReplyTo: string[]; references: string[] }
2911
+ ) {
2912
+ const placeOf = (id: string) =>
2913
+ this.db
2914
+ .select({ mailboxState: conversations.mailboxState })
2915
+ .from(conversations)
2916
+ .where(eq(conversations.id, id))
2917
+ .all()[0];
2918
+
2919
+ let targetId = row.splitFrom;
2920
+ let target = targetId ? placeOf(targetId) : undefined;
2921
+
2922
+ if (!target) {
2923
+ const parent = this.resolveParent(row.inReplyTo, row.references);
2924
+ targetId = parent?.conversationId ?? null;
2925
+ target = targetId ? placeOf(targetId) : undefined;
2926
+ }
2927
+
2928
+ return targetId &&
2929
+ targetId !== conversationId &&
2930
+ (target?.mailboxState === "active" || target?.mailboxState === "archive")
2931
+ ? targetId
2932
+ : null;
2687
2933
  }
2688
2934
 
2689
2935
  submitOutgoing(input: NewEmail) {
@@ -2727,6 +2973,9 @@ export class MailboxDO extends DurableObject<Env> {
2727
2973
  indexInsertedEmail(this.state.storage.sql, email.id);
2728
2974
  insertOfficePreviewJobs(this.state.storage.sql, email);
2729
2975
  recordCorrespondents(this.state.storage.sql, email);
2976
+ // A reply sent from here brings its conversation out of Spam, and
2977
+ // mail kept out of a conversation as spam rejoins it.
2978
+ this.rejoinSplitConversations([email.conversationId]);
2730
2979
 
2731
2980
  const inserted = tx
2732
2981
  .select()
@@ -2913,11 +3162,12 @@ export class MailboxDO extends DurableObject<Env> {
2913
3162
  const targetPredicate =
2914
3163
  update.folderId === undefined ? "" : "and c.has_incoming = 1";
2915
3164
 
2916
- // Keep the source-folder guard in the update itself so a stale shared
2917
- // selection cannot overwrite a teammate's newer move.
2918
- const result = this.state.storage.sql
2919
- .exec<{ id: string }>(
2920
- `
3165
+ const result = this.db.transaction(() => {
3166
+ // Keep the source-folder guard in the update itself so a stale shared
3167
+ // selection cannot overwrite a teammate's newer move.
3168
+ const moved = this.state.storage.sql
3169
+ .exec<{ id: string }>(
3170
+ `
2921
3171
  update conversations as c
2922
3172
  set ${assignments.join(", ")}
2923
3173
  where c.id in (
@@ -2927,11 +3177,17 @@ export class MailboxDO extends DurableObject<Env> {
2927
3177
  ${targetPredicate}
2928
3178
  returning id
2929
3179
  `,
2930
- ...values,
2931
- candidatesJson,
2932
- ...membership.bindings
2933
- )
2934
- .toArray();
3180
+ ...values,
3181
+ candidatesJson,
3182
+ ...membership.bindings
3183
+ )
3184
+ .toArray();
3185
+
3186
+ // Mail kept out of a conversation as spam rejoins it once moved out of Spam.
3187
+ this.rejoinSplitConversations(moved.map((row) => row.id));
3188
+
3189
+ return moved;
3190
+ });
2935
3191
 
2936
3192
  if (result.length) this.publishUpdate();
2937
3193
 
@@ -3188,14 +3444,21 @@ export class MailboxDO extends DurableObject<Env> {
3188
3444
  async alarm() {
3189
3445
  const now = Date.now();
3190
3446
  await this.finishImport();
3191
- await this.processInboundJobs(now);
3192
- await dispatchOfficePreviewJobs(
3193
- this.state.storage.sql,
3194
- this.bindings,
3195
- this.state.id.name ?? "unknown-mailbox"
3196
- );
3447
+ // Object deletion runs first, so a delivery that keeps failing (or keeps
3448
+ // getting the alarm killed) cannot hold it back.
3197
3449
  await this.processObjectDeletionJobs(now);
3198
- await this.scheduleRemainingWork();
3450
+
3451
+ try {
3452
+ await this.processInboundJobs(now);
3453
+ } finally {
3454
+ // Previews of the mail just stored are queued in the same wake.
3455
+ await dispatchOfficePreviewJobs(
3456
+ this.state.storage.sql,
3457
+ this.bindings,
3458
+ this.state.id.name ?? "unknown-mailbox"
3459
+ );
3460
+ await this.scheduleRemainingWork();
3461
+ }
3199
3462
  }
3200
3463
 
3201
3464
  /**
@@ -3244,6 +3507,31 @@ export class MailboxDO extends DurableObject<Env> {
3244
3507
  return;
3245
3508
  }
3246
3509
 
3510
+ if (job.attempts > 0 && isPastRetryAge(job, now)) {
3511
+ // Earlier attempts ended without an outcome (the alarm was killed
3512
+ // mid-parse, say); this message is not parsed again.
3513
+ await this.storeUnparsedInbound(
3514
+ job,
3515
+ now,
3516
+ "Message processing did not finish within 24 hours"
3517
+ );
3518
+
3519
+ return;
3520
+ }
3521
+
3522
+ if (job.unfinishedAttempts >= MAX_UNFINISHED_INBOUND_ATTEMPTS) {
3523
+ // Processing it got the alarm killed every time: other mail goes first.
3524
+ await this.storeUnparsedInbound(
3525
+ job,
3526
+ now,
3527
+ `Message processing did not finish in ${MAX_UNFINISHED_INBOUND_ATTEMPTS} attempts`
3528
+ );
3529
+
3530
+ return;
3531
+ }
3532
+
3533
+ await this.recordInboundAttempt(job, now);
3534
+
3247
3535
  try {
3248
3536
  const rawMime = await readInboundRawMime(this.bindings, job);
3249
3537
 
@@ -3295,6 +3583,10 @@ export class MailboxDO extends DurableObject<Env> {
3295
3583
  this.db
3296
3584
  .update(pendingInbound)
3297
3585
  .set({
3586
+ // The model failed, not the delivery: the attempt recorded
3587
+ // before parsing is given back.
3588
+ attempts: job.attempts,
3589
+ unfinishedAttempts: job.unfinishedAttempts,
3298
3590
  aiAttempts,
3299
3591
  nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
3300
3592
  })
@@ -3347,7 +3639,7 @@ export class MailboxDO extends DurableObject<Env> {
3347
3639
  return;
3348
3640
  }
3349
3641
 
3350
- if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
3642
+ if (isPastRetryAge(job, now)) {
3351
3643
  const fallback = prepareUnprocessableInboundEmail({
3352
3644
  job,
3353
3645
  reason: "Message processing remained unavailable for 24 hours",
@@ -3377,6 +3669,8 @@ export class MailboxDO extends DurableObject<Env> {
3377
3669
  .update(pendingInbound)
3378
3670
  .set({
3379
3671
  attempts,
3672
+ // This attempt ended with a failure, not a killed alarm.
3673
+ unfinishedAttempts: job.unfinishedAttempts,
3380
3674
  nextAttemptAt: new Date(now + retryDelay(attempts)),
3381
3675
  })
3382
3676
  .where(eq(pendingInbound.id, job.id))
@@ -3385,6 +3679,73 @@ export class MailboxDO extends DurableObject<Env> {
3385
3679
  }
3386
3680
  }
3387
3681
 
3682
+ /**
3683
+ * Counts an attempt and backs the delivery off before it is parsed, and
3684
+ * makes that durable: when parsing gets the alarm killed (CPU or memory),
3685
+ * no catch runs, and the delivery must not stay first in line. The
3686
+ * attempt also counts as unfinished until a path with an outcome gives
3687
+ * that back (storing deletes the row; a failure restores the count).
3688
+ */
3689
+ private async recordInboundAttempt(job: PendingInbound, now: number) {
3690
+ const attempts = job.attempts + 1;
3691
+ const nextAttemptAt = now + retryDelay(attempts);
3692
+ this.db
3693
+ .update(pendingInbound)
3694
+ .set({
3695
+ attempts,
3696
+ unfinishedAttempts: job.unfinishedAttempts + 1,
3697
+ nextAttemptAt: new Date(nextAttemptAt),
3698
+ })
3699
+ .where(eq(pendingInbound.id, job.id))
3700
+ .run();
3701
+ // The retry's wake, in case this alarm never gets to schedule it.
3702
+ await this.scheduleAlarm(nextAttemptAt);
3703
+ this.attemptAlarmAt = nextAttemptAt;
3704
+ await this.state.storage.sync();
3705
+ }
3706
+
3707
+ /**
3708
+ * Stores a delivery that is not parsed again as an unreadable message,
3709
+ * with a link to its raw MIME. The delivery is backed off first, so a
3710
+ * failure here (R2 or storage) waits its turn behind newer mail.
3711
+ */
3712
+ private async storeUnparsedInbound(
3713
+ job: PendingInbound,
3714
+ now: number,
3715
+ reason: string
3716
+ ) {
3717
+ await this.recordInboundAttempt(job, now);
3718
+
3719
+ try {
3720
+ // Without an answer from R2 the link is kept: a missing object only
3721
+ // makes the download fail.
3722
+ const raw = await this.bindings.MAIL_STORAGE.head(job.rawObjectKey).then(
3723
+ (object) => object !== null,
3724
+ () => true
3725
+ );
3726
+
3727
+ const fallback = prepareUnprocessableInboundEmail({
3728
+ job,
3729
+ reason,
3730
+ rawMimeR2Key: raw ? job.rawObjectKey : null,
3731
+ });
3732
+
3733
+ const stored = await this.insertEmail(fallback);
3734
+
3735
+ if (!stored) {
3736
+ throw new Error("Unparsed inbound fallback was not persisted");
3737
+ }
3738
+
3739
+ await this.finishStoredInbound(job, stored, now, true);
3740
+ console.error(`Stored fallback for unparsed inbound delivery ${job.id}`);
3741
+ } catch (error) {
3742
+ console.error(
3743
+ `Could not store unparsed inbound delivery ${job.id}`,
3744
+ error
3745
+ );
3746
+ }
3747
+ }
3748
+
3388
3749
  private async processObjectDeletionJobs(now: number) {
3389
3750
  const jobs = this.db
3390
3751
  .select()
@@ -3439,7 +3800,8 @@ export class MailboxDO extends DurableObject<Env> {
3439
3800
  }
3440
3801
  }
3441
3802
 
3442
- private async scheduleRemainingWork() {
3803
+ /** When the earliest pending job (inbound, object deletion, Office preview) is due, or null. */
3804
+ private nextDueWork() {
3443
3805
  const nextInbound = this.db
3444
3806
  .select({ nextAttemptAt: pendingInbound.nextAttemptAt })
3445
3807
  .from(pendingInbound)
@@ -3466,13 +3828,39 @@ export class MailboxDO extends DurableObject<Env> {
3466
3828
  : [{ nextAttemptAt: new Date(officePreviewAttempt) }]),
3467
3829
  ].flatMap((job) => (job ? [job.nextAttemptAt.getTime()] : []));
3468
3830
 
3469
- const nextAttemptAt =
3470
- attemptTimes.length > 0 ? Math.min(...attemptTimes) : null;
3831
+ return attemptTimes.length > 0 ? Math.min(...attemptTimes) : null;
3832
+ }
3471
3833
 
3472
- if (nextAttemptAt !== null) {
3473
- await this.scheduleAlarm(
3474
- Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt)
3475
- );
3834
+ /**
3835
+ * Schedules the next wake for the work left. A wake set only for a parse
3836
+ * that might never finish (`recordInboundAttempt`) is replaced by the real
3837
+ * next due time, or removed when nothing is due, so a stored message does
3838
+ * not cause an empty wake. Any other alarm is only moved earlier.
3839
+ */
3840
+ private async scheduleRemainingWork() {
3841
+ const { attemptAlarmAt } = this;
3842
+ this.attemptAlarmAt = null;
3843
+ const current = await this.state.storage.getAlarm();
3844
+ // Read after the await, so nothing changes between the read and the write.
3845
+ const nextAttemptAt = this.nextDueWork();
3846
+
3847
+ const wakeAt =
3848
+ nextAttemptAt === null
3849
+ ? null
3850
+ : Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt);
3851
+
3852
+ const ownWake =
3853
+ current !== null &&
3854
+ current === attemptAlarmAt &&
3855
+ // Imported mail waits for this alarm to be announced.
3856
+ !this.state.storage.kv.get<boolean>(IMPORT_PENDING_KEY);
3857
+
3858
+ if (ownWake) {
3859
+ await (wakeAt === null
3860
+ ? this.state.storage.deleteAlarm()
3861
+ : this.state.storage.setAlarm(wakeAt));
3862
+ } else if (wakeAt !== null) {
3863
+ await this.scheduleAlarm(wakeAt);
3476
3864
  }
3477
3865
  }
3478
3866
 
@@ -3535,6 +3923,15 @@ export class MailboxDO extends DurableObject<Env> {
3535
3923
  /**
3536
3924
  * Message-ID is intentionally non-unique. Ordered header arrays decide which
3537
3925
  * locally known copy is the parent; References fall back newest-to-oldest.
3926
+ *
3927
+ * Anyone can send mail that copies a Message-ID, so among the copies of
3928
+ * one Message-ID:
3929
+ * 1. a message this mailbox sent comes first: its Message-ID is the one
3930
+ * the counterparty's reply names, and a stranger's copy of it must not
3931
+ * take that reply (into Spam, say);
3932
+ * 2. then a copy whose conversation is outside Spam and Trash, so a copy
3933
+ * in Spam is picked only when every copy is in Spam or Trash;
3934
+ * 3. then the newest.
3538
3935
  */
3539
3936
  resolveParent(inReplyTo: string[], references: string[]) {
3540
3937
  const candidates = [...new Set([...inReplyTo, ...references])];
@@ -3542,30 +3939,33 @@ export class MailboxDO extends DurableObject<Env> {
3542
3939
  if (!candidates.length) return null;
3543
3940
 
3544
3941
  const rows = this.db
3545
- .select()
3942
+ .select({ email: emails, mailboxState: conversations.mailboxState })
3546
3943
  .from(emails)
3944
+ .leftJoin(conversations, eq(conversations.id, emails.conversationId))
3547
3945
  .where(inArray(emails.messageIdHeader, candidates))
3548
3946
  .orderBy(desc(emails.timelineAt))
3549
3947
  .all();
3550
3948
 
3949
+ const rank = (row: (typeof rows)[number]) =>
3950
+ (row.email.direction === "outgoing" ? 0 : 2) +
3951
+ (row.mailboxState === "spam" || row.mailboxState === "trash" ? 1 : 0);
3952
+
3551
3953
  const byMessageId = new Map<string, (typeof rows)[number]>();
3552
3954
 
3955
+ // Rows are newest first, so a later row replaces a kept one only when it ranks better.
3553
3956
  for (const row of rows) {
3554
- if (row.messageIdHeader && !byMessageId.has(row.messageIdHeader)) {
3555
- byMessageId.set(row.messageIdHeader, row);
3556
- }
3557
- }
3957
+ const messageId = row.email.messageIdHeader;
3558
3958
 
3559
- for (const messageId of inReplyTo) {
3560
- const row = byMessageId.get(messageId);
3959
+ if (!messageId) continue;
3960
+ const kept = byMessageId.get(messageId);
3561
3961
 
3562
- if (row) return row;
3962
+ if (!kept || rank(row) < rank(kept)) byMessageId.set(messageId, row);
3563
3963
  }
3564
3964
 
3565
- for (const messageId of references.toReversed()) {
3965
+ for (const messageId of [...inReplyTo, ...references.toReversed()]) {
3566
3966
  const row = byMessageId.get(messageId);
3567
3967
 
3568
- if (row) return row;
3968
+ if (row) return row.email;
3569
3969
  }
3570
3970
 
3571
3971
  return null;