-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathoutbox-api.test.ts
More file actions
1420 lines (1267 loc) · 48.7 KB
/
outbox-api.test.ts
File metadata and controls
1420 lines (1267 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors";
import { wait } from "@stackframe/stack-shared/dist/utils/promises";
import { deindent } from "@stackframe/stack-shared/dist/utils/strings";
import { describe } from "vitest";
import { it } from "../../../../../helpers";
import { withPortPrefix } from "../../../../../helpers/ports";
import { Project, backendContext, bumpEmailAddress, getOutboxEmails, niceBackendFetch, waitForOutboxEmailWithStatus } from "../../../../backend-helpers";
const testEmailConfig = {
type: "standard",
host: "localhost",
port: Number(withPortPrefix("29")),
username: "test",
password: "test",
sender_name: "Test Project",
sender_email: "test@example.com",
} as const;
const simpleTemplate = deindent`
import { Container } from "@react-email/components";
import { Subject, NotificationCategory, Props } from "@stackframe/emails";
export function EmailTemplate({ user, project }) {
return (
<Container>
<Subject value="Test Email Subject" />
<NotificationCategory value="Marketing" />
<div>Test email content</div>
</Container>
);
}
`;
// A template that is slow to render, giving us time to pause/cancel it
const slowTemplate = deindent`
import { Container } from "@react-email/components";
import { Subject, NotificationCategory, Props } from "@stackframe/emails";
// Artificial delay to make the email slow to render
const startTime = performance.now();
while (performance.now() - startTime < 2000) {
// Busy wait - 2000ms delay
}
export function EmailTemplate({ user, project }) {
return (
<Container>
<Subject value="Slow Render Cancel Test" />
<NotificationCategory value="Transactional" />
<div>Slow email content</div>
</Container>
);
}
`;
describe("email outbox API", () => {
describe("list endpoint", () => {
it("should list emails in the outbox", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Outbox List Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly to avoid signup emails
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send an email
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>List test email</p>",
subject: "List Test Email",
notification_category_name: "Transactional",
},
});
expect(sendResponse.status).toBe(200);
// Wait for email to be processed
await wait(7_000);
// List outbox
const listResponse = await niceBackendFetch("/api/v1/emails/outbox", {
method: "GET",
accessType: "server",
});
expect(listResponse.status).toBe(200);
expect(listResponse.body.items.length).toBeGreaterThanOrEqual(1);
expect(listResponse.body.is_paginated).toBe(true);
});
it("should filter by status", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Outbox Filter Status Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send an email
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Filter test email</p>",
subject: "Filter Test Email",
notification_category_name: "Transactional",
},
});
// Wait for email to be processed
await wait(7_000);
// Filter by sent status
const sentResponse = await niceBackendFetch("/api/v1/emails/outbox?status=sent", {
method: "GET",
accessType: "server",
});
expect(sentResponse.status).toBe(200);
expect(sentResponse.body.items.every((e: any) => e.status === "sent")).toBe(true);
});
it("should filter by simple_status", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Outbox Filter Simple Status Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send an email
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Simple status test email</p>",
subject: "Simple Status Test Email",
notification_category_name: "Transactional",
},
});
// Wait for email to be processed
await wait(7_000);
// Filter by ok simple_status
const okResponse = await niceBackendFetch("/api/v1/emails/outbox?simple_status=ok", {
method: "GET",
accessType: "server",
});
expect(okResponse.status).toBe(200);
expect(okResponse.body.items.every((e: any) => e.simple_status === "ok")).toBe(true);
});
it("should return empty list for project with no emails", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Empty Outbox Project",
config: {
email_config: testEmailConfig,
},
});
const listResponse = await niceBackendFetch("/api/v1/emails/outbox", {
method: "GET",
accessType: "server",
});
expect(listResponse.status).toBe(200);
expect(listResponse.body.items).toEqual([]);
});
});
describe("get endpoint", () => {
it("should get email by id", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Outbox Get Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send an email
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Get test email</p>",
subject: "Get Test Email",
notification_category_name: "Transactional",
},
});
// Wait for email to reach sent status
const emails = await waitForOutboxEmailWithStatus("Get Test Email", "sent");
const emailId = emails[0].id;
// Get the email by ID
const getResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
expect(getResponse.status).toBe(200);
expect(getResponse.body.id).toBe(emailId);
expect(getResponse.body.status).toBe("sent");
expect(getResponse.body.simple_status).toBe("ok");
});
it("should return 404 for non-existent email", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Outbox 404 Project",
config: {
email_config: testEmailConfig,
},
});
// Use a valid UUID v4 format
const getResponse = await niceBackendFetch("/api/v1/emails/outbox/a1234567-89ab-4def-8123-456789abcdef", {
method: "GET",
accessType: "server",
});
expect(getResponse.status).toBe(404);
});
it("should return 404 for email from different project", async ({ expect }) => {
// Create first project and send an email
await Project.createAndSwitch({
display_name: "Test Outbox Project 1",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Cross project test email</p>",
subject: "Cross Project Test Email",
notification_category_name: "Transactional",
},
});
// Wait for email to reach sent status
const emails = await waitForOutboxEmailWithStatus("Cross Project Test Email", "sent");
const emailId = emails[0].id;
// Create second project
await Project.createAndSwitch({
display_name: "Test Outbox Project 2",
config: {
email_config: testEmailConfig,
},
});
// Try to get email from first project using second project's credentials
const getResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
expect(getResponse.status).toBe(404);
});
});
describe("edit endpoint - state restrictions", () => {
it("should return EMAIL_NOT_EDITABLE for sent email", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Not Editable SENT Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send and wait for completion
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Not editable test</p>",
subject: "Not Editable Test",
notification_category_name: "Transactional",
},
});
// Wait for email to reach sent status
const emails = await waitForOutboxEmailWithStatus("Not Editable Test", "sent");
const emailId = emails[0].id;
// Try to edit
const editResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: true,
},
});
expect(editResponse.status).toBe(400);
expect(editResponse.body.code).toBe("EMAIL_NOT_EDITABLE");
});
it("should return EMAIL_NOT_EDITABLE for already skipped email", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Not Editable SKIPPED Project",
config: {
email_config: testEmailConfig,
},
});
// Create user without primary email
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Send email to user without primary email (will be skipped)
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Skipped test</p>",
subject: "Skipped Test",
notification_category_name: "Transactional",
},
});
// Wait for email to reach skipped status
const emails = await waitForOutboxEmailWithStatus("Skipped Test", "skipped");
const email = emails[0];
// Try to edit
const editResponse = await niceBackendFetch(`/api/v1/emails/outbox/${email.id}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: true,
},
});
expect(editResponse.status).toBe(400);
expect(editResponse.body.code).toBe("EMAIL_NOT_EDITABLE");
});
});
describe("status discriminated union validation", () => {
it("should return correct fields for sent status with no delivery info", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test SENT Status Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Status test</p>",
subject: "Status Test Email",
notification_category_name: "Transactional",
},
});
const emails = await waitForOutboxEmailWithStatus("Status Test Email", "sent");
const email = emails[0];
// Check discriminated union fields
expect(email.status).toBe("sent");
expect(email.simple_status).toBe("ok");
expect(email.is_paused).toBe(false);
expect(email.can_have_delivery_info).toBe(false);
expect(typeof email.started_rendering_at_millis).toBe("number");
expect(typeof email.rendered_at_millis).toBe("number");
expect(typeof email.started_sending_at_millis).toBe("number");
expect(typeof email.delivered_at_millis).toBe("number");
expect(typeof email.subject).toBe("string");
expect(email.is_transactional).toBe(true);
});
it("should return correct fields for skipped status", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test SKIPPED Status Project",
config: {
email_config: testEmailConfig,
},
});
// Create user without primary email
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Skipped status test</p>",
subject: "Skipped Status Test",
notification_category_name: "Transactional",
},
});
const emails = await waitForOutboxEmailWithStatus("Skipped Status Test", "skipped");
const email = emails[0];
expect(email.status).toBe("skipped");
expect(email.simple_status).toBe("ok");
expect(email.is_paused).toBe(false);
expect(email.skipped_reason).toBe("USER_HAS_NO_PRIMARY_EMAIL");
expect(email.skipped_details).toEqual({});
});
});
describe("edit endpoint - success cases", () => {
it("should edit tsx_source and trigger re-render", async ({ expect }) => {
await Project.createAndSwitch({
display_name: "Test Edit TSX Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user directly
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Create email that will be paused immediately so we can edit it
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
html: "<p>Original content</p>",
subject: "Edit TSX Test",
notification_category_name: "Transactional",
},
});
expect(sendResponse.status).toBe(200);
// Wait for email to reach sent status
const emails = await waitForOutboxEmailWithStatus("Edit TSX Test", "sent");
const emailId = emails[0].id;
// For emails that are already SENT, we can't edit them
// So we test by confirming the error is correct
const editResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
tsx_source: simpleTemplate,
},
});
expect(editResponse.status).toBe(400);
expect(editResponse.body.code).toBe("EMAIL_NOT_EDITABLE");
});
it("should edit scheduled_at_millis to reschedule email", async ({ expect }) => {
// This test uses a slow-rendering template to reliably pause the email,
// then edits the scheduled_at_millis to verify rescheduling works.
await Project.createAndSwitch({
display_name: "Test Edit Schedule Project",
config: {
email_config: testEmailConfig,
},
});
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Create a draft with a slow-rendering template to give us time to pause
const createDraftResponse = await niceBackendFetch("/api/v1/internal/email-drafts", {
method: "POST",
accessType: "admin",
body: {
display_name: "Schedule Edit Draft",
tsx_source: slowTemplate,
theme_id: false,
},
});
expect(createDraftResponse.status).toBe(200);
const draftId = createDraftResponse.body.id;
// Send the email using the slow-rendering template
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
draft_id: draftId,
},
});
expect(sendResponse.status).toBe(200);
// Poll until we find the email and can pause it (with timeout)
let emailId: string;
for (let i = 0;; i++) {
const listResponse = await niceBackendFetch("/api/v1/emails/outbox", {
method: "GET",
accessType: "server",
});
const emails = listResponse.body.items.filter((e: any) => e.to?.user_id === userId);
if (emails.length > 0) {
emailId = emails[0].id;
// Try to pause it
const pauseResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: true,
},
});
expect(pauseResponse).toMatchInlineSnapshot(`
NiceResponse {
"status": 200,
"body": {
"created_at_millis": <stripped field 'created_at_millis'>,
"has_delivered": false,
"has_rendered": false,
"id": "<stripped UUID>",
"is_paused": true,
"next_send_retry_at_millis": null,
"scheduled_at_millis": <stripped field 'scheduled_at_millis'>,
"send_attempt_errors": null,
"send_retries": 0,
"simple_status": "in-progress",
"skip_deliverability_check": false,
"status": "paused",
"theme_id": null,
"to": {
"type": "user-primary-email",
"user_id": "<stripped UUID>",
},
"tsx_source": deindent\`
import { Container } from "@react-email/components";
import { Subject, NotificationCategory, Props } from "@stackframe/emails";
// Artificial delay to make the email slow to render
const startTime = performance.now();
while (performance.now() - startTime < 2000) {
// Busy wait - 2000ms delay
}
export function EmailTemplate({ user, project }) {
return (
<Container>
<Subject value="Slow Render Cancel Test" />
<NotificationCategory value="Transactional" />
<div>Slow email content</div>
</Container>
);
}
\`,
"updated_at_millis": <stripped field 'updated_at_millis'>,
"variables": {},
},
"headers": Headers { <some fields may have been hidden> },
}
`);
break;
} else {
if (i >= 50) {
throw new StackAssertionError(`Timeout waiting for email in the outbox`, {
outboxEmails: await getOutboxEmails(),
});
}
await wait(100);
}
}
// Now edit the scheduled_at_millis
const newScheduleTime = Date.now() + 3600000; // 1 hour from now
const editResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
scheduled_at_millis: newScheduleTime,
},
});
expect(editResponse.status).toBe(200);
expect(editResponse.body.scheduled_at_millis).toBe(newScheduleTime);
// Verify the scheduled time was updated by fetching the email
const getResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
expect(getResponse.body.scheduled_at_millis).toBe(newScheduleTime);
});
it("should update recipient via PATCH and process email correctly", async ({ expect }) => {
// This test verifies that updating the 'to' field via PATCH correctly converts
// from API format (snake_case: user_id) to DB format (camelCase: userId),
// ensuring the email worker can process the updated recipient.
await Project.createAndSwitch({
display_name: "Test Update Recipient Project",
config: {
email_config: testEmailConfig,
},
});
// Create the original user
const originalMailbox = backendContext.value.mailbox;
const createOriginalUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: originalMailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createOriginalUserResponse.status).toBe(201);
const originalUserId = createOriginalUserResponse.body.id;
// Create a second user to redirect the email to
const newMailbox = await bumpEmailAddress();
const createNewUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: newMailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createNewUserResponse.status).toBe(201);
const newUserId = createNewUserResponse.body.id;
// Create a draft with a slow-rendering template to give us time to pause
const createDraftResponse = await niceBackendFetch("/api/v1/internal/email-drafts", {
method: "POST",
accessType: "admin",
body: {
display_name: "Update Recipient Draft",
tsx_source: slowTemplate,
theme_id: false,
},
});
expect(createDraftResponse.status).toBe(200);
const draftId = createDraftResponse.body.id;
// Send the email to the original user
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [originalUserId],
draft_id: draftId,
},
});
expect(sendResponse.status).toBe(200);
// Poll until we find the email and can pause it
let emailId: string | null = null;
let pauseSucceeded = false;
for (let i = 0; i < 50; i++) {
const listResponse = await niceBackendFetch("/api/v1/emails/outbox", {
method: "GET",
accessType: "server",
});
const emails = listResponse.body.items.filter((e: any) => e.to?.user_id === originalUserId);
if (emails.length > 0 && ["preparing", "scheduled", "queued", "rendering"].includes(emails[0].status)) {
emailId = emails[0].id;
const pauseResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: true,
},
});
if (pauseResponse.status === 200 && pauseResponse.body.status === "paused") {
pauseSucceeded = true;
break;
}
}
await wait(100);
}
expect(emailId).not.toBeNull();
expect(pauseSucceeded).toBe(true);
// Update the recipient to the new user using the API format (snake_case: user_id)
const updateResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
to: {
type: "user-primary-email",
user_id: newUserId, // API format uses snake_case
},
},
});
expect(updateResponse.status).toBe(200);
expect(updateResponse.body.to.type).toBe("user-primary-email");
expect(updateResponse.body.to.user_id).toBe(newUserId);
// Unpause the email so it gets processed
const unpauseResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: false,
},
});
expect(unpauseResponse.status).toBe(200);
// Wait for the email to be sent to the new user
await newMailbox.waitForMessagesWithSubject("Slow Render Cancel Test");
// Verify the original user did NOT receive the email
const originalUserMessages = await originalMailbox.fetchMessages();
const originalUserEmails = originalUserMessages.filter(m => m.subject === "Slow Render Cancel Test");
expect(originalUserEmails).toHaveLength(0);
// Verify outbox shows sent status and correct recipient
const finalGetResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
expect(finalGetResponse.body.status).toBe("sent");
expect(finalGetResponse.body.to.user_id).toBe(newUserId);
});
it("should pause and unpause email deterministically", async ({ expect }) => {
// This test uses a slow-rendering template to reliably place the email
// into a pausable state before asserting pause/unpause behavior.
await Project.createAndSwitch({
display_name: "Test Pause Email Project",
config: {
email_config: testEmailConfig,
},
});
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Create a draft with a slow-rendering template to give us time to pause
const createDraftResponse = await niceBackendFetch("/api/v1/internal/email-drafts", {
method: "POST",
accessType: "admin",
body: {
display_name: "Pause Test Draft",
tsx_source: slowTemplate,
theme_id: false,
},
});
expect(createDraftResponse.status).toBe(200);
const draftId = createDraftResponse.body.id;
// Send the email using the slow-rendering template
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
draft_id: draftId,
},
});
expect(sendResponse.status).toBe(200);
// Poll until we find the email and can pause it (with timeout)
let emailId: string | null = null;
let pauseSucceeded = false;
for (let i = 0; i < 50; i++) {
const listResponse = await niceBackendFetch("/api/v1/emails/outbox", {
method: "GET",
accessType: "server",
});
const emails = listResponse.body.items.filter((e: any) => e.to?.user_id === userId);
if (emails.length > 0) {
emailId = emails[0].id;
// Try to pause it
const pauseResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: true,
},
});
if (pauseResponse.status === 200 && pauseResponse.body.status === "paused") {
pauseSucceeded = true;
break;
}
}
await wait(100);
}
// These assertions must always run - test fails if we couldn't pause
expect(emailId).not.toBeNull();
expect(pauseSucceeded).toBe(true);
// Verify the email is in paused state
const getResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
expect(getResponse.status).toBe(200);
expect(getResponse.body.status).toBe("paused");
expect(getResponse.body.is_paused).toBe(true);
// Unpause the email
const unpauseResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "PATCH",
accessType: "server",
body: {
is_paused: false,
},
});
expect(unpauseResponse.status).toBe(200);
expect(unpauseResponse.body.is_paused).toBe(false);
// After unpausing, the email should go back to processing (preparing/rendering/scheduled/etc)
expect(unpauseResponse.body.status).not.toBe("paused");
// Poll until the email is sent (since we unpaused it)
for (let i = 0; ; i++) {
const finalGetResponse = await niceBackendFetch(`/api/v1/emails/outbox/${emailId}`, {
method: "GET",
accessType: "server",
});
if (finalGetResponse.body.status === "sent") break;
if (i >= 50) {
throw new StackAssertionError(`Timed out waiting for email to be sent after unpause`, {
status: finalGetResponse.body.status,
});
}
await wait(500);
}
});
it("should cancel email with MANUALLY_CANCELLED reason", async ({ expect }) => {
// This test uses a slow-rendering template to give us time to pause the email,
// then reschedules it to the far future to prevent any race conditions,
// and finally cancels it to verify the cancel functionality works correctly.
await Project.createAndSwitch({
display_name: "Test Cancel Email Project",
config: {
email_config: testEmailConfig,
},
});
// Create a user with verified email
const createUserResponse = await niceBackendFetch("/api/v1/users", {
method: "POST",
accessType: "server",
body: {
primary_email: backendContext.value.mailbox.emailAddress,
primary_email_verified: true,
},
});
expect(createUserResponse.status).toBe(201);
const userId = createUserResponse.body.id;
// Create a draft with a slow-rendering template
const createDraftResponse = await niceBackendFetch("/api/v1/internal/email-drafts", {
method: "POST",
accessType: "admin",
body: {
display_name: "Slow Cancel Test Draft",
tsx_source: slowTemplate,
theme_id: false,
},
});
expect(createDraftResponse.status).toBe(200);
const draftId = createDraftResponse.body.id;
// Send the email using the slow-rendering template
const sendResponse = await niceBackendFetch("/api/v1/emails/send-email", {
method: "POST",
accessType: "server",
body: {
user_ids: [userId],
draft_id: draftId,
},
});