-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.ts
849 lines (766 loc) · 25.2 KB
/
index.ts
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
import { expect, type Page } from '@playwright/test';
import {
loginUser,
getAllRoomEvents,
getJoinedRooms,
type SynapseInstance,
sync,
} from '../docker/synapse';
import { realmPassword } from './realm-credentials';
import { registerUser } from '../docker/synapse';
import { IsolatedRealmServer } from './isolated-realm-server';
import { APP_BOXEL_MESSAGE_MSGTYPE } from './matrix-constants';
export const testHost = 'http://localhost:4202/test';
export const mailHost = 'http://localhost:5001';
export const initialRoomName = 'New AI Assistant Chat';
const realmSecretSeed = "shhh! it's a secret";
interface ProfileAssertions {
userId?: string;
displayName?: string;
email?: string;
}
interface LoginOptions {
url?: string;
expectFailure?: true;
skipOpeningAssistant?: true;
}
export async function registerRealmUsers(synapse: SynapseInstance) {
await registerUser(
synapse,
'base_realm',
await realmPassword('base_realm', realmSecretSeed),
);
await registerUser(
synapse,
'experiments_realm',
await realmPassword('experiments_realm', realmSecretSeed),
);
await registerUser(
synapse,
'seed_realm',
await realmPassword('seed_realm', realmSecretSeed),
);
await registerUser(
synapse,
'catalog_realm',
await realmPassword('catalog_realm', realmSecretSeed),
);
await registerUser(
synapse,
'test_realm',
await realmPassword('test_realm', realmSecretSeed),
);
await registerUser(
synapse,
'node-test_realm',
await realmPassword('node-test_realm', realmSecretSeed),
);
await registerUser(
synapse,
'realm_server',
await realmPassword('realm_server', realmSecretSeed),
);
}
export async function reloadAndOpenAiAssistant(page: Page) {
await page.reload();
await openAiAssistant(page);
}
export async function openAiAssistant(page: Page) {
await page.locator('[data-test-open-ai-assistant]').click();
await expect(page.locator('[data-test-close-ai-assistant]')).toHaveCount(1);
await expect(page.locator('[data-test-room]')).toHaveCount(1);
}
export async function createRealm(
page: Page,
endpoint: string,
name = endpoint,
copyFromSeed = true,
) {
await page.locator('[data-test-add-workspace]').click();
await page.locator('[data-test-display-name-field]').fill(name);
await page.locator('[data-test-endpoint-field]').fill(endpoint);
if (!copyFromSeed) {
await page.locator('[data-test-copy-from-seed-field]').click();
}
await page.locator('[data-test-create-workspace-submit]').click();
await expect(page.locator(`[data-test-workspace="${name}"]`)).toBeVisible();
await expect(page.locator('[data-test-create-workspace-modal]')).toHaveCount(
0,
);
}
export async function openRoot(page: Page, url = testHost) {
await page.goto(url);
}
export async function clearLocalStorage(page: Page, appURL = testHost) {
await openRoot(page, appURL);
await page.evaluate(() => window.localStorage.clear());
}
export async function validateEmail(
appPage: Page,
email: string,
opts?: {
onEmailPage?: (page: Page) => Promise<void>;
onValidationPage?: (page: Page) => Promise<void>;
sendAttempts?: number;
isLoggedInWhenValidated?: true;
onAppTrigger?: (page: Page) => Promise<void>;
},
) {
let sendAttempts = opts?.sendAttempts ?? 1;
if (opts?.onAppTrigger) {
await opts.onAppTrigger(appPage);
} else {
await expect(appPage.locator('[data-test-email-validation]')).toContainText(
'Please check your email to complete registration.',
);
}
for (let i = 0; i < sendAttempts - 1; i++) {
await appPage.waitForTimeout(500);
await appPage.locator('[data-test-resend-validation]').click();
}
let context = appPage.context();
let emailPage = await context.newPage();
await emailPage.goto(mailHost);
await expect(
emailPage.locator('.messagelist .unread').filter({ hasText: email }),
).toHaveCount(sendAttempts);
await emailPage
.locator('.messagelist .unread')
.filter({ hasText: email })
.first()
.click();
await expect(
emailPage.frameLocator('.messageview iframe').locator('body'),
).toContainText('Verify Email');
await expect(
emailPage.locator('.messageview .messageviewheader'),
).toContainText(`To:${email}`);
if (opts?.onEmailPage) {
await opts.onEmailPage(emailPage);
}
const validationPagePromise = context.waitForEvent('page');
let textBtn = emailPage
.frameLocator('.messageview iframe')
.getByText('Verify Email');
// We have to delay before going to validation window
// to avoid the validation window won't open
await emailPage.waitForTimeout(500);
await textBtn.click();
const validationPage = await validationPagePromise;
await validationPage.waitForLoadState();
if (opts?.onValidationPage) {
await opts.onValidationPage(validationPage);
}
}
export async function validateEmailForResetPassword(
appPage: Page,
email: string,
opts?: {
onEmailPage?: (page: Page) => Promise<void>;
onValidationPage?: (page: Page) => Promise<void>;
sendAttempts?: number;
isLoggedInWhenValidated?: true;
},
): Promise<Page> {
let sendAttempts = opts?.sendAttempts ?? 1;
await expect(appPage.locator('[data-test-email-validation]')).toContainText(
'Please check your email to reset your password',
);
for (let i = 0; i < sendAttempts - 1; i++) {
await appPage.waitForTimeout(500);
await appPage.locator('[data-test-resend-validation-btn]').click();
}
let context = appPage.context();
let emailPage = await context.newPage();
await emailPage.goto(mailHost);
await expect(
emailPage.locator('.messagelist .unread').filter({ hasText: email }),
).toHaveCount(sendAttempts);
await emailPage
.locator('.messagelist .unread')
.filter({ hasText: email })
.first()
.click();
await expect(
emailPage.frameLocator('.messageview iframe').locator('body'),
).toContainText('Reset Password');
await expect(
emailPage.locator('.messageview .messageviewheader'),
).toContainText(`To:${email}`);
if (opts?.onEmailPage) {
await opts.onEmailPage(emailPage);
}
const pagePromise = context.waitForEvent('page');
let btn = emailPage
.frameLocator('.messageview iframe')
.getByText('Reset Password')
.last();
// We have to delay before going to validation window
// to avoid the validation window won't open
await emailPage.waitForTimeout(500);
await btn.click();
const validationPage = await pagePromise;
await validationPage.waitForLoadState();
if (opts?.onValidationPage) {
await opts.onValidationPage(validationPage);
}
let validationBtn = validationPage
.locator('body')
.getByText('Confirm changing my password');
await validationPage.waitForTimeout(500);
await validationBtn.click();
const resetPasswordPage = await pagePromise;
await resetPasswordPage.waitForLoadState();
return resetPasswordPage;
}
export async function gotoRegistration(page: Page, appURL = testHost) {
await openRoot(page, appURL);
await page.locator('[data-test-register-user]').click();
await expect(page.locator('[data-test-register-btn]')).toHaveCount(1);
}
export async function gotoForgotPassword(page: Page, appURL = testHost) {
await openRoot(page, appURL);
await page.locator('[data-test-forgot-password]').click();
await expect(page.locator('[data-test-reset-your-password-btn]')).toHaveCount(
1,
);
}
export async function login(
page: Page,
username: string,
password: string,
opts?: LoginOptions,
) {
await openRoot(page, opts?.url);
await expect(page.locator('[data-test-username-field]')).toBeEditable();
await page.locator('[data-test-username-field]').fill(username);
await page.locator('[data-test-password-field]').fill(password);
await page.locator('[data-test-login-btn]').click();
if (opts?.expectFailure) {
await expect(page.locator('[data-test-login-error]')).toHaveCount(1);
} else {
if (!opts?.skipOpeningAssistant) {
await openAiAssistant(page);
}
}
}
export async function enterWorkspace(
page: Page,
workspace = 'Test Workspace A',
) {
await expect(page.locator('[data-test-workspace-chooser]')).toHaveCount(1);
await expect(
page.locator(`[data-test-workspace="${workspace}"]`),
).toHaveCount(1);
await page.locator(`[data-test-workspace="${workspace}"]`).click();
await expect(
page.locator(
`[data-test-stack-card-index="0"] [data-test-boxel-card-header-title]`,
),
).toContainText(workspace);
}
export async function showAllCards(page: Page) {
await expect(
page.locator(`[data-test-boxel-filter-list-button="All Cards"]`),
).toHaveCount(1);
await page
.locator(`[data-test-boxel-filter-list-button="All Cards"]`)
.click();
}
export async function logout(page: Page) {
await page.locator('[data-test-profile-icon-button]').click();
await page.locator('[data-test-signout-button]').click();
await expect(page.locator('[data-test-login-btn]')).toHaveCount(1);
}
export async function createRoom(page: Page) {
await page.locator('[data-test-create-room-btn]').click();
let roomId = await getRoomId(page);
await isInRoom(page, roomId);
return roomId;
}
export async function createRoomWithMessage(page: Page, message?: string) {
let roomId = await createRoom(page);
await sendMessage(page, roomId, message ?? 'Hello, world!');
return roomId;
}
export async function getRoomId(page: Page) {
await page.locator(`[data-test-room-settled]`).waitFor();
let roomId = await page
.locator('[data-test-room]')
.getAttribute('data-test-room');
if (roomId == null) {
throw new Error('room ID is not found');
}
return roomId;
}
export async function isInRoom(page: Page, roomId: string) {
await page.locator(`[data-test-room="${roomId}"]`).waitFor();
await expect(page.locator(`[data-test-room-settled]`)).toHaveCount(1);
}
export async function deleteRoom(page: Page, roomId: string) {
await page.locator(`[data-test-past-sessions-button]`).click();
// Here, past sessions could be rerendered because in one case we're creating a new room when opening an AI panel, so we need to wait for the past sessions to settle
await page.waitForTimeout(500);
await page
.locator(`[data-test-past-session-options-button="${roomId}"]`)
.click();
await page.locator(`[data-test-boxel-menu-item-text="Delete"]`).click();
await page
.locator(
`[data-test-delete-modal-container] [data-test-confirm-delete-button]`,
)
.click();
}
export async function openRoom(page: Page, roomId: string) {
await page.locator(`[data-test-past-sessions-button]`).click(); // toggle past sessions on
await page.locator(`[data-test-enter-room="${roomId}"]`).click();
await isInRoom(page, roomId);
}
export async function openRenameMenu(page: Page, roomId: string) {
await page.locator(`[data-test-past-sessions-button]`).click();
await page.waitForTimeout(500); // without this, the click on the options button result in the menu staying open
await page
.locator(`[data-test-past-session-options-button="${roomId}"]`)
.click();
await expect(
page.locator(`[data-test-boxel-menu-item-text="Rename"]`),
).toHaveCount(1);
await page.locator(`[data-test-boxel-menu-item-text="Rename"]`).click();
await page.locator(`[data-test-name-field]`).waitFor();
}
export async function writeMessage(
page: Page,
roomId: string,
message: string,
) {
await page.locator(`[data-test-message-field="${roomId}"]`).fill(message);
await expect(
page.locator(`[data-test-message-field="${roomId}"]`),
).toHaveValue(message);
}
export async function selectCardFromCatalog(
page: Page,
cardId: string,
realmName = 'Test Workspace A',
) {
await page.locator('[data-test-choose-card-btn]').click();
await page
.locator(`[data-test-realm="${realmName}"] [data-test-show-more-cards]`)
.click();
await page
.locator(`[data-test-realm="${realmName}"] [data-test-show-more-cards]`)
.click();
await page.locator(`[data-test-select="${cardId}"]`).click();
await page.locator('[data-test-card-catalog-go-button]').click();
}
export async function setupTwoStackItems(
page: Page,
leftStackTopCardId: string,
rightStackTopCardId: string,
) {
await page
.locator(
`[data-test-stack-item-content] [data-test-cards-grid-item='${rightStackTopCardId}']`,
)
.click();
await page
.locator(
`[data-test-stack-card='${rightStackTopCardId}'] [data-test-close-button]`,
)
.click();
await page
.locator(
`[data-test-stack-item-content] [data-test-cards-grid-item='${leftStackTopCardId}']`,
)
.click();
await page.locator('[data-test-add-card-right-stack]').click();
await page
.locator(`[data-test-search-result="${rightStackTopCardId}"]`)
.click();
}
export async function sendMessage(
page: Page,
roomId: string,
message: string | undefined,
cardIds?: string[],
) {
if (message == null && cardIds == null) {
throw new Error(
`sendMessage requires at least a message or a card ID be specified`,
);
}
if (message != null) {
await writeMessage(page, roomId, message);
}
if (cardIds?.length) {
for (let cardId of cardIds) {
await selectCardFromCatalog(page, cardId);
}
}
// can we check it's higher than before?
await page.waitForSelector(`[data-test-room-settled]`);
await page.waitForSelector(`[data-test-can-send-msg]`);
await page.locator('[data-test-send-message-btn]').click();
}
export async function assertMessages(
page: Page,
messages: {
from: string;
message?: string;
cards?: { id: string; title?: string; realmIconUrl?: string }[];
files?: { name: string; sourceUrl: string }[];
}[],
) {
await expect(page.locator('[data-test-message-idx]')).toHaveCount(
messages.length,
);
for (let [index, { from, message, cards, files }] of messages.entries()) {
await expect(
page.locator(
`[data-test-message-idx="${index}"][data-test-boxel-message-from="${from}"]`,
),
).toHaveCount(1);
if (message != null) {
await expect(
page.locator(`[data-test-message-idx="${index}"] .content`),
).toContainText(message);
}
if (cards?.length) {
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-message-items]`,
),
).toHaveCount(1);
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-attached-card]`,
),
).toHaveCount(cards.length);
for (let card of cards) {
if (card.title) {
if (message != null && card.title.includes(message)) {
throw new Error(
`This is not a good test since the message '${message}' overlaps with the asserted card text '${card.title}'`,
);
}
// note: attached cards are in atom format (which display the title by default)
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-attached-card="${card.id}"]`,
),
).toContainText(card.title);
}
if (card.realmIconUrl) {
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-attached-card="${card.id}"] [data-test-realm-icon-url="${card.realmIconUrl}"]`,
),
).toHaveCount(1);
}
}
}
if (files?.length) {
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-message-items]`,
),
).toHaveCount(1);
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-attached-file]`,
),
).toHaveCount(files.length);
files.map(async (file) => {
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-attached-file="${file.sourceUrl}"]`,
),
).toContainText(file.name);
});
}
if (!files?.length && !cards?.length) {
await expect(
page.locator(
`[data-test-message-idx="${index}"] [data-test-message-items]`,
),
).toHaveCount(0);
}
}
}
export async function assertRooms(page: Page, rooms: string[]) {
await page.locator(`[data-test-past-sessions-button]`).click(); // toggle past sessions on
if (rooms && rooms.length > 0) {
await page.waitForFunction(
(rooms) =>
document.querySelectorAll('[data-test-joined-room]').length ===
rooms.length,
rooms,
);
await Promise.all(
rooms.map((name) =>
expect(
page.locator(`[data-test-joined-room="${name}"]`),
`the joined room '${name}' is displayed`,
).toHaveCount(1),
),
);
} else {
await expect(
page.locator('[data-test-joined-room]'),
`joined rooms are not displayed`,
).toHaveCount(0);
}
await page.locator(`[data-test-close-past-sessions]`).click();
}
export async function assertLoggedIn(page: Page, opts?: ProfileAssertions) {
await page.locator('[data-test-profile-icon-button]').click();
await expect(
page.locator('[data-test-username-field]'),
'username field is not displayed',
).toHaveCount(0);
await expect(
page.locator('[data-test-password-field]'),
'password field is not displayed',
).toHaveCount(0);
await expect(page.locator('[data-test-profile-display-name]')).toContainText(
opts?.displayName ?? 'user1',
);
await expect(page.locator('[data-test-profile-icon-handle]')).toContainText(
opts?.userId ?? '@user1:localhost',
);
if (opts?.email) {
await page.locator('[data-test-settings-button]').click();
await expect(page.locator('[data-test-current-email]')).toContainText(
opts.email,
);
await page.locator('[data-test-confirm-cancel-button]').click(); // close settings modal + popover
} else {
await page.locator('[data-test-profile-icon-button]').click(); // close profile popover
}
}
export async function setupUser(
username: string,
realmServer: IsolatedRealmServer,
) {
await realmServer.executeSQL(
`INSERT INTO users (matrix_user_id) VALUES ('${username}')`,
);
}
export async function assertPaymentLink(
page: Page,
{ username, email }: { username: string; email: string },
) {
const paymentLink =
(await page.locator('[data-test-setup-payment]').getAttribute('href')) ??
'';
const queryString = paymentLink.split('?')[1];
const params = new Map(
queryString.split('&').map((param) => {
const [key, value] = param.split('=');
return [key, value];
}),
);
const clientReferenceId = params.get('client_reference_id');
expect(clientReferenceId).toBe(encodeWebSafeBase64(username));
const emailFromUrl = params.get('prefilled_email');
expect(emailFromUrl).toBe(encodeURIComponent(email));
}
export async function setupPayment(
username: string,
realmServer: IsolatedRealmServer,
page?: Page,
) {
// decode the username from base64
const decodedUsername = decodeFromAlphanumeric(username);
// mock trigger stripe webhook 'checkout.session.completed'
let freePlan = await realmServer.executeSQL(
`SELECT * FROM plans WHERE name = 'Free'`,
);
const randomNumber = Math.random().toString(36).substring(2, 12);
let subscriptionId = `sub_${randomNumber}`;
let stripeCustomerId = `cus_${randomNumber}`;
await realmServer.executeSQL(
`UPDATE users SET stripe_customer_id = '${stripeCustomerId}' WHERE matrix_user_id = '${decodedUsername}'`,
);
let findUser = await realmServer.executeSQL(
`SELECT * FROM users WHERE matrix_user_id = '${decodedUsername}'`,
);
const userId = findUser[0].id;
const now = Math.floor(Date.now() / 1000); // Current time in seconds
const oneYearFromNow = now + 31536000; // One year in seconds
const oneMonthFromNow = now + 2592000; // One month in seconds
// mock trigger stripe webhook 'invoice.payment_succeeded'
await realmServer.executeSQL(
`INSERT INTO subscriptions (
user_id,
plan_id,
started_at,
ended_at,
status,
stripe_subscription_id
) VALUES (
'${userId}',
'${freePlan[0].id}',
${now},
${oneYearFromNow},
'active',
'${subscriptionId}'
)`,
);
const getSubscription = await realmServer.executeSQL(
`SELECT id FROM subscriptions WHERE stripe_subscription_id = '${subscriptionId}'`,
);
const subscriptionUUID = getSubscription[0].id;
await realmServer.executeSQL(
`INSERT INTO subscription_cycles (
subscription_id,
period_start,
period_end
) VALUES (
'${subscriptionUUID}',
${now},
${oneMonthFromNow}
)`,
);
let subscriptionCycle = await realmServer.executeSQL(
`SELECT id FROM subscription_cycles WHERE subscription_id = '${subscriptionUUID}'`,
);
const subscriptionCycleUUID = subscriptionCycle[0].id;
await realmServer.executeSQL(
`INSERT INTO credits_ledger (user_id, credit_amount, credit_type, subscription_cycle_id) VALUES ('${userId}', ${freePlan[0].credits_included}, 'plan_allowance', '${subscriptionCycleUUID}')`,
);
// Return url example: https://realms-staging.stack.cards/?from-free-plan-payment-link=true
// extract return url from page.url()
// assert return url contains ?from-free-plan-payment-link=true
if (page) {
const currentUrl = new URL(page.url());
const currentParams = currentUrl.searchParams;
await currentParams.append('from-free-plan-payment-link', 'true');
const returnUrl = `${currentUrl.origin}${
currentUrl.pathname
}?${currentParams.toString()}`;
await page.goto(returnUrl);
}
}
export async function setupUserSubscribed(
username: string,
realmServer: IsolatedRealmServer,
) {
const matrixUserId = encodeWebSafeBase64(username);
await setupUser(username, realmServer);
await setupPayment(matrixUserId, realmServer);
}
export async function assertLoggedOut(page: Page) {
await expect(
page.locator('[data-test-username-field]'),
'username field is displayed',
).toHaveCount(1);
await expect(
page.locator('[data-test-password-field]'),
'password field is displayed',
).toHaveCount(1);
await expect(
page.locator('[data-test-field-value="userId"]'),
'user profile - user ID is not displayed',
).toHaveCount(0);
await expect(
page.locator('[data-test-field-value="displayName"]'),
'user profile - display name is not displayed',
).toHaveCount(0);
}
export async function getRoomEvents(
username = 'user1',
password = 'pass',
roomId?: string,
) {
let { accessToken } = await loginUser(username, password);
let rooms = await getJoinedRooms(accessToken);
if (!roomId) {
let roomsWithEvents = await Promise.all(
rooms.map((r) => getAllRoomEvents(r, accessToken)),
);
// there will generally be 2 rooms, one is the DM room we do for
// authentication, the other is the actual chat (with app.boxel.message events)
return (
roomsWithEvents.find((messages) => {
return messages.find(
(message) =>
message.type === 'm.room.message' &&
message.content?.msgtype === APP_BOXEL_MESSAGE_MSGTYPE,
);
}) ?? []
);
}
return await getAllRoomEvents(roomId, accessToken);
}
export async function getRoomsFromSync(username = 'user1', password = 'pass') {
let { accessToken } = await loginUser(username, password);
let response = (await sync(accessToken)) as any;
return response.rooms;
}
export async function waitUntil<T>(
condition: () => Promise<T>,
timeout = 10000,
interval = 250,
): Promise<T> {
const start = Date.now();
while (Date.now() - start < timeout) {
const result = await condition();
if (result) {
return result;
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
throw new Error('Timeout waiting for condition');
}
export function encodeWebSafeBase64(string: string) {
return Buffer.from(string)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, ''); // Remove padding
}
export function decodeFromAlphanumeric(encodedString: string) {
const base64 = encodedString.replace(/-/g, '+').replace(/_/g, '/');
return Buffer.from(base64, 'base64').toString('utf8');
}
export function getSearchTool() {
return {
type: 'function',
function: {
name: 'searchCardsByTypeAndTitle',
description:
'Propose a query to search for card instances filtered by type. If a card was shared with you, always prioritise search based upon the card that was last shared. If you do not have information on card module and name, do the search using the `cardType` attribute.',
parameters: {
type: 'object',
properties: {
description: {
type: 'string',
},
attributes: {
type: 'object',
properties: {
title: {
type: 'string',
description: 'title of the card',
},
cardType: {
type: 'string',
description: 'name of the card type',
},
type: {
type: 'object',
description: 'CodeRef of the card type',
properties: {
module: { type: 'string' },
name: { type: 'string' },
},
},
},
},
},
required: ['attributes', 'description'],
},
},
};
}